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 error_handler(const CARemoteEndpoint_t *object, const CAErrorInfo_t* errorInfo);
100 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info);
101 void get_resource_uri(char *URI, char *resourceURI, int length);
102 int get_secure_information(CAPayload_t payLoad);
104 static CAToken_t g_last_request_token = NULL;
105 static const char SECURE_COAPS_PREFIX[] = "coaps://";
106 static const char SECURE_INFO_DATA[] =
107 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
108 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
109 static const char NORMAL_INFO_DATA[] =
110 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
111 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
114 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
116 void clearDtlsCredentialInfo()
118 printf("clearDtlsCredentialInfo IN\n");
121 // Initialize sensitive data to zeroes before freeing.
122 if (pskCredsBlob->creds)
124 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
125 free(pskCredsBlob->creds);
128 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
132 printf("clearDtlsCredentialInfo OUT\n");
135 // Internal API. Invoked by CA stack to retrieve credentials from this module.
136 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
138 printf("CAGetDtlsPskCredentials IN\n");
142 printf("Invalid credential container");
146 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
147 if (NULL == *credInfo)
149 printf("Failed to allocate credential blob.");
153 int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
154 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
155 if (NULL == (*credInfo)->creds)
157 printf("Failed to allocate credentials.");
163 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
164 (*credInfo)->num = pskCredsBlob->num;
165 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
167 printf("CAGetDtlsPskCredentials OUT\n");
170 CAResult_t SetCredentials()
172 printf("SetCredentials IN\n");
173 pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
174 if (NULL == pskCredsBlob)
176 printf("Memory allocation failed!\n");
177 return CA_MEMORY_ALLOC_FAILED;
179 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
181 pskCredsBlob->num = 1;
183 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
184 if (NULL == pskCredsBlob->creds)
186 printf("Memory allocation failed!\n");
188 return CA_MEMORY_ALLOC_FAILED;
191 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
192 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
194 printf("SetCredentials OUT\n");
199 void GMainLoopThread()
201 g_main_loop_run(g_mainloop);
204 CAResult_t Initialize()
206 g_mainloop = g_main_loop_new(NULL, FALSE);
209 printf("g_main_loop_new failed\n");
210 return CA_STATUS_FAILED;
213 int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
216 printf("pthread_create failed in initialize\n");
217 return CA_STATUS_FAILED;
220 CAResult_t res = CAInitialize();
221 if (res != CA_STATUS_OK)
223 printf("CAInitialize fail\n");
230 int ret = system("clear");
231 // shell invoke error: 127, others: -1
232 if (127 == ret || -1 == ret)
234 printf("Terminal Clear Error: %d\n", ret);
237 printf("=============================================\n");
238 printf("\t\tsample main\n");
239 printf("=============================================\n");
241 CAResult_t res = Initialize();
242 if (CA_STATUS_OK != res)
244 printf("Initialization is failed\n");
249 * Read DTLS PSK credentials from persistent storage and
250 * set in the OC stack.
253 res = SetCredentials();
254 if (CA_STATUS_OK != res)
256 printf("SetCredentials failed\n");
260 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
261 if (CA_STATUS_OK != res)
263 printf("Set credential handler fail\n");
269 CARegisterHandler(request_handler, response_handler, error_handler);
273 CADestroyToken(g_last_request_token);
277 clearDtlsCredentialInfo();
286 char menu = get_menu();
296 printf("quit..!!\n");
299 case 's': // start server
301 start_listening_server();
304 case 't': // send request
309 case 'c': // start client
311 start_discovery_server();
314 case 'f': // find resource
319 case 'r': // send request
324 case 'a': // advertise resource
326 advertise_resource();
329 case 'b': // send notification
334 case 'n': // select network
339 case 'x': // unselect network
344 case 'h': // handle request response
346 handle_request_response();
354 find_fixed_resource();
355 while (g_received == 0)
358 handle_request_response();
367 start_discovery_server();
368 //send_secure_request();
369 while (g_received == 0)
372 handle_request_response();
378 start_listening_server();
382 handle_request_response();
386 case 'g': // get network information
392 printf("Not supported menu!!\n");
399 void start_listening_server()
401 printf("Start listening server!!\n");
403 CAResult_t res = CAStartListeningServer();
404 if (CA_STATUS_OK != res)
406 printf("Start listening server fail, error code : %d\n", res);
410 printf("Start listening server success\n");
414 void start_discovery_server()
416 printf("Start discovery client!!\n");
418 CAResult_t res = CAStartDiscoveryServer();
419 if (CA_STATUS_OK != res)
421 printf("Start discovery client fail, error code : %d\n", res);
425 printf("Start discovery client success\n");
429 void find_fixed_resource()
432 CAToken_t token = NULL;
433 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
435 CAResult_t res = CAGenerateToken(&token, tokenLength);
436 if ((CA_STATUS_OK != res) || (!token))
438 printf("Token generate error!!");
442 printf("Generated token %s\n", token);
444 char buf[MAX_BUF_LEN] = { 0 };
445 strcpy(buf, "/a/light");
447 res = CAFindResource(buf, token, tokenLength);
448 if (CA_STATUS_OK != res)
450 printf("Find resource error : %d\n", res);
454 printf("Find resource to %s URI\n", buf);
458 CADestroyToken(token);
460 printf("=============================================\n");
465 printf("\n=============================================\n");
466 printf("ex) /a/light\n");
467 printf("reference uri : ");
469 char buf[MAX_BUF_LEN] = { 0 };
470 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
476 CAToken_t token = NULL;
477 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
479 CAResult_t res = CAGenerateToken(&token, tokenLength);
480 if ((CA_STATUS_OK != res) || (!token))
482 printf("Token generate error!!\n");
486 printf("Generated token %s\n", token);
488 res = CAFindResource(buf, token, tokenLength);
489 if (CA_STATUS_OK != res)
491 printf("Find resource error : %d\n", res);
492 CADestroyToken(token);
496 printf("Find resource to %s URI\n", buf);
497 CADestroyToken(g_last_request_token);
498 g_last_request_token = token;
501 printf("=============================================\n");
506 CAResult_t res = get_network_type();
507 if (CA_STATUS_OK != res)
512 printf("Do you want to send secure request ?.... enter (0/1): ");
514 char secureRequest[MAX_BUF_LEN] = {0};
515 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
520 if (strcmp(secureRequest, "1") == 0)
522 printf("Enter the URI like below....\n");
523 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
525 else if (strcmp(secureRequest, "0") == 0)
527 printf("Enter the URI like below....\n");
528 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
529 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
533 printf("Input data is wrong value\n");
537 char uri[MAX_BUF_LEN] = {'\0'};
538 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
543 // create remote endpoint
544 CARemoteEndpoint_t *endpoint = NULL;
545 res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
546 if (CA_STATUS_OK != res || !endpoint)
548 printf("Failed to create remote endpoint, error code : %d\n", res);
552 printf("\n=============================================\n");
553 printf("0:CON, 1:NON\n");
554 printf("select message type : ");
556 char buf[MAX_BUF_LEN] = { 0 };
557 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
559 CADestroyRemoteEndpoint(endpoint);
563 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
566 CAToken_t token = NULL;
567 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
569 res = CAGenerateToken(&token, tokenLength);
570 if ((CA_STATUS_OK != res) || (!token))
572 printf("Token generate error, error code : %d\n", res);
573 CADestroyRemoteEndpoint(endpoint);
577 printf("Generated token %s\n", token);
579 // extract relative resourceuri from give uri
580 printf("URI : %s\n", uri);
582 char resourceURI[15] = {0};
583 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
585 // create request data
586 CAInfo_t requestData = { 0 };
587 requestData.token = token;
588 requestData.tokenLength = tokenLength;
590 if (strcmp(secureRequest, "1") == 0)
592 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
593 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
594 if (NULL == requestData.payload)
596 printf("Memory allocation fail\n");
597 CADestroyRemoteEndpoint(endpoint);
598 CADestroyToken(token);
601 snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
605 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
606 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
607 if (NULL == requestData.payload)
609 printf("Memory allocation fail\n");
610 CADestroyRemoteEndpoint(endpoint);
611 CADestroyToken(token);
614 snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
616 requestData.type = msgType;
618 CARequestInfo_t requestInfo = { 0 };
619 requestInfo.method = CA_GET;
620 requestInfo.info = requestData;
623 res = CASendRequest(endpoint, &requestInfo);
624 if (CA_STATUS_OK != res)
626 printf("Could not send request : %d\n", res);
630 CADestroyToken(token);
631 // destroy remote endpoint
632 CADestroyRemoteEndpoint(endpoint);
633 free(requestData.payload);
636 printf("=============================================\n");
639 void send_request_all()
641 CAResult_t res = get_network_type();
642 if (CA_STATUS_OK != res)
647 printf("\n=============================================\n");
648 printf("ex) /a/light\n");
649 printf("resource uri : ");
651 char buf[MAX_BUF_LEN] = { 0 };
652 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
657 // create remote endpoint
658 CARemoteEndpoint_t *endpoint = NULL;
659 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
660 if (CA_STATUS_OK != res)
662 printf("Create remote endpoint error, error code: %d\n", res);
666 CAGroupEndpoint_t *group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
669 printf("Memory allocation failed!\n");
670 CADestroyRemoteEndpoint(endpoint);
673 group->transportType = endpoint->transportType;
674 group->resourceUri = endpoint->resourceUri;
677 CAToken_t token = NULL;
678 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
680 res = CAGenerateToken(&token, tokenLength);
681 if ((CA_STATUS_OK != res) || (!token))
683 printf("Token generate error!!\n");
684 CADestroyRemoteEndpoint(endpoint);
689 printf("generated token %s\n", token);
691 CAInfo_t requestData = {CA_MSG_RESET};
692 requestData.token = token;
693 requestData.tokenLength = tokenLength;
694 requestData.payload = "Temp Json Payload";
695 requestData.type = CA_MSG_NONCONFIRM;
697 CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
698 requestInfo.method = CA_GET;
699 requestInfo.info = requestData;
702 res = CASendRequestToAll(group, &requestInfo);
703 if (CA_STATUS_OK != res)
705 printf("Could not send request to all\n");
706 CADestroyToken(token);
710 CADestroyToken(g_last_request_token);
711 g_last_request_token = token;
714 // destroy remote endpoint
715 CADestroyRemoteEndpoint(endpoint);
718 printf("=============================================\n");
721 void advertise_resource()
723 printf("\n=============================================\n");
726 char buf[MAX_BUF_LEN] = { 0 };
727 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
732 char optionNumBuf[MAX_BUF_LEN] = { 0 };
733 char optionData[MAX_OPT_LEN] = { 0 } ;
735 printf("Option Num : ");
736 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
740 int optionNum = atoi(optionNumBuf);
742 CAHeaderOption_t * headerOpt = (CAHeaderOption_t *)
743 calloc(1, optionNum * sizeof(CAHeaderOption_t));
744 if (NULL == headerOpt)
746 printf("Memory allocation failed!\n");
751 for (i = 0; i < optionNum; i++)
753 char getOptionID[MAX_BUF_LEN] = { 0 } ;
755 printf("[%d] Option ID : ", i + 1);
756 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
761 int optionID = atoi(getOptionID);
763 headerOpt[i].optionID = optionID;
765 printf("[%d] Option Data : ", i + 1);
766 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
772 memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
773 printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
775 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
777 printf("\n=============================================\n");
780 CAToken_t token = NULL;
781 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
783 CAResult_t res = CAGenerateToken(&token, tokenLength);
784 if ((CA_STATUS_OK != res) || (!token))
786 printf("Token generate error!!\n");
791 printf("Generated token %s\n", token);
793 res = CAAdvertiseResource(buf, token, tokenLength, headerOpt, (uint8_t) optionNum);
794 if (CA_STATUS_OK != res)
796 printf("Could not start advertise resource\n");
797 CADestroyToken(token);
801 CADestroyToken(g_last_request_token);
802 g_last_request_token = token;
808 void send_notification()
810 CAResult_t res = get_network_type();
811 if (CA_STATUS_OK != res)
816 printf("\n=============================================\n");
817 printf("Enter the URI like below....\n");
818 printf("10.11.12.13:4545/resource_uri ( for IP )\n");
819 printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
822 char buf[MAX_BUF_LEN] = { 0 };
823 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
828 printf("\n=============================================\n");
829 printf("\tselect message type\n");
834 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
835 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
840 int messageType = messageTypeBuf[0] - '0';
845 printf("CONFIRM messagetype is selected\n");
848 printf("NONCONFIRM messagetype is selected\n");
851 printf("Invalid Selection\n");
855 // create remote endpoint
856 CARemoteEndpoint_t *endpoint = NULL;
857 res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
858 if (CA_STATUS_OK != res)
860 printf("Create remote endpoint error, error code: %d\n", res);
865 CAToken_t token = NULL;
866 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
868 res = CAGenerateToken(&token, tokenLength);
869 if ((CA_STATUS_OK != res) || (!token))
871 printf("Token generate error!!\n");
872 CADestroyRemoteEndpoint(endpoint);
876 printf("Generated token %s\n", token);
878 CAInfo_t respondData = { 0 };
879 respondData.token = token;
880 respondData.tokenLength = tokenLength;
881 respondData.payload = "Temp Notification Data";
882 respondData.type = messageType;
884 CAResponseInfo_t responseInfo = { 0 };
885 responseInfo.result = CA_SUCCESS;
886 responseInfo.info = respondData;
889 res = CASendNotification(endpoint, &responseInfo);
890 if (CA_STATUS_OK != res)
892 printf("Send notification error, error code: %d\n", res);
896 printf("Send notification success\n");
900 CADestroyToken(token);
901 // destroy remote endpoint
902 CADestroyRemoteEndpoint(endpoint);
904 printf("\n=============================================\n");
907 void select_network()
909 printf("\n=============================================\n");
910 printf("\tselect network\n");
911 printf("IPv4 : 0\n");
916 char buf[MAX_BUF_LEN] = { 0 };
917 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
922 int number = buf[0] - '0';
924 if (number < 0 || number > 3)
926 printf("Invalid network type\n");
930 CAResult_t res = CASelectNetwork(1 << number);
931 if (CA_STATUS_OK != res)
933 printf("Select network error\n");
934 g_selected_nw_type = 1 << number;
938 printf("Select network success\n");
941 printf("=============================================\n");
944 void unselect_network()
946 printf("\n=============================================\n");
947 printf("\tunselect enabled network\n");
948 printf("IPv4 : 0\n");
953 char buf[MAX_BUF_LEN] = { 0 };
954 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
959 int number = buf[0] - '0';
961 if (number < 0 || number > 3)
963 printf("Invalid network type\n");
967 CAResult_t res = CAUnSelectNetwork(1 << number);
968 if (CA_STATUS_OK != res)
970 printf("Unselect network error\n");
974 printf("Unselect network success\n");
977 printf("=============================================\n");
982 printf("\n=============================================\n");
983 printf("\t\tMenu\n");
984 printf("\ts : start server\n");
985 printf("\tc : start client\n");
986 printf("\tf : find resource\n");
987 printf("\tr : send request\n");
988 printf("\tt : send request to all\n");
989 printf("\ta : advertise resource\n");
990 printf("\tb : send notification\n");
991 printf("\tn : select network\n");
992 printf("\tx : unselect network\n");
993 printf("\tg : get network information\n");
994 printf("\th : handle request response\n");
995 printf("\ty : run static client\n");
996 printf("\tz : run static server\n");
997 printf("\tw : send secure request\n");
998 printf("\tq : quit\n");
999 printf("=============================================\n");
1000 printf("select : ");
1002 char buf[MAX_BUF_LEN] = { 0 };
1003 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1005 printf("Failed to get input data\n");
1011 void handle_request_response()
1013 printf("Handle_request_response\n");
1015 CAResult_t res = CAHandleRequestResponse();
1016 if (CA_STATUS_OK != res)
1018 printf("Handle request error, error code: %d\n", res);
1022 printf("Handle request success\n");
1026 void get_network_info()
1028 CALocalConnectivity_t *tempInfo = NULL;
1029 uint32_t tempSize = 0;
1031 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
1032 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
1034 printf("Network not connected\n");
1039 printf("################## Network Information #######################\n");
1040 printf("Network info total size is %d\n\n", tempSize);
1043 for (index = 0; index < tempSize; index++)
1045 printf("Type: %d\n", tempInfo[index].type);
1046 if (CA_IPV4 == tempInfo[index].type)
1048 printf("Address: %s\n", tempInfo[index].addressInfo.IP.ipAddress);
1049 printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
1051 else if (CA_EDR == tempInfo[index].type)
1053 printf("Address: %s\n", tempInfo[index].addressInfo.BT.btMacAddress);
1055 printf("Secured: %d\n\n", tempInfo[index].isSecured);
1057 if (tempInfo[index].isSecured)
1059 g_local_secure_port = tempInfo[index].addressInfo.IP.port;
1060 printf("Secured: in global %d\n\n", g_local_secure_port);
1065 printf("##############################################################");
1068 void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
1070 if (NULL == object || NULL == requestInfo)
1072 printf("Input parameter is NULL\n");
1076 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1077 && (strncmp(g_last_request_token, requestInfo->info.token,
1078 requestInfo->info.tokenLength) == 0))
1080 printf("Token is same. received request of it's own. skip.. \n");
1084 printf("##########received request from remote device #############\n");
1085 printf("Uri: %s\n", object->resourceUri);
1086 if (CA_IPV4 == object->transportType)
1088 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1089 object->addressInfo.IP.port, object->isSecured);
1091 else if (CA_EDR == object->transportType)
1093 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1095 printf("Data: %s\n", requestInfo->info.payload);
1096 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1098 if (requestInfo->info.options)
1100 uint32_t len = requestInfo->info.numOptions;
1102 for (i = 0; i < len; i++)
1104 printf("Option %d\n", i + 1);
1105 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1106 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1107 requestInfo->info.options[i].optionData);
1110 printf("############################################################\n");
1112 //Check if this has secure communication information
1113 if (requestInfo->info.payload &&
1114 (CA_IPV4 == object->transportType))
1116 int securePort = get_secure_information(requestInfo->info.payload);
1117 if (0 < securePort) //Set the remote endpoint secure details and send response
1119 printf("This is secure resource...\n");
1121 //length of "coaps://"
1122 int length = sizeof(SECURE_COAPS_PREFIX) - 1;
1124 // length of "ipaddress:port"
1125 length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
1126 length += strlen(object->resourceUri) + 1;
1128 char *uri = calloc(1, sizeof(char) * length);
1131 printf("Failed to create new uri\n");
1134 sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
1135 object->addressInfo.IP.port, object->resourceUri);
1137 CARemoteEndpoint_t *endpoint = NULL;
1138 if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, object->transportType, &endpoint))
1140 printf("Failed to create duplicate of remote endpoint!\n");
1143 endpoint->isSecured = true;
1150 printf("Send response with URI\n");
1151 send_response(object, &requestInfo->info);
1156 void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1158 printf("##########Received response from remote device #############\n");
1159 printf("Uri: %s\n", object->resourceUri);
1160 if (CA_IPV4 == object->transportType)
1162 printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
1163 object->addressInfo.IP.port, object->isSecured);
1165 else if (CA_EDR == object->transportType)
1167 printf("Remote Address: %s \n", object->addressInfo.BT.btMacAddress);
1169 printf("response result : %d\n", responseInfo->result);
1170 printf("Data: %s\n", responseInfo->info.payload);
1171 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1172 printf("Token: %s\n", responseInfo->info.token);
1173 if (responseInfo->info.options)
1175 uint32_t len = responseInfo->info.numOptions;
1177 for (i = 0; i < len; i++)
1179 printf("Option %d\n", i + 1);
1180 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1181 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1182 responseInfo->info.options[i].optionData);
1185 printf("############################################################\n");
1188 //Check if this has secure communication information
1189 if (responseInfo->info.payload)
1191 int securePort = get_secure_information(responseInfo->info.payload);
1192 if (0 < securePort) //Set the remote endpoint secure details and send response
1194 printf("This is secure resource...\n");
1199 void error_handler(const CARemoteEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1201 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1203 if(rep && rep->resourceUri )
1205 printf("Error Handler, RemoteEndpoint Info resourceUri : %s\n", rep->resourceUri);
1209 printf("Error Handler, RemoteEndpoint is NULL");
1214 const CAInfo_t *info = &errorInfo->info;
1215 printf("Error Handler, ErrorInfo :\n");
1216 printf("Error Handler result : %d\n", errorInfo->result);
1217 printf("Error Handler token : %s\n", info->token);
1218 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1219 printf("Error Handler type : %d\n", info->type);
1220 printf("Error Handler payload : %s\n", info->payload);
1222 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1224 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1226 else if(CA_SEND_FAILED == errorInfo->result)
1228 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1230 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1232 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1234 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1236 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1238 else if(CA_STATUS_FAILED == errorInfo->result)
1240 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1243 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1248 void send_response(const CARemoteEndpoint_t *endpoint, const CAInfo_t *info)
1250 printf("entering send_response\n");
1252 printf("\n=============================================\n");
1253 printf("\tselect message type\n");
1254 printf("CON : 0\n");
1255 printf("NON : 1\n");
1256 printf("ACK : 2\n");
1257 printf("RESET : 3\n");
1258 printf("select : ");
1260 char buf[MAX_BUF_LEN] = { 0 };
1261 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1266 int messageType = buf[0] - '0';
1267 int responseCode = 0 ;
1268 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1269 if (CA_MSG_RESET != messageType)
1271 printf("\n=============================================\n");
1272 printf("\tselect response code\n");
1273 printf("EMPTY : 0\n");
1274 printf("SUCCESS : 200\n");
1275 printf("CREATED : 201\n");
1276 printf("DELETED : 202\n");
1277 printf("BAD_REQ : 400\n");
1278 printf("BAD_OPT : 402\n");
1279 printf("NOT_FOUND : 404\n");
1280 printf("INTERNAL_SERVER_ERROR : 500\n");
1281 printf("RETRANSMIT_TIMEOUT : 504\n");
1282 printf("select : ");
1284 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1288 responseCode = atoi(responseCodeBuf);
1290 CAInfo_t responseData = { 0 };
1291 responseData.type = messageType;
1293 responseData.messageId = (info != NULL) ? info->messageId : 0;
1294 if(CA_MSG_RESET != messageType)
1296 responseData.token = (info != NULL) ? info->token : NULL;
1297 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1299 if (endpoint->isSecured)
1301 printf("Sending response on secure communication\n");
1303 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(endpoint->resourceUri);
1304 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1305 if (NULL == responseData.payload)
1307 printf("Memory allocation fail\n");
1310 snprintf(responseData.payload, length, SECURE_INFO_DATA, endpoint->resourceUri,
1311 g_local_secure_port);
1315 printf("Sending response on non-secure communication\n");
1317 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(endpoint->resourceUri);
1318 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1319 if (NULL == responseData.payload)
1321 printf("Memory allocation fail\n");
1324 snprintf(responseData.payload, length, NORMAL_INFO_DATA, endpoint->resourceUri);
1328 CAResponseInfo_t responseInfo = { 0 };
1329 responseInfo.result = responseCode;
1330 responseInfo.info = responseData;
1332 // send response (transportType from remoteEndpoint of request Info)
1333 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1334 if (CA_STATUS_OK != res)
1336 printf("Send response error\n");
1340 printf("Send response success\n");
1343 printf("=============================================\n");
1346 int get_secure_information(CAPayload_t payLoad)
1348 printf("Entering get_secure_information\n");
1352 printf("Payload is NULL\n");
1356 char *subString = NULL;
1357 if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
1359 printf("This is not secure resource\n");
1363 if (NULL == (subString = strstr(payLoad, "\"port\":")))
1365 printf("This secure resource does not have port information\n");
1369 char *startPos = strstr(subString, ":");
1372 printf("Parsing failed !\n");
1376 char *endPos = strstr(startPos, "}");
1379 printf("Parsing failed !\n");
1383 if(((endPos - 1) - startPos) > 4)
1385 printf("port length is not proper.Exceeding length 4\n");
1389 char portStr[4] = {0};
1390 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1392 printf("secured port is: %s\n", portStr);
1393 return atoi(portStr);
1396 void get_resource_uri(char *URI, char *resourceURI, int length)
1398 char *startPos = URI;
1400 if (NULL != (temp = strstr(URI, "://")))
1402 startPos = strchr(temp + 3, '/');
1405 printf("Resource URI is missing\n");
1410 char *endPos = strchr(startPos, '?');
1413 endPos = URI + strlen(URI);
1417 if (endPos - startPos <= length)
1419 memcpy(resourceURI, startPos + 1, endPos - startPos);
1422 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1425 CAResult_t get_network_type()
1427 printf("\n=============================================\n");
1428 printf("\tselect network type\n");
1429 printf("IPv4 : 0\n");
1432 printf("select : ");
1434 char buf[MAX_BUF_LEN] = { 0 };
1435 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1437 return CA_NOT_SUPPORTED ;
1440 int number = buf[0] - '0';
1441 number = (number < 0 || number > 3) ? 0 : 1 << number;
1443 if (!(number & 0xf))
1445 return CA_NOT_SUPPORTED;
1447 if (number & CA_IPV4)
1449 g_selected_nw_type = CA_IPV4;
1450 return CA_STATUS_OK;
1452 if (number & CA_EDR)
1454 g_selected_nw_type = CA_EDR;
1455 return CA_STATUS_OK;
1459 g_selected_nw_type = CA_LE;
1460 return CA_STATUS_OK;
1463 printf("\n=============================================\n");
1465 return CA_STATUS_FAILED;
1468 CAResult_t get_input_data(char *buf, int32_t length)
1470 if (!fgets(buf, length, stdin))
1472 printf("fgets error\n");
1473 return CA_STATUS_FAILED;
1477 if ((p = strchr(buf, '\n')) != NULL)
1482 return CA_STATUS_OK;