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 send_notification();
89 void select_network();
90 void unselect_network();
91 void handle_request_response();
92 void find_fixed_resource();
93 void get_network_info();
95 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
96 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
97 void error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
99 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
100 void get_resource_uri(char *URI, char *resourceURI, int length);
101 int get_secure_information(CAPayload_t payLoad);
103 static CAToken_t g_last_request_token = NULL;
104 static const char SECURE_COAPS_PREFIX[] = "coaps://";
105 static const char SECURE_INFO_DATA[] =
106 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
107 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
108 static const char NORMAL_INFO_DATA[] =
109 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
110 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
113 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
115 void clearDtlsCredentialInfo()
117 printf("clearDtlsCredentialInfo IN\n");
120 // Initialize sensitive data to zeroes before freeing.
121 if (pskCredsBlob->creds)
123 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
124 free(pskCredsBlob->creds);
127 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
131 printf("clearDtlsCredentialInfo OUT\n");
134 // Internal API. Invoked by CA stack to retrieve credentials from this module.
135 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
137 printf("CAGetDtlsPskCredentials IN\n");
141 printf("Invalid credential container");
145 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
146 if (NULL == *credInfo)
148 printf("Failed to allocate credential blob.");
152 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
153 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
154 if (NULL == (*credInfo)->creds)
156 printf("Failed to allocate credentials.");
162 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
163 (*credInfo)->num = pskCredsBlob->num;
164 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
166 printf("CAGetDtlsPskCredentials OUT\n");
169 CAResult_t SetCredentials()
171 printf("SetCredentials IN\n");
172 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
173 if (NULL == pskCredsBlob)
175 printf("Memory allocation failed!\n");
176 return CA_MEMORY_ALLOC_FAILED;
178 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
180 pskCredsBlob->num = 1;
182 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
183 if (NULL == pskCredsBlob->creds)
185 printf("Memory allocation failed!\n");
187 return CA_MEMORY_ALLOC_FAILED;
190 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
191 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
193 printf("SetCredentials OUT\n");
198 void GMainLoopThread()
200 g_main_loop_run(g_mainloop);
203 CAResult_t Initialize()
205 g_mainloop = g_main_loop_new(NULL, FALSE);
208 printf("g_main_loop_new failed\n");
209 return CA_STATUS_FAILED;
212 int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
215 printf("pthread_create failed in initialize\n");
216 return CA_STATUS_FAILED;
219 CAResult_t res = CAInitialize();
220 if (res != CA_STATUS_OK)
222 printf("CAInitialize fail\n");
229 int ret = system("clear");
230 // shell invoke error: 127, others: -1
231 if (127 == ret || -1 == ret)
233 printf("Terminal Clear Error: %d\n", ret);
236 printf("=============================================\n");
237 printf("\t\tsample main\n");
238 printf("=============================================\n");
240 CAResult_t res = Initialize();
241 if (CA_STATUS_OK != res)
243 printf("Initialization is failed\n");
248 * Read DTLS PSK credentials from persistent storage and
249 * set in the OC stack.
252 res = SetCredentials();
253 if (CA_STATUS_OK != res)
255 printf("SetCredentials failed\n");
259 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
260 if (CA_STATUS_OK != res)
262 printf("Set credential handler fail\n");
268 CARegisterHandler(request_handler, response_handler, error_handler);
272 CADestroyToken(g_last_request_token);
276 clearDtlsCredentialInfo();
285 char menu = get_menu();
295 printf("quit..!!\n");
298 case 's': // start server
300 start_listening_server();
303 case 't': // send request
308 case 'c': // start client
310 start_discovery_server();
313 case 'f': // find resource
318 case 'r': // send request
323 case 'b': // send notification
328 case 'n': // select network
333 case 'x': // unselect network
338 case 'h': // handle request response
340 handle_request_response();
348 find_fixed_resource();
349 while (g_received == 0)
352 handle_request_response();
361 start_discovery_server();
362 //send_secure_request();
363 while (g_received == 0)
366 handle_request_response();
372 start_listening_server();
376 handle_request_response();
380 case 'g': // get network information
386 printf("Not supported menu!!\n");
393 void start_listening_server()
395 printf("Start listening server!!\n");
397 CAResult_t res = CAStartListeningServer();
398 if (CA_STATUS_OK != res)
400 printf("Start listening server fail, error code : %d\n", res);
404 printf("Start listening server success\n");
408 void start_discovery_server()
410 printf("Start discovery client!!\n");
412 CAResult_t res = CAStartDiscoveryServer();
413 if (CA_STATUS_OK != res)
415 printf("Start discovery client fail, error code : %d\n", res);
419 printf("Start discovery client success\n");
423 void find_fixed_resource()
426 CAToken_t token = NULL;
427 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
429 CAResult_t res = CAGenerateToken(&token, tokenLength);
430 if ((CA_STATUS_OK != res) || (!token))
432 printf("Token generate error!!");
436 printf("Generated token %s\n", token);
438 char buf[MAX_BUF_LEN] = { 0 };
439 strcpy(buf, "/a/light");
441 res = CAFindResource(buf, token, tokenLength);
442 if (CA_STATUS_OK != res)
444 printf("Find resource error : %d\n", res);
448 printf("Find resource to %s URI\n", buf);
452 CADestroyToken(token);
454 printf("=============================================\n");
459 printf("\n=============================================\n");
460 printf("ex) /a/light\n");
461 printf("reference uri : ");
463 char buf[MAX_BUF_LEN] = { 0 };
464 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
470 CAToken_t token = NULL;
471 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
473 CAResult_t res = CAGenerateToken(&token, tokenLength);
474 if ((CA_STATUS_OK != res) || (!token))
476 printf("Token generate error!!\n");
480 printf("Generated token %s\n", token);
482 res = CAFindResource(buf, token, tokenLength);
483 if (CA_STATUS_OK != res)
485 printf("Find resource error : %d\n", res);
486 CADestroyToken(token);
490 printf("Find resource to %s URI\n", buf);
491 CADestroyToken(g_last_request_token);
492 g_last_request_token = token;
495 printf("=============================================\n");
500 CAResult_t res = get_network_type();
501 if (CA_STATUS_OK != res)
506 printf("Do you want to send secure request ?.... enter (0/1): ");
508 char secureRequest[MAX_BUF_LEN] = {0};
509 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
514 if (strcmp(secureRequest, "1") == 0)
516 printf("Enter the URI like below....\n");
517 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
519 else if (strcmp(secureRequest, "0") == 0)
521 printf("Enter the URI like below....\n");
522 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
523 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
527 printf("Input data is wrong value\n");
531 char uri[MAX_BUF_LEN] = {'\0'};
532 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
537 // create remote endpoint
538 CARemoteEndpoint_t *endpoint = NULL;
539 res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
540 if (CA_STATUS_OK != res || !endpoint)
542 printf("Failed to create remote endpoint, error code : %d\n", res);
546 printf("\n=============================================\n");
547 printf("0:CON, 1:NON\n");
548 printf("select message type : ");
550 char buf[MAX_BUF_LEN] = { 0 };
551 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
553 CADestroyRemoteEndpoint(endpoint);
557 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
560 CAToken_t token = NULL;
561 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
563 res = CAGenerateToken(&token, tokenLength);
564 if ((CA_STATUS_OK != res) || (!token))
566 printf("Token generate error, error code : %d\n", res);
567 CADestroyRemoteEndpoint(endpoint);
571 printf("Generated token %s\n", token);
573 // extract relative resourceuri from give uri
574 printf("URI : %s\n", uri);
576 char resourceURI[15] = {0};
577 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
579 // create request data
580 CAInfo_t requestData = { 0 };
581 requestData.token = token;
582 requestData.tokenLength = tokenLength;
584 if (strcmp(secureRequest, "1") == 0)
586 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
587 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
588 if (NULL == requestData.payload)
590 printf("Memory allocation fail\n");
591 CADestroyRemoteEndpoint(endpoint);
592 CADestroyToken(token);
595 snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
599 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
600 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
601 if (NULL == requestData.payload)
603 printf("Memory allocation fail\n");
604 CADestroyRemoteEndpoint(endpoint);
605 CADestroyToken(token);
608 snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
610 requestData.type = msgType;
612 CARequestInfo_t requestInfo = { 0 };
613 requestInfo.method = CA_GET;
614 requestInfo.info = requestData;
617 res = CASendRequest(endpoint, &requestInfo);
618 if (CA_STATUS_OK != res)
620 printf("Could not send request : %d\n", res);
624 CADestroyToken(token);
625 // destroy remote endpoint
626 CADestroyRemoteEndpoint(endpoint);
627 free(requestData.payload);
630 printf("=============================================\n");
633 void send_request_all()
635 CAResult_t res = get_network_type();
636 if (CA_STATUS_OK != res)
641 printf("\n=============================================\n");
642 printf("ex) /a/light\n");
643 printf("resource uri : ");
645 char buf[MAX_BUF_LEN] = { 0 };
646 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
651 // create remote endpoint
652 CARemoteEndpoint_t *endpoint = NULL;
653 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
654 if (CA_STATUS_OK != res)
656 printf("Create remote endpoint error, error code: %d\n", res);
660 CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
663 printf("Memory allocation failed!\n");
664 CADestroyRemoteEndpoint(endpoint);
667 group->transportType = endpoint->transportType;
668 group->resourceUri = endpoint->resourceUri;
671 CAToken_t token = NULL;
672 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
674 res = CAGenerateToken(&token, tokenLength);
675 if ((CA_STATUS_OK != res) || (!token))
677 printf("Token generate error!!\n");
678 CADestroyRemoteEndpoint(endpoint);
683 printf("generated token %s\n", token);
685 CAInfo_t requestData = {CA_MSG_RESET};
686 requestData.token = token;
687 requestData.tokenLength = tokenLength;
688 requestData.payload = "Temp Json Payload";
689 requestData.type = CA_MSG_NONCONFIRM;
691 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
692 requestInfo.method = CA_GET;
693 requestInfo.info = requestData;
696 res = CASendRequestToAll(group, &requestInfo);
697 if (CA_STATUS_OK != res)
699 printf("Could not send request to all\n");
700 CADestroyToken(token);
704 CADestroyToken(g_last_request_token);
705 g_last_request_token = token;
708 // destroy remote endpoint
709 CADestroyRemoteEndpoint(endpoint);
712 printf("=============================================\n");
715 void send_notification()
717 CAResult_t res = get_network_type();
718 if (CA_STATUS_OK != res)
723 printf("\n=============================================\n");
724 printf("Enter the URI like below....\n");
725 printf("10.11.12.13:4545/resource_uri ( for IP )\n");
726 printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
729 char buf[MAX_BUF_LEN] = { 0 };
730 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
735 printf("\n=============================================\n");
736 printf("\tselect message type\n");
741 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
742 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
747 int messageType = messageTypeBuf[0] - '0';
752 printf("CONFIRM messagetype is selected\n");
755 printf("NONCONFIRM messagetype is selected\n");
758 printf("Invalid Selection\n");
762 // create remote endpoint
763 CARemoteEndpoint_t *endpoint = NULL;
764 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
765 if (CA_STATUS_OK != res)
767 printf("Create remote endpoint error, error code: %d\n", res);
772 CAToken_t token = NULL;
773 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
775 res = CAGenerateToken(&token, tokenLength);
776 if ((CA_STATUS_OK != res) || (!token))
778 printf("Token generate error!!\n");
779 CADestroyRemoteEndpoint(endpoint);
783 printf("Generated token %s\n", token);
785 CAInfo_t respondData = { 0 };
786 respondData.token = token;
787 respondData.tokenLength = tokenLength;
788 respondData.payload = "Temp Notification Data";
789 respondData.type = messageType;
791 CAResponseInfo_t responseInfo = { 0 };
792 responseInfo.result = CA_CONTENT;
793 responseInfo.info = respondData;
796 res = CASendNotification(endpoint, &responseInfo);
797 if (CA_STATUS_OK != res)
799 printf("Send notification error, error code: %d\n", res);
803 printf("Send notification success\n");
807 CADestroyToken(token);
808 // destroy remote endpoint
809 CADestroyRemoteEndpoint(endpoint);
811 printf("\n=============================================\n");
814 void select_network()
816 printf("\n=============================================\n");
817 printf("\tselect network\n");
818 printf("IPv4 : 0\n");
823 char buf[MAX_BUF_LEN] = { 0 };
824 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
829 int number = buf[0] - '0';
831 if (number < 0 || number > 3)
833 printf("Invalid network type\n");
837 CAResult_t res = CASelectNetwork(1 << number);
838 if (CA_STATUS_OK != res)
840 printf("Select network error\n");
841 g_selected_nw_type = 1 << number;
845 printf("Select network success\n");
848 printf("=============================================\n");
851 void unselect_network()
853 printf("\n=============================================\n");
854 printf("\tunselect enabled network\n");
855 printf("IPv4 : 0\n");
860 char buf[MAX_BUF_LEN] = { 0 };
861 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
866 int number = buf[0] - '0';
868 if (number < 0 || number > 3)
870 printf("Invalid network type\n");
874 CAResult_t res = CAUnSelectNetwork(1 << number);
875 if (CA_STATUS_OK != res)
877 printf("Unselect network error\n");
881 printf("Unselect network success\n");
884 printf("=============================================\n");
889 printf("\n=============================================\n");
890 printf("\t\tMenu\n");
891 printf("\ts : start server\n");
892 printf("\tc : start client\n");
893 printf("\tf : find resource\n");
894 printf("\tr : send request\n");
895 printf("\tt : send request to all\n");
896 printf("\ta : advertise resource\n");
897 printf("\tb : send notification\n");
898 printf("\tn : select network\n");
899 printf("\tx : unselect network\n");
900 printf("\tg : get network information\n");
901 printf("\th : handle request response\n");
902 printf("\ty : run static client\n");
903 printf("\tz : run static server\n");
904 printf("\tw : send secure request\n");
905 printf("\tq : quit\n");
906 printf("=============================================\n");
909 char buf[MAX_BUF_LEN] = { 0 };
910 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
912 printf("Failed to get input data\n");
918 void handle_request_response()
920 printf("Handle_request_response\n");
922 CAResult_t res = CAHandleRequestResponse();
923 if (CA_STATUS_OK != res)
925 printf("Handle request error, error code: %d\n", res);
929 printf("Handle request success\n");
933 void get_network_info()
935 CALocalConnectivity_t *tempInfo = NULL;
936 uint32_t tempSize = 0;
938 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
939 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
941 printf("Network not connected\n");
946 printf("################## Network Information #######################\n");
947 printf("Network info total size is %d\n\n", tempSize);
950 for (index = 0; index < tempSize; index++)
952 printf("Type: %d\n", tempInfo[index].type);
953 if (CA_IPV4 == tempInfo[index].type)
955 printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
956 printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
958 else if (CA_EDR == tempInfo[index].type)
960 printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
962 printf("Secured: %d\n\n", tempInfo[index].isSecured);
964 if (tempInfo[index].isSecured)
966 g_local_secure_port = tempInfo[index].addressInfo.IP.port;
967 printf("Secured: in global %d\n\n", g_local_secure_port);
972 printf("##############################################################");
975 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
977 if (NULL == object || NULL == requestInfo)
979 printf("Input parameter is NULL\n");
983 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
984 && (strncmp(g_last_request_token, requestInfo->info.token,
985 requestInfo->info.tokenLength) == 0))
987 printf("Token is same. received request of it's own. skip.. \n");
991 printf("##########received request from remote device #############\n");
992 printf("Uri: %s\n", object->resourceUri);
993 if (CA_IPV4 == object->transportType)
995 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
996 object->addressInfo.IP.port, object->isSecured);
998 else if (CA_EDR == object->transportType)
1000 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1002 printf("Data: %s\n", requestInfo->info.payload);
1003 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1005 if (requestInfo->info.options)
1007 uint32_t len = requestInfo->info.numOptions;
1009 for (i = 0; i < len; i++)
1011 printf("Option %d\n", i + 1);
1012 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1013 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1014 requestInfo->info.options[i].optionData);
1017 printf("############################################################\n");
1019 //Check if this has secure communication information
1020 if (requestInfo->info.payload &&
1021 (CA_IPV4 == object->transportType))
1023 int securePort = get_secure_information(requestInfo->info.payload);
1024 if (0 < securePort) //Set the remote endpoint secure details and send response
1026 printf("This is secure resource...\n");
1028 //length of "coaps://"
1029 int length = sizeof(SECURE_COAPS_PREFIX) - 1;
1031 // length of "ipaddress:port"
1032 length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
1033 length += strlen(object->resourceUri) + 1;
1035 char *uri = calloc(1, sizeof(char) * length);
1038 printf("Failed to create new uri\n");
1041 sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
1042 object->addressInfo.IP.port, object->resourceUri);
1044 CARemoteEndpoint_t *endpoint = NULL;
1045 if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
1047 printf("Failed to create duplicate of remote endpoint!\n");
1050 endpoint->isSecured = true;
1057 printf("Send response with URI\n");
1058 send_response(object, &requestInfo->info);
1063 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1065 printf("##########Received response from remote device #############\n");
1066 printf("Uri: %s\n", object->resourceUri);
1067 if (CA_IPV4 == object->transportType)
1069 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1070 object->addressInfo.IP.port, object->isSecured);
1072 else if (CA_EDR == object->transportType)
1074 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1076 printf("response result : %d\n", responseInfo->result);
1077 printf("Data: %s\n", responseInfo->info.payload);
1078 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1079 printf("Token: %s\n", responseInfo->info.token);
1080 if (responseInfo->info.options)
1082 uint32_t len = responseInfo->info.numOptions;
1084 for (i = 0; i < len; i++)
1086 printf("Option %d\n", i + 1);
1087 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1088 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1089 responseInfo->info.options[i].optionData);
1092 printf("############################################################\n");
1095 //Check if this has secure communication information
1096 if (responseInfo->info.payload)
1098 int securePort = get_secure_information(responseInfo->info.payload);
1099 if (0 < securePort) //Set the remote endpoint secure details and send response
1101 printf("This is secure resource...\n");
1106 void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1108 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1110 if(rep && rep->resourceUri )
1112 printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
1116 printf("Error Handler, RemoteEndpoint is NULL");
1121 const CAInfo_t *info = &errorInfo->info;
1122 printf("Error Handler, ErrorInfo :\n");
1123 printf("Error Handler result : %d\n", errorInfo->result);
1124 printf("Error Handler token : %s\n", info->token);
1125 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1126 printf("Error Handler type : %d\n", info->type);
1127 printf("Error Handler payload : %s\n", info->payload);
1129 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1131 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1133 else if(CA_SEND_FAILED == errorInfo->result)
1135 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1137 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1139 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1141 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1143 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1145 else if(CA_STATUS_FAILED == errorInfo->result)
1147 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1150 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1155 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
1157 printf("entering send_response\n");
1159 printf("\n=============================================\n");
1160 printf("\tselect message type\n");
1161 printf("CON : 0\n");
1162 printf("NON : 1\n");
1163 printf("ACK : 2\n");
1164 printf("RESET : 3\n");
1165 printf("select : ");
1167 char buf[MAX_BUF_LEN] = { 0 };
1168 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1173 int messageType = buf[0] - '0';
1174 int responseCode = 0 ;
1175 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1176 if (CA_MSG_RESET != messageType)
1178 printf("\n=============================================\n");
1179 printf("\tselect response code\n");
1180 printf("EMPTY : 0\n");
1181 printf("SUCCESS : 200\n");
1182 printf("CREATED : 201\n");
1183 printf("DELETED : 202\n");
1184 printf("VALID : 203\n");
1185 printf("CHANGED : 204\n");
1186 printf("CONTENT : 205\n");
1187 printf("BAD_REQ : 400\n");
1188 printf("BAD_OPT : 402\n");
1189 printf("NOT_FOUND : 404\n");
1190 printf("INTERNAL_SERVER_ERROR : 500\n");
1191 printf("RETRANSMIT_TIMEOUT : 504\n");
1192 printf("select : ");
1194 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1198 responseCode = atoi(responseCodeBuf);
1200 CAInfo_t responseData = { 0 };
1201 responseData.type = messageType;
1203 responseData.messageId = (info != NULL) ? info->messageId : 0;
1204 if(CA_MSG_RESET != messageType)
1206 responseData.token = (info != NULL) ? info->token : NULL;
1207 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1209 if (endpoint->isSecured)
1211 printf("Sending response on secure communication\n");
1213 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
1214 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1215 if (NULL == responseData.payload)
1217 printf("Memory allocation fail\n");
1220 snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
1221 g_local_secure_port);
1225 printf("Sending response on non-secure communication\n");
1227 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
1228 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1229 if (NULL == responseData.payload)
1231 printf("Memory allocation fail\n");
1234 snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
1238 CAResponseInfo_t responseInfo = { 0 };
1239 responseInfo.result = responseCode;
1240 responseInfo.info = responseData;
1242 // send response (transportType from remoteEndpoint of request Info)
1243 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1244 if (CA_STATUS_OK != res)
1246 printf("Send response error\n");
1250 printf("Send response success\n");
1253 printf("=============================================\n");
1256 int get_secure_information(CAPayload_t payLoad)
1258 printf("Entering get_secure_information\n");
1262 printf("Payload is NULL\n");
1266 char *subString = NULL;
1267 if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1269 printf("This is not secure resource\n");
1273 if (NULL == (subString = strstr(payLoad, "\"port\":")))
1275 printf("This secure resource does not have port information\n");
1279 char *startPos = strstr(subString, ":");
1282 printf("Parsing failed !\n");
1286 char *endPos = strstr(startPos, "}");
1289 printf("Parsing failed !\n");
1293 if(((endPos - 1) - startPos) > 4)
1295 printf("port length is not proper.Exceeding length 4\n");
1299 char portStr[4] = {0};
1300 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1302 printf("secured port is: %s\n", portStr);
1303 return atoi(portStr);
1306 void get_resource_uri(char *URI, char *resourceURI, int length)
1308 char *startPos = URI;
1310 if (NULL != (temp = strstr(URI, "://")))
1312 startPos = strchr(temp + 3, '/');
1315 printf("Resource URI is missing\n");
1320 char *endPos = strchr(startPos, '?');
1323 endPos = URI + strlen(URI);
1327 if (endPos - startPos <= length)
1329 memcpy(resourceURI, startPos + 1, endPos - startPos);
1332 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1335 CAResult_t get_network_type()
1337 printf("\n=============================================\n");
1338 printf("\tselect network type\n");
1339 printf("IPv4 : 0\n");
1342 printf("select : ");
1344 char buf[MAX_BUF_LEN] = { 0 };
1345 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1347 return CA_NOT_SUPPORTED ;
1350 int number = buf[0] - '0';
1351 number = (number < 0 || number > 3) ? 0 : 1 << number;
1353 if (!(number & 0xf))
1355 return CA_NOT_SUPPORTED;
1357 if (number & CA_IPV4)
1359 g_selected_nw_type = CA_IPV4;
1360 return CA_STATUS_OK;
1362 if (number & CA_EDR)
1364 g_selected_nw_type = CA_EDR;
1365 return CA_STATUS_OK;
1369 g_selected_nw_type = CA_LE;
1370 return CA_STATUS_OK;
1373 printf("\n=============================================\n");
1375 return CA_STATUS_FAILED;
1378 CAResult_t get_input_data(char *buf, int32_t length)
1380 if (!fgets(buf, length, stdin))
1382 printf("fgets error\n");
1383 return CA_STATUS_FAILED;
1387 if ((p = strchr(buf, '\n')) != NULL)
1392 return CA_STATUS_OK;