1 /******************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
29 #include "cainterface.h"
30 #include "oic_malloc.h"
32 #include "ocsecurityconfig.h"
35 #define MAX_BUF_LEN 1024
36 #define MAX_OPT_LEN 16
40 #define SECURE_DEFAULT_PORT 5684
42 #define RESOURCE_URI_LENGTH 14
44 #define SYSTEM_INVOKE_ERROR 127
45 #define SYSTEM_ERROR -1
47 #define COAP_PREFIX "coap://"
48 #define COAP_PREFIX_LEN 7
49 #define COAPS_PREFIX "coaps://"
50 #define COAPS_PREFIX_LEN 8
56 #define IDENTITY ("1111111111111111")
60 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
63 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
64 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
65 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
69 char ipAddress[CA_IPADDR_SIZE];
75 CAResult_t get_network_type();
76 CAResult_t get_input_data(char *buf, int32_t length);
78 void start_listening_server();
79 void start_discovery_server();
81 void send_request_all();
82 void send_notification();
83 void select_network();
84 void unselect_network();
85 void handle_request_response();
86 void get_network_info();
87 void send_secure_request();
89 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
90 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
91 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
92 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
93 void get_resource_uri(char *URI, char *resourceURI, int length);
94 int get_secure_information(CAPayload_t payLoad);
95 int get_address_set(const char *pAddress, addressSet_t* outAddress);
96 void parsing_coap_uri(const char* uri, addressSet_t* address);
98 static CAToken_t g_last_request_token = NULL;
99 static const char SECURE_COAPS_PREFIX[] = "coaps://";
100 static const char SECURE_INFO_DATA[] =
101 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
102 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
104 static const char NORMAL_INFO_DATA[] =
105 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
106 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
109 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
111 void clearDtlsCredentialInfo()
113 printf("clearDtlsCredentialInfo IN\n");
116 // Initialize sensitive data to zeroes before freeing.
117 if (pskCredsBlob->creds)
119 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
120 free(pskCredsBlob->creds);
123 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
127 printf("clearDtlsCredentialInfo OUT\n");
130 // Internal API. Invoked by CA stack to retrieve credentials from this module
131 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
133 printf("CAGetDtlsPskCredentials IN\n");
136 printf("Invalid credential container");
140 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
141 if (NULL == *credInfo)
143 printf("Failed to allocate credential blob.");
147 size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
148 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
149 if (NULL == (*credInfo)->creds)
151 printf("Failed to allocate credentials.");
157 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
158 (*credInfo)->num = pskCredsBlob->num;
159 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
161 printf("CAGetDtlsPskCredentials OUT\n");
165 CAResult_t SetCredentials()
167 printf("SetCredentials IN\n");
168 pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
169 if (NULL == pskCredsBlob)
171 printf("Memory allocation failed!\n");
172 return CA_MEMORY_ALLOC_FAILED;
174 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
177 pskCredsBlob->num = 1;
179 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
180 if (NULL == pskCredsBlob->creds)
182 printf("Memory allocation failed!\n");
184 return CA_MEMORY_ALLOC_FAILED;
187 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
188 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
190 printf("SetCredentials OUT\n");
197 int ret = system("clear");
198 // shell invoke error: 127, others: -1
199 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
201 printf("Terminal Clear Error: %d\n", ret);
205 printf("=============================================\n");
206 printf("\t\tsample main\n");
207 printf("=============================================\n");
209 CAResult_t res = CAInitialize();
210 if (CA_STATUS_OK != res)
212 printf("CAInitialize fail\n");
217 * Read DTLS PSK credentials from persistent storage and
218 * set in the OC stack.
221 res = SetCredentials();
222 if (CA_STATUS_OK != res)
224 printf("SetCredentials failed\n");
228 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
229 if (CA_STATUS_OK != res)
231 printf("Set credential handler fail\n");
237 CARegisterHandler(request_handler, response_handler, error_handler);
241 CADestroyToken(g_last_request_token);
243 g_last_request_token = NULL;
247 clearDtlsCredentialInfo();
256 char menu = get_menu();
266 printf("quit..!!\n");
269 case 's': // start server
271 start_listening_server();
274 case 't': // send request
279 case 'c': // start client
281 start_discovery_server();
284 case 'r': // send request
289 case 'b': // send notification
294 case 'n': // select network
299 case 'x': // unselect network
304 case 'h': // handle request response
306 handle_request_response();
312 start_discovery_server();
313 send_secure_request();
314 while (g_received == 0)
317 handle_request_response();
323 start_listening_server();
327 handle_request_response();
331 case 'g': // get network information
337 printf("not supported menu!!\n");
343 void start_listening_server()
345 printf("start listening server!!\n");
347 CAResult_t res = CAStartListeningServer();
348 if (CA_STATUS_OK != res)
350 printf("start listening server fail, error code : %d\n", res);
354 printf("start listening server success\n");
358 void start_discovery_server()
360 printf("start discovery client!!\n");
362 CAResult_t res = CAStartDiscoveryServer();
363 if (CA_STATUS_OK != res)
365 printf("start discovery client fail, error code : %d\n", res);
369 printf("start discovery client success\n");
375 CAResult_t res = get_network_type();
376 if (CA_STATUS_OK != res)
381 printf("Do you want to send secure request ?.... enter (0/1): ");
383 char secureRequest[MAX_BUF_LEN] = {0};
384 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
389 if (strcmp(secureRequest, "1") == 0)
391 printf("Enter the URI like below....\n");
392 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
394 else if (strcmp(secureRequest, "0") == 0)
396 printf("Enter the URI like below....\n");
397 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
398 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
402 printf("Input data is wrong value\n");
406 char uri[MAX_BUF_LEN] = {'\0'};
407 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
412 // create remote endpoint
413 CAEndpoint_t *endpoint = NULL;
415 printf("URI : %s\n", uri);
416 addressSet_t address = {};
417 parsing_coap_uri(uri, &address);
419 res = CACreateEndpoint(CA_DEFAULT_FLAGS, g_selected_nw_type,
420 (const char*)address.ipAddress, address.port, &endpoint);
421 if (CA_STATUS_OK != res || !endpoint)
423 printf("Failed to create remote endpoint, error code : %d\n", res);
427 printf("\n=============================================\n");
428 printf("0:CON, 1:NON\n");
429 printf("select message type : ");
431 char buf[MAX_BUF_LEN] = { 0 };
432 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
434 CADestroyEndpoint(endpoint);
438 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
441 CAToken_t token = NULL;
442 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
444 res = CAGenerateToken(&token, tokenLength);
445 if ((CA_STATUS_OK != res) || (!token))
447 printf("Token generate error, error code : %d\n", res);
448 CADestroyEndpoint(endpoint);
452 printf("Generated token %s\n", token);
454 // extract relative resourceuri from give uri
455 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
456 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
457 printf("resourceURI : %s\n", resourceURI);
459 // create request data
460 CAInfo_t requestData = { 0 };
461 requestData.token = token;
462 requestData.tokenLength = tokenLength;
463 requestData.resourceUri = (CAURI_t)resourceURI;
465 if (strcmp(secureRequest, "1") == 0)
467 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
468 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
469 if (NULL == requestData.payload)
471 printf("Memory allocation fail\n");
472 CADestroyEndpoint(endpoint);
473 CADestroyToken(token);
476 snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
480 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
481 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
482 if (NULL == requestData.payload)
484 printf("Memory allocation fail\n");
485 CADestroyEndpoint(endpoint);
486 CADestroyToken(token);
489 snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
491 requestData.type = msgType;
493 CARequestInfo_t requestInfo = { 0 };
494 requestInfo.method = CA_GET;
495 requestInfo.info = requestData;
496 requestInfo.isMulticast = false;
499 res = CASendRequest(endpoint, &requestInfo);
500 if (CA_STATUS_OK != res)
502 printf("Could not send request : %d\n", res);
506 CADestroyToken(token);
507 // destroy remote endpoint
508 CADestroyEndpoint(endpoint);
509 free(requestData.payload);
512 printf("=============================================\n");
515 void send_secure_request()
517 char uri[MAX_BUF_LEN];
518 char ipv4addr[CA_IPADDR_SIZE];
520 printf("\n=============================================\n");
521 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
523 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
527 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
529 // create remote endpoint
530 CAEndpoint_t *endpoint = NULL;
531 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
532 if (CA_STATUS_OK != res)
534 printf("Failed to create remote endpoint, error code: %d\n", res);
539 CAToken_t token = NULL;
540 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
542 res = CAGenerateToken(&token, tokenLength);
543 if ((CA_STATUS_OK != res) || (!token))
545 printf("Token generate error, error code : %d\n", res);
549 printf("Generated token %s\n", token);
551 // create request data
552 CAMessageType_t msgType = CA_MSG_NONCONFIRM;
553 CAInfo_t requestData = { 0 };
554 requestData.token = token;
555 requestData.tokenLength = tokenLength;
556 requestData.type = msgType;
558 CARequestInfo_t requestInfo = { 0 };
559 requestInfo.method = CA_GET;
560 requestInfo.info = requestData;
561 requestInfo.isMulticast = false;
564 CASendRequest(endpoint, &requestInfo);
568 CADestroyToken(token);
569 CADestroyEndpoint(endpoint);
570 printf("=============================================\n");
574 void send_request_all()
576 CAResult_t res = get_network_type();
577 if (CA_STATUS_OK != res)
582 printf("\n=============================================\n");
583 printf("ex) /a/light\n");
584 printf("resource uri : ");
586 char resourceURI[MAX_BUF_LEN] = { 0 };
587 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
592 // create remote endpoint
593 CAEndpoint_t *endpoint = NULL;
594 res = CACreateEndpoint(0, g_selected_nw_type, NULL, 0, &endpoint);
595 if (CA_STATUS_OK != res)
597 printf("Create remote endpoint error, error code: %d\n", res);
601 CAEndpoint_t *group = (CAEndpoint_t *) malloc(sizeof(CAEndpoint_t));
604 printf("Memory allocation failed!\n");
605 CADestroyEndpoint(endpoint);
608 group->adapter = endpoint->adapter;
611 CAToken_t token = NULL;
612 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
614 res = CAGenerateToken(&token, tokenLength);
615 if ((CA_STATUS_OK != res) || (!token))
617 printf("Token generate error!!\n");
618 CADestroyEndpoint(endpoint);
623 printf("generated token %s\n", token);
625 CAInfo_t requestData = { 0 };
626 requestData.token = token;
627 requestData.tokenLength = tokenLength;
628 requestData.payload = "Temp Json Payload";
629 requestData.type = CA_MSG_NONCONFIRM;
630 requestData.resourceUri = (CAURI_t)resourceURI;
632 CARequestInfo_t requestInfo = { 0 };
633 requestInfo.method = CA_GET;
634 requestInfo.info = requestData;
635 requestInfo.isMulticast = true;
638 res = CASendRequest(group, &requestInfo);
639 if (CA_STATUS_OK != res)
641 printf("Could not send request to all\n");
642 CADestroyToken(token);
646 CADestroyToken(g_last_request_token);
647 g_last_request_token = token;
650 // destroy remote endpoint
651 CADestroyEndpoint(endpoint);
654 printf("=============================================\n");
657 void send_notification()
659 CAResult_t res = get_network_type();
660 if (CA_STATUS_OK != res)
665 printf("\n=============================================\n");
666 printf("Enter the URI like below....\n");
667 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
668 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
671 char uri[MAX_BUF_LEN] = { 0 };
672 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
677 printf("\n=============================================\n");
678 printf("\tselect message type\n");
682 printf("RESET : 3\n");
685 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
686 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
691 int messageType = messageTypeBuf[0] - '0';
693 addressSet_t address = {};
694 parsing_coap_uri(uri, &address);
696 // create remote endpoint
697 CAEndpoint_t *endpoint = NULL;
698 res = CACreateEndpoint(0, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
699 if (CA_STATUS_OK != res)
701 printf("Create remote endpoint error, error code: %d\n", res);
706 CAToken_t token = NULL;
707 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
709 res = CAGenerateToken(&token, tokenLength);
710 if ((CA_STATUS_OK != res) || (!token))
712 printf("Token generate error!!\n");
713 CADestroyEndpoint(endpoint);
717 printf("Generated token %s\n", token);
719 CAInfo_t respondData = { 0 };
720 respondData.token = token;
721 respondData.tokenLength = tokenLength;
722 respondData.payload = "Temp Notification Data";
723 respondData.type = messageType;
724 respondData.resourceUri = (CAURI_t)uri;
726 CAResponseInfo_t responseInfo = { 0 };
727 responseInfo.result = CA_CONTENT;
728 responseInfo.info = respondData;
731 res = CASendNotification(endpoint, &responseInfo);
732 if (CA_STATUS_OK != res)
734 printf("Send notification error, error code: %d\n", res);
738 printf("Send notification success\n");
742 CADestroyToken(token);
743 // destroy remote endpoint
744 CADestroyEndpoint(endpoint);
746 printf("\n=============================================\n");
749 void select_network()
751 printf("\n=============================================\n");
752 printf("\tselect network\n");
754 printf("GATT : 1\n");
755 printf("RFCOMM : 2\n");
758 char buf[MAX_BUF_LEN] = { 0 };
759 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
764 int number = buf[0] - '0';
766 if (number < 0 || number > 3)
768 printf("Invalid network type\n");
772 CAResult_t res = CASelectNetwork(1 << number);
773 if (CA_STATUS_OK != res)
775 printf("Select network error\n");
779 printf("Select network success\n");
782 printf("=============================================\n");
785 void unselect_network()
787 printf("\n=============================================\n");
788 printf("\tunselect enabled network\n");
790 printf("GATT : 1\n");
791 printf("RFCOMM : 2\n");
794 char buf[MAX_BUF_LEN] = { 0 };
795 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
800 int number = buf[0] - '0';
802 if (number < 0 || number > 3)
804 printf("Invalid network type\n");
808 CAResult_t res = CAUnSelectNetwork(1 << number);
809 if (CA_STATUS_OK != res)
811 printf("Unselect network error\n");
815 printf("Unselect network success\n");
818 printf("=============================================\n");
823 printf("\n=============================================\n");
824 printf("\t\tMenu\n");
825 printf("\ts : start server\n");
826 printf("\tc : start client\n");
827 printf("\tr : send request\n");
828 printf("\tt : send request to all\n");
829 printf("\tb : send notification\n");
830 printf("\tn : select network\n");
831 printf("\tx : unselect network\n");
832 printf("\tg : get network information\n");
833 printf("\th : handle request response\n");
834 printf("\tz : run static server\n");
835 printf("\tw : send secure request\n");
836 printf("\tq : quit\n");
837 printf("=============================================\n");
840 char buf[MAX_BUF_LEN] = { 0 };
841 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
843 printf("Failed to get input data\n");
849 void handle_request_response()
851 printf("Handle_request_response\n");
853 CAResult_t res = CAHandleRequestResponse();
854 if (CA_STATUS_OK != res)
856 printf("Handle request error, error code: %d\n", res);
860 printf("Handle request success\n");
864 void get_network_info()
866 CAEndpoint_t *tempInfo = NULL;
867 uint32_t tempSize = 0;
869 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
870 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
872 printf("Network not connected\n");
877 printf("################## Network Information #######################\n");
878 printf("Network info total size is %d\n\n", tempSize);
881 for (index = 0; index < tempSize; index++)
883 printf("Type: %d\n", tempInfo[index].adapter);
884 if (CA_ADAPTER_IP == tempInfo[index].adapter)
886 printf("Address: %s\n", tempInfo[index].addr);
887 printf("Port: %d\n", tempInfo[index].port);
889 else if (CA_ADAPTER_RFCOMM_BTEDR == tempInfo[index].adapter)
891 printf("Address: %s\n", tempInfo[index].addr);
893 else if (CA_ADAPTER_GATT_BTLE == tempInfo[index].adapter)
895 printf("Address: %s\n", tempInfo[index].addr);
897 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
899 if (tempInfo[index].flags & CA_SECURE)
901 g_local_secure_port = tempInfo[index].port;
902 printf("Secured: in global %d\n\n", g_local_secure_port);
907 printf("##############################################################");
910 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
912 if (NULL == object || NULL == requestInfo)
914 printf("Input parameter is NULL\n");
918 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
919 && (memcmp(g_last_request_token, requestInfo->info.token,
920 CA_MAX_TOKEN_LEN) == 0))
922 printf("token is same. received request of it's own. skip.. \n");
926 printf("##########received request from remote device #############\n");
927 if (CA_ADAPTER_IP == object->adapter)
929 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
930 object->port, object->flags & CA_SECURE);
932 else if (CA_ADAPTER_RFCOMM_BTEDR == object->adapter)
934 printf("Remote Address: %s \n", object->addr);
936 else if (CA_ADAPTER_GATT_BTLE == object->adapter)
938 printf("Remote Address: %s \n", object->addr);
940 printf("Data: %s\n", requestInfo->info.payload);
941 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
943 if (requestInfo->info.options)
945 uint32_t len = requestInfo->info.numOptions;
947 for (i = 0; i < len; i++)
949 printf("Option %d\n", i + 1);
950 printf("ID : %d\n", requestInfo->info.options[i].optionID);
951 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
952 requestInfo->info.options[i].optionData);
955 printf("############################################################\n");
957 //Check if this has secure communication information
958 if (requestInfo->info.payload &&
959 (CA_ADAPTER_IP == object->adapter))
961 int securePort = get_secure_information(requestInfo->info.payload);
962 if (0 < securePort) //Set the remote endpoint secure details and send response
964 printf("This is secure resource...\n");
966 //length of "coaps://"
967 size_t length = sizeof(SECURE_COAPS_PREFIX) - 1;
969 // length of "ipaddress:port"
970 length += strlen(object->addr) + PORT_LENGTH;
973 char *uri = calloc(1, sizeof(char) * length);
976 printf("Failed to create new uri\n");
979 sprintf(uri, "%s%s:%d/", SECURE_COAPS_PREFIX, object->addr,
982 CAEndpoint_t *endpoint = NULL;
983 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
984 object->port, &endpoint))
986 printf("Failed to create duplicate of remote endpoint!\n");
990 endpoint->flags = CA_SECURE;
997 printf("Send response with URI\n");
998 send_response(object, &requestInfo->info);
1003 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1005 printf("##########Received response from remote device #############\n");
1006 if (CA_ADAPTER_IP == object->adapter)
1008 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1009 object->port, object->flags & CA_SECURE);
1011 else if (CA_ADAPTER_RFCOMM_BTEDR == object->adapter)
1013 printf("Remote Address: %s \n", object->addr);
1015 else if (CA_ADAPTER_GATT_BTLE == object->adapter)
1017 printf("Remote Address: %s \n", object->addr);
1019 printf("response result : %d\n", responseInfo->result);
1020 printf("Data: %s\n", responseInfo->info.payload);
1021 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1022 printf("Token: %s\n", responseInfo->info.token);
1023 if (responseInfo->info.options)
1025 uint32_t len = responseInfo->info.numOptions;
1027 for (i = 0; i < len; i++)
1029 printf("Option %d\n", i + 1);
1030 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1031 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1032 responseInfo->info.options[i].optionData);
1035 printf("############################################################\n");
1038 //Check if this has secure communication information
1039 if (responseInfo->info.payload)
1041 int securePort = get_secure_information(responseInfo->info.payload);
1042 if (0 < securePort) //Set the remote endpoint secure details and send response
1044 printf("This is secure resource...\n");
1049 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1051 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1055 const CAInfo_t *info = &errorInfo->info;
1056 printf("Error Handler, ErrorInfo :\n");
1057 printf("Error Handler result : %d\n", errorInfo->result);
1058 printf("Error Handler token : %s\n", info->token);
1059 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1060 printf("Error Handler type : %d\n", info->type);
1061 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1062 printf("Error Handler payload : %s\n", info->payload);
1064 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1066 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1068 else if(CA_SEND_FAILED == errorInfo->result)
1070 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1072 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1074 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1076 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1078 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1080 else if(CA_STATUS_FAILED == errorInfo->result)
1082 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1085 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1090 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1092 printf("entering send_response\n");
1094 printf("\n=============================================\n");
1095 printf("\tselect message type\n");
1096 printf("CON : 0\n");
1097 printf("NON : 1\n");
1098 printf("ACK : 2\n");
1099 printf("RESET : 3\n");
1100 printf("select : ");
1102 char buf[MAX_BUF_LEN] = { 0 };
1103 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1108 int messageType = buf[0] - '0';
1109 if (0 > messageType || 3 < messageType)
1111 printf("Invalid message type\n");
1115 int responseCode = 0 ;
1116 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1117 if (CA_MSG_RESET != messageType)
1119 printf("\n=============================================\n");
1120 printf("\tselect response code\n");
1121 printf("EMPTY : 0\n");
1122 printf("SUCCESS : 200\n");
1123 printf("CREATED : 201\n");
1124 printf("DELETED : 202\n");
1125 printf("VALID : 203\n");
1126 printf("CHANGED : 204\n");
1127 printf("CONTENT : 205\n");
1128 printf("BAD_REQ : 400\n");
1129 printf("BAD_OPT : 402\n");
1130 printf("NOT_FOUND : 404\n");
1131 printf("INTERNAL_SERVER_ERROR : 500\n");
1132 printf("RETRANSMIT_TIMEOUT : 504\n");
1133 printf("select : ");
1135 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1139 responseCode = atoi(responseCodeBuf);
1141 CAInfo_t responseData = { 0 };
1142 responseData.type = messageType;
1143 responseData.messageId = (info != NULL) ? info->messageId : 0;
1144 responseData.resourceUri = info->resourceUri;
1146 if(CA_MSG_RESET != messageType)
1148 responseData.token = (info != NULL) ? info->token : NULL;
1149 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1151 if (endpoint->flags & CA_SECURE)
1153 printf("Sending response on secure communication\n");
1155 uint32_t length = sizeof(SECURE_INFO_DATA);
1156 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1157 if (NULL == responseData.payload)
1159 printf("Memory allocation fail\n");
1162 snprintf(responseData.payload, length, SECURE_INFO_DATA, info->resourceUri,
1163 g_local_secure_port);
1167 printf("Sending response on non-secure communication\n");
1169 uint32_t length = sizeof(NORMAL_INFO_DATA);
1170 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1171 if (NULL == responseData.payload)
1173 printf("Memory allocation fail\n");
1176 snprintf(responseData.payload, length, NORMAL_INFO_DATA, info->resourceUri);
1180 CAResponseInfo_t responseInfo = { 0 };
1181 responseInfo.result = responseCode;
1182 responseInfo.info = responseData;
1184 // send response (transportType from remoteEndpoint of request Info)
1185 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1186 if (CA_STATUS_OK != res)
1188 printf("Send response error\n");
1192 printf("Send response success\n");
1195 printf("=============================================\n");
1198 int get_secure_information(CAPayload_t payLoad)
1200 printf("Entering get_secure_information\n");
1204 printf("Payload is NULL\n");
1208 char *subString = NULL;
1209 if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1211 printf("This is not secure resource\n");
1215 if (NULL == (subString = strstr(payLoad, "\"port\":")))
1217 printf("This secure resource does not have port information\n");
1221 char *startPos = strstr(subString, ":");
1224 printf("Parsing failed !\n");
1228 char *endPos = strstr(startPos, "}");
1231 printf("Parsing failed !\n");
1235 char portStr[4] = {0};
1236 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1238 printf("secured port is: %s\n", portStr);
1239 return atoi(portStr);
1242 void get_resource_uri(char *URI, char *resourceURI, int length)
1244 char *startPos = URI;
1246 if (NULL != (temp = strstr(URI, "://")))
1248 startPos = strchr(temp + 3, '/');
1251 printf("Resource URI is missing\n");
1256 char *endPos = strchr(startPos, '?');
1259 endPos = URI + strlen(URI);
1263 if (endPos - startPos <= length)
1265 memcpy(resourceURI, startPos + 1, endPos - startPos);
1268 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1271 CAResult_t get_network_type()
1273 char buf[MAX_BUF_LEN] = { 0 };
1275 printf("\n=============================================\n");
1276 printf("\tselect network type\n");
1278 printf("GATT : 1\n");
1279 printf("RFCOMM : 2\n");
1280 printf("select : ");
1282 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1284 return CA_NOT_SUPPORTED ;
1287 int number = buf[0] - '0';
1289 number = (number < 0 || number > 3) ? 0 : 1 << number;
1293 g_selected_nw_type = CA_ADAPTER_IP;
1294 return CA_STATUS_OK;
1298 g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
1299 return CA_STATUS_OK;
1303 g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
1304 return CA_STATUS_OK;
1307 return CA_NOT_SUPPORTED;
1310 CAResult_t get_input_data(char *buf, int32_t length)
1312 if (!fgets(buf, length, stdin))
1314 printf("fgets error\n");
1315 return CA_STATUS_FAILED;
1319 if ( (p = strchr(buf, '\n')) != NULL )
1324 return CA_STATUS_OK;
1327 void parsing_coap_uri(const char* uri, addressSet_t* address)
1331 printf("parameter is null\n");
1337 uint8_t startIndex = 0;
1338 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1340 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1341 startIndex = COAPS_PREFIX_LEN;
1343 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1345 printf("uri has '%s' prefix\n", COAP_PREFIX);
1346 startIndex = COAP_PREFIX_LEN;
1349 // #2. copy uri for parse
1350 int32_t len = strlen(uri) - startIndex;
1354 printf("uri length is 0!\n");
1358 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1359 if (NULL == cloneUri)
1361 printf("Out of memory\n");
1365 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1366 cloneUri[len] = '\0';
1368 char *pAddress = cloneUri;
1369 printf("pAddress : %s\n", pAddress);
1371 int res = get_address_set(pAddress, address);
1374 printf("address parse error\n");
1383 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1385 if (NULL == pAddress)
1387 printf("parameter is null !\n");
1391 int32_t len = strlen(pAddress);
1395 for (int i = 0; i < len; i++)
1397 if (pAddress[i] == '.')
1402 // found port number start index
1403 if (isIp && pAddress[i] == ':')
1412 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1414 strncpy(outAddress->ipAddress, pAddress, ipLen);
1415 outAddress->ipAddress[ipLen] = '\0';
1417 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1419 strncpy(outAddress->ipAddress, pAddress, len);
1420 outAddress->ipAddress[len] = '\0';
1424 printf("IP Address too long: %d\n", ipLen==0 ? len : ipLen);
1430 outAddress->port = atoi(pAddress + ipLen + 1);