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"
32 #include "ocsecurityconfig.h"
36 * @brief maximum buffer length
38 #define MAX_BUF_LEN 1024
42 * @brief maximum option length
44 #define MAX_OPT_LEN 16
48 * @brief maximum port length
53 * @def SECURE_DEFAULT_PORT
54 * @brief default secured port
56 #define SECURE_DEFAULT_PORT 5684
58 #define RESOURCE_URI_LENGTH 14
64 #define IDENTITY ("1111111111111111")
68 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
70 static GMainLoop *g_mainloop = NULL;
74 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
75 CATransportType_t g_selected_nw_type = CA_IPV4;
76 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
80 CAResult_t get_network_type();
81 CAResult_t get_input_data(char *buf, int32_t length);
83 void start_listening_server();
84 void start_discovery_server();
87 void send_request_all();
88 void advertise_resource();
89 void send_notification();
90 void select_network();
91 void unselect_network();
92 void handle_request_response();
93 void find_fixed_resource();
94 void get_network_info();
96 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
97 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
98 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
99 void get_resource_uri(char *URI, char *resourceURI, int length);
100 int get_secure_information(CAPayload_t payLoad);
102 static CAToken_t g_last_request_token = NULL;
103 static const char SECURE_COAPS_PREFIX[] = "coaps://";
104 static const char SECURE_INFO_DATA[] =
105 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
106 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
107 static const char NORMAL_INFO_DATA[] =
108 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
109 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
112 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
114 void clearDtlsCredentialInfo()
116 printf("clearDtlsCredentialInfo IN\n");
119 // Initialize sensitive data to zeroes before freeing.
120 if (pskCredsBlob->creds)
122 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
123 free(pskCredsBlob->creds);
126 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
130 printf("clearDtlsCredentialInfo OUT\n");
133 // Internal API. Invoked by CA stack to retrieve credentials from this module.
134 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
136 printf("CAGetDtlsPskCredentials IN\n");
140 printf("Invalid credential container");
144 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
145 if (NULL == *credInfo)
147 printf("Failed to allocate credential blob.");
151 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
152 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
153 if (NULL == (*credInfo)->creds)
155 printf("Failed to allocate credentials.");
161 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
162 (*credInfo)->num = pskCredsBlob->num;
163 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
165 printf("CAGetDtlsPskCredentials OUT\n");
168 CAResult_t SetCredentials()
170 printf("SetCredentials IN\n");
171 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
172 if (NULL == pskCredsBlob)
174 printf("Memory allocation failed!\n");
175 return CA_MEMORY_ALLOC_FAILED;
177 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
179 pskCredsBlob->num = 1;
181 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
182 if (NULL == pskCredsBlob->creds)
184 printf("Memory allocation failed!\n");
186 return CA_MEMORY_ALLOC_FAILED;
189 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
190 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
192 printf("SetCredentials OUT\n");
197 void GMainLoopThread()
199 g_main_loop_run(g_mainloop);
202 CAResult_t Initialize()
204 g_mainloop = g_main_loop_new(NULL, FALSE);
207 printf("g_main_loop_new failed\n");
208 return CA_STATUS_FAILED;
211 int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
214 printf("pthread_create failed in initialize\n");
215 return CA_STATUS_FAILED;
218 CAResult_t res = CAInitialize();
219 if (res != CA_STATUS_OK)
221 printf("CAInitialize fail\n");
228 int ret = system("clear");
229 // shell invoke error: 127, others: -1
230 if (127 == ret || -1 == ret)
232 printf("Terminal Clear Error: %d\n", ret);
235 printf("=============================================\n");
236 printf("\t\tsample main\n");
237 printf("=============================================\n");
239 CAResult_t res = Initialize();
240 if (CA_STATUS_OK != res)
242 printf("Initialization is failed\n");
247 * Read DTLS PSK credentials from persistent storage and
248 * set in the OC stack.
251 res = SetCredentials();
252 if (CA_STATUS_OK != res)
254 printf("SetCredentials failed\n");
258 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
259 if (CA_STATUS_OK != res)
261 printf("Set credential handler fail\n");
267 CARegisterHandler(request_handler, response_handler);
271 CADestroyToken(g_last_request_token);
275 clearDtlsCredentialInfo();
284 char menu = get_menu();
294 printf("quit..!!\n");
297 case 's': // start server
299 start_listening_server();
302 case 't': // send request
307 case 'c': // start client
309 start_discovery_server();
312 case 'f': // find resource
317 case 'r': // send request
322 case 'a': // advertise resource
324 advertise_resource();
327 case 'b': // send notification
332 case 'n': // select network
337 case 'x': // unselect network
342 case 'h': // handle request response
344 handle_request_response();
352 find_fixed_resource();
353 while (g_received == 0)
356 handle_request_response();
365 start_discovery_server();
366 //send_secure_request();
367 while (g_received == 0)
370 handle_request_response();
376 start_listening_server();
380 handle_request_response();
384 case 'g': // get network information
390 printf("Not supported menu!!\n");
397 void start_listening_server()
399 printf("Start listening server!!\n");
401 CAResult_t res = CAStartListeningServer();
402 if (CA_STATUS_OK != res)
404 printf("Start listening server fail, error code : %d\n", res);
408 printf("Start listening server success\n");
412 void start_discovery_server()
414 printf("Start discovery client!!\n");
416 CAResult_t res = CAStartDiscoveryServer();
417 if (CA_STATUS_OK != res)
419 printf("Start discovery client fail, error code : %d\n", res);
423 printf("Start discovery client success\n");
427 void find_fixed_resource()
430 CAToken_t token = NULL;
431 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
433 CAResult_t res = CAGenerateToken(&token, tokenLength);
434 if ((CA_STATUS_OK != res) || (!token))
436 printf("Token generate error!!");
440 printf("Generated token %s\n", token);
442 char buf[MAX_BUF_LEN] = { 0 };
443 strcpy(buf, "/a/light");
445 res = CAFindResource(buf, token, tokenLength);
446 if (CA_STATUS_OK != res)
448 printf("Find resource error : %d\n", res);
452 printf("Find resource to %s URI\n", buf);
456 CADestroyToken(token);
458 printf("=============================================\n");
463 printf("\n=============================================\n");
464 printf("ex) /a/light\n");
465 printf("reference uri : ");
467 char buf[MAX_BUF_LEN] = { 0 };
468 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
474 CAToken_t token = NULL;
475 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
477 CAResult_t res = CAGenerateToken(&token, tokenLength);
478 if ((CA_STATUS_OK != res) || (!token))
480 printf("Token generate error!!\n");
484 printf("Generated token %s\n", token);
486 res = CAFindResource(buf, token, tokenLength);
487 if (CA_STATUS_OK != res)
489 printf("Find resource error : %d\n", res);
490 CADestroyToken(token);
494 printf("Find resource to %s URI\n", buf);
495 CADestroyToken(g_last_request_token);
496 g_last_request_token = token;
499 printf("=============================================\n");
504 CAResult_t res = get_network_type();
505 if (CA_STATUS_OK != res)
510 printf("Do you want to send secure request ?.... enter (0/1): ");
512 char secureRequest[MAX_BUF_LEN] = {0};
513 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
518 if (strcmp(secureRequest, "1") == 0)
520 printf("Enter the URI like below....\n");
521 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
523 else if (strcmp(secureRequest, "0") == 0)
525 printf("Enter the URI like below....\n");
526 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
527 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
531 printf("Input data is wrong value\n");
535 char uri[MAX_BUF_LEN] = {'\0'};
536 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
541 // create remote endpoint
542 CARemoteEndpoint_t *endpoint = NULL;
543 res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
544 if (CA_STATUS_OK != res || !endpoint)
546 printf("Failed to create remote endpoint, error code : %d\n", res);
550 printf("\n=============================================\n");
551 printf("0:CON, 1:NON\n");
552 printf("select message type : ");
554 char buf[MAX_BUF_LEN] = { 0 };
555 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
557 CADestroyRemoteEndpoint(endpoint);
561 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
564 CAToken_t token = NULL;
565 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
567 res = CAGenerateToken(&token, tokenLength);
568 if ((CA_STATUS_OK != res) || (!token))
570 printf("Token generate error, error code : %d\n", res);
571 CADestroyRemoteEndpoint(endpoint);
575 printf("Generated token %s\n", token);
577 // extract relative resourceuri from give uri
578 printf("URI : %s\n", uri);
580 char resourceURI[15] = {0};
581 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
583 // create request data
584 CAInfo_t requestData = { 0 };
585 requestData.token = token;
586 requestData.tokenLength = tokenLength;
588 if (strcmp(secureRequest, "1") == 0)
590 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
591 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
592 if (NULL == requestData.payload)
594 printf("Memory allocation fail\n");
595 CADestroyRemoteEndpoint(endpoint);
596 CADestroyToken(token);
599 snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
603 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
604 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
605 if (NULL == requestData.payload)
607 printf("Memory allocation fail\n");
608 CADestroyRemoteEndpoint(endpoint);
609 CADestroyToken(token);
612 snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
614 requestData.type = msgType;
616 CARequestInfo_t requestInfo = { 0 };
617 requestInfo.method = CA_GET;
618 requestInfo.info = requestData;
621 res = CASendRequest(endpoint, &requestInfo);
622 if (CA_STATUS_OK != res)
624 printf("Could not send request : %d\n", res);
628 CADestroyToken(token);
629 // destroy remote endpoint
630 CADestroyRemoteEndpoint(endpoint);
631 free(requestData.payload);
634 printf("=============================================\n");
637 void send_request_all()
639 CAResult_t res = get_network_type();
640 if (CA_STATUS_OK != res)
645 printf("\n=============================================\n");
646 printf("ex) /a/light\n");
647 printf("resource uri : ");
649 char buf[MAX_BUF_LEN] = { 0 };
650 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
655 // create remote endpoint
656 CARemoteEndpoint_t *endpoint = NULL;
657 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
658 if (CA_STATUS_OK != res)
660 printf("Create remote endpoint error, error code: %d\n", res);
664 CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
667 printf("Memory allocation failed!\n");
668 CADestroyRemoteEndpoint(endpoint);
671 group->transportType = endpoint->transportType;
672 group->resourceUri = endpoint->resourceUri;
675 CAToken_t token = NULL;
676 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
678 res = CAGenerateToken(&token, tokenLength);
679 if ((CA_STATUS_OK != res) || (!token))
681 printf("Token generate error!!\n");
682 CADestroyRemoteEndpoint(endpoint);
687 printf("generated token %s\n", token);
689 CAInfo_t requestData = {CA_MSG_RESET};
690 requestData.token = token;
691 requestData.tokenLength = tokenLength;
692 requestData.payload = "Temp Json Payload";
693 requestData.type = CA_MSG_NONCONFIRM;
695 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
696 requestInfo.method = CA_GET;
697 requestInfo.info = requestData;
700 res = CASendRequestToAll(group, &requestInfo);
701 if (CA_STATUS_OK != res)
703 printf("Could not send request to all\n");
704 CADestroyToken(token);
708 CADestroyToken(g_last_request_token);
709 g_last_request_token = token;
712 // destroy remote endpoint
713 CADestroyRemoteEndpoint(endpoint);
716 printf("=============================================\n");
719 void advertise_resource()
721 printf("\n=============================================\n");
724 char buf[MAX_BUF_LEN] = { 0 };
725 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
730 char optionNumBuf[MAX_BUF_LEN] = { 0 };
731 char optionData[MAX_OPT_LEN] = { 0 } ;
733 printf("Option Num : ");
734 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
738 int optionNum = atoi(optionNumBuf);
740 CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
741 calloc(1, optionNum * sizeof(CAHeaderOption_t));
742 if (NULL == headerOpt)
744 printf("Memory allocation failed!\n");
749 for (i = 0; i < optionNum; i++)
751 char getOptionID[MAX_BUF_LEN] = { 0 } ;
753 printf("[%d] Option ID : ", i + 1);
754 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
759 int optionID = atoi(getOptionID);
761 headerOpt[i].optionID = optionID;
763 printf("[%d] Option Data : ", i + 1);
764 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
770 memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
771 printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
773 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
775 printf("\n=============================================\n");
778 CAToken_t token = NULL;
779 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
781 CAResult_t res = CAGenerateToken(&token, tokenLength);
782 if ((CA_STATUS_OK != res) || (!token))
784 printf("Token generate error!!\n");
789 printf("Generated token %s\n", token);
791 res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
792 if (CA_STATUS_OK != res)
794 printf("Could not start advertise resource\n");
795 CADestroyToken(token);
799 CADestroyToken(g_last_request_token);
800 g_last_request_token = token;
806 void send_notification()
808 CAResult_t res = get_network_type();
809 if (CA_STATUS_OK != res)
814 printf("\n=============================================\n");
815 printf("Enter the URI like below....\n");
816 printf("10.11.12.13:4545/resource_uri ( for IP )\n");
817 printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
820 char buf[MAX_BUF_LEN] = { 0 };
821 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
826 printf("\n=============================================\n");
827 printf("\tselect message type\n");
832 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
833 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
838 int messageType = messageTypeBuf[0] - '0';
843 printf("CONFIRM messagetype is selected\n");
846 printf("NONCONFIRM messagetype is selected\n");
849 printf("Invalid Selection\n");
853 // create remote endpoint
854 CARemoteEndpoint_t *endpoint = NULL;
855 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
856 if (CA_STATUS_OK != res)
858 printf("Create remote endpoint error, error code: %d\n", res);
863 CAToken_t token = NULL;
864 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
866 res = CAGenerateToken(&token, tokenLength);
867 if ((CA_STATUS_OK != res) || (!token))
869 printf("Token generate error!!\n");
870 CADestroyRemoteEndpoint(endpoint);
874 printf("Generated token %s\n", token);
876 CAInfo_t respondData = { 0 };
877 respondData.token = token;
878 respondData.tokenLength = tokenLength;
879 respondData.payload = "Temp Notification Data";
880 respondData.type = messageType;
882 CAResponseInfo_t responseInfo = { 0 };
883 responseInfo.result = CA_SUCCESS;
884 responseInfo.info = respondData;
887 res = CASendNotification(endpoint, &responseInfo);
888 if (CA_STATUS_OK != res)
890 printf("Send notification error, error code: %d\n", res);
894 printf("Send notification success\n");
898 CADestroyToken(token);
899 // destroy remote endpoint
900 CADestroyRemoteEndpoint(endpoint);
902 printf("\n=============================================\n");
905 void select_network()
907 printf("\n=============================================\n");
908 printf("\tselect network\n");
909 printf("IPv4 : 0\n");
914 char buf[MAX_BUF_LEN] = { 0 };
915 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
920 int number = buf[0] - '0';
922 if (number < 0 || number > 3)
924 printf("Invalid network type\n");
928 CAResult_t res = CASelectNetwork(1 << number);
929 if (CA_STATUS_OK != res)
931 printf("Select network error\n");
932 g_selected_nw_type = 1 << number;
936 printf("Select network success\n");
939 printf("=============================================\n");
942 void unselect_network()
944 printf("\n=============================================\n");
945 printf("\tunselect enabled network\n");
946 printf("IPv4 : 0\n");
951 char buf[MAX_BUF_LEN] = { 0 };
952 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
957 int number = buf[0] - '0';
959 if (number < 0 || number > 3)
961 printf("Invalid network type\n");
965 CAResult_t res = CAUnSelectNetwork(1 << number);
966 if (CA_STATUS_OK != res)
968 printf("Unselect network error\n");
972 printf("Unselect network success\n");
975 printf("=============================================\n");
980 printf("\n=============================================\n");
981 printf("\t\tMenu\n");
982 printf("\ts : start server\n");
983 printf("\tc : start client\n");
984 printf("\tf : find resource\n");
985 printf("\tr : send request\n");
986 printf("\tt : send request to all\n");
987 printf("\ta : advertise resource\n");
988 printf("\tb : send notification\n");
989 printf("\tn : select network\n");
990 printf("\tx : unselect network\n");
991 printf("\tg : get network information\n");
992 printf("\th : handle request response\n");
993 printf("\ty : run static client\n");
994 printf("\tz : run static server\n");
995 printf("\tw : send secure request\n");
996 printf("\tq : quit\n");
997 printf("=============================================\n");
1000 char buf[MAX_BUF_LEN] = { 0 };
1001 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1003 printf("Failed to get input data\n");
1009 void handle_request_response()
1011 printf("Handle_request_response\n");
1013 CAResult_t res = CAHandleRequestResponse();
1014 if (CA_STATUS_OK != res)
1016 printf("Handle request error, error code: %d\n", res);
1020 printf("Handle request success\n");
1024 void get_network_info()
1026 CALocalConnectivity_t *tempInfo = NULL;
1027 uint32_t tempSize = 0;
1029 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
1030 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
1032 printf("Network not connected\n");
1037 printf("################## Network Information #######################\n");
1038 printf("Network info total size is %d\n\n", tempSize);
1041 for (index = 0; index < tempSize; index++)
1043 printf("Type: %d\n", tempInfo[index].type);
1044 if (CA_IPV4 == tempInfo[index].type)
1046 printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
1047 printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
1049 else if (CA_EDR == tempInfo[index].type)
1051 printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
1053 printf("Secured: %d\n\n", tempInfo[index].isSecured);
1055 if (tempInfo[index].isSecured)
1057 g_local_secure_port = tempInfo[index].addressInfo.IP.port;
1058 printf("Secured: in global %d\n\n", g_local_secure_port);
1063 printf("##############################################################");
1066 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
1068 if (NULL == object || NULL == requestInfo)
1070 printf("Input parameter is NULL\n");
1074 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1075 && (strncmp(g_last_request_token, requestInfo->info.token,
1076 requestInfo->info.tokenLength) == 0))
1078 printf("Token is same. received request of it's own. skip.. \n");
1082 printf("##########received request from remote device #############\n");
1083 printf("Uri: %s\n", object->resourceUri);
1084 if (CA_IPV4 == object->transportType)
1086 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1087 object->addressInfo.IP.port, object->isSecured);
1089 else if (CA_EDR == object->transportType)
1091 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1093 printf("Data: %s\n", requestInfo->info.payload);
1094 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1096 if (requestInfo->info.options)
1098 uint32_t len = requestInfo->info.numOptions;
1100 for (i = 0; i < len; i++)
1102 printf("Option %d\n", i + 1);
1103 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1104 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1105 requestInfo->info.options[i].optionData);
1108 printf("############################################################\n");
1110 //Check if this has secure communication information
1111 if (requestInfo->info.payload &&
1112 (CA_IPV4 == object->transportType))
1114 int securePort = get_secure_information(requestInfo->info.payload);
1115 if (0 < securePort) //Set the remote endpoint secure details and send response
1117 printf("This is secure resource...\n");
1119 //length of "coaps://"
1120 int length = sizeof(SECURE_COAPS_PREFIX) - 1;
1122 // length of "ipaddress:port"
1123 length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
1124 length += strlen(object->resourceUri) + 1;
1126 char *uri = calloc(1, sizeof(char) * length);
1129 printf("Failed to create new uri\n");
1132 sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
1133 object->addressInfo.IP.port, object->resourceUri);
1135 CARemoteEndpoint_t *endpoint = NULL;
1136 if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
1138 printf("Failed to create duplicate of remote endpoint!\n");
1141 endpoint->isSecured = true;
1148 printf("Send response with URI\n");
1149 send_response(object, &requestInfo->info);
1154 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1156 printf("##########Received response from remote device #############\n");
1157 printf("Uri: %s\n", object->resourceUri);
1158 if (CA_IPV4 == object->transportType)
1160 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1161 object->addressInfo.IP.port, object->isSecured);
1163 else if (CA_EDR == object->transportType)
1165 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1167 printf("response result : %d\n", responseInfo->result);
1168 printf("Data: %s\n", responseInfo->info.payload);
1169 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1170 printf("Token: %s\n", responseInfo->info.token);
1171 if (responseInfo->info.options)
1173 uint32_t len = responseInfo->info.numOptions;
1175 for (i = 0; i < len; i++)
1177 printf("Option %d\n", i + 1);
1178 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1179 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1180 responseInfo->info.options[i].optionData);
1183 printf("############################################################\n");
1186 //Check if this has secure communication information
1187 if (responseInfo->info.payload)
1189 int securePort = get_secure_information(responseInfo->info.payload);
1190 if (0 < securePort) //Set the remote endpoint secure details and send response
1192 printf("This is secure resource...\n");
1197 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
1199 printf("entering send_response\n");
1201 printf("\n=============================================\n");
1202 printf("\tselect message type\n");
1203 printf("CON : 0\n");
1204 printf("NON : 1\n");
1205 printf("ACK : 2\n");
1206 printf("RESET : 3\n");
1207 printf("select : ");
1209 char buf[MAX_BUF_LEN] = { 0 };
1210 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1215 int messageType = buf[0] - '0';
1216 int responseCode = 0 ;
1217 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1218 if (CA_MSG_RESET != messageType)
1220 printf("\n=============================================\n");
1221 printf("\tselect response code\n");
1222 printf("EMPTY : 0\n");
1223 printf("SUCCESS : 200\n");
1224 printf("CREATED : 201\n");
1225 printf("DELETED : 202\n");
1226 printf("BAD_REQ : 400\n");
1227 printf("BAD_OPT : 402\n");
1228 printf("NOT_FOUND : 404\n");
1229 printf("INTERNAL_SERVER_ERROR : 500\n");
1230 printf("RETRANSMIT_TIMEOUT : 504\n");
1231 printf("select : ");
1233 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1237 responseCode = atoi(responseCodeBuf);
1239 CAInfo_t responseData = { 0 };
1240 responseData.type = messageType;
1242 responseData.messageId = (info != NULL) ? info->messageId : 0;
1243 if(CA_MSG_RESET != messageType)
1245 responseData.token = (info != NULL) ? info->token : NULL;
1246 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1248 if (endpoint->isSecured)
1250 printf("Sending response on secure communication\n");
1252 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
1253 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1254 if (NULL == responseData.payload)
1256 printf("Memory allocation fail\n");
1259 snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
1260 g_local_secure_port);
1264 printf("Sending response on non-secure communication\n");
1266 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
1267 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1268 if (NULL == responseData.payload)
1270 printf("Memory allocation fail\n");
1273 snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
1277 CAResponseInfo_t responseInfo = { 0 };
1278 responseInfo.result = responseCode;
1279 responseInfo.info = responseData;
1281 // send response (transportType from remoteEndpoint of request Info)
1282 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1283 if (CA_STATUS_OK != res)
1285 printf("Send response error\n");
1289 printf("Send response success\n");
1292 printf("=============================================\n");
1295 int get_secure_information(CAPayload_t payLoad)
1297 printf("Entering get_secure_information\n");
1301 printf("Payload is NULL\n");
1305 char *subString = NULL;
1306 if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1308 printf("This is not secure resource\n");
1312 if (NULL == (subString = strstr(payLoad, "\"port\":")))
1314 printf("This secure resource does not have port information\n");
1318 char *startPos = strstr(subString, ":");
1321 printf("Parsing failed !\n");
1325 char *endPos = strstr(startPos, "}");
1328 printf("Parsing failed !\n");
1332 if(((endPos - 1) - startPos) > 4)
1334 printf("port length is not proper.Exceeding length 4\n");
1338 char portStr[4] = {0};
1339 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1341 printf("secured port is: %s\n", portStr);
1342 return atoi(portStr);
1345 void get_resource_uri(char *URI, char *resourceURI, int length)
1347 char *startPos = URI;
1349 if (NULL != (temp = strstr(URI, "://")))
1351 startPos = strchr(temp + 3, '/');
1354 printf("Resource URI is missing\n");
1359 char *endPos = strchr(startPos, '?');
1362 endPos = URI + strlen(URI);
1366 if (endPos - startPos <= length)
1368 memcpy(resourceURI, startPos + 1, endPos - startPos);
1371 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1374 CAResult_t get_network_type()
1376 printf("\n=============================================\n");
1377 printf("\tselect network type\n");
1378 printf("IPv4 : 0\n");
1381 printf("select : ");
1383 char buf[MAX_BUF_LEN] = { 0 };
1384 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1386 return CA_NOT_SUPPORTED ;
1389 int number = buf[0] - '0';
1390 number = (number < 0 || number > 3) ? 0 : 1 << number;
1392 if (!(number & 0xf))
1394 return CA_NOT_SUPPORTED;
1396 if (number & CA_IPV4)
1398 g_selected_nw_type = CA_IPV4;
1399 return CA_STATUS_OK;
1401 if (number & CA_EDR)
1403 g_selected_nw_type = CA_EDR;
1404 return CA_STATUS_OK;
1408 g_selected_nw_type = CA_LE;
1409 return CA_STATUS_OK;
1412 printf("\n=============================================\n");
1414 return CA_STATUS_FAILED;
1417 CAResult_t get_input_data(char *buf, int32_t length)
1419 if (!fgets(buf, length, stdin))
1421 printf("fgets error\n");
1422 return CA_STATUS_FAILED;
1426 if ((p = strchr(buf, '\n')) != NULL)
1431 return CA_STATUS_OK;