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"
31 #include "ocsecurityconfig.h"
34 #define MAX_BUF_LEN 1024
35 #define MAX_OPT_LEN 16
39 #define SECURE_DEFAULT_PORT 5684
41 #define RESOURCE_URI_LENGTH 14
43 #define SYSTEM_INVOKE_ERROR 127
44 #define SYSTEM_ERROR -1
46 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
52 #define IDENTITY ("1111111111111111")
56 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
59 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
60 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
61 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
65 char ipAddress[CA_IPADDR_SIZE];
71 CAResult_t get_network_type();
72 CAResult_t get_input_data(char *buf, int32_t length);
74 bool select_payload_type();
75 CAPayload_t get_binary_payload(size_t *payloadLength);
76 bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
77 void create_file(CAPayload_t bytes, size_t length);
79 void start_listening_server();
80 void start_discovery_server();
82 void send_request_all();
83 void send_notification();
84 void select_network();
85 void unselect_network();
86 void handle_request_response();
87 void get_network_info();
88 void send_secure_request();
90 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
91 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
92 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
93 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
94 void get_resource_uri(char *URI, char *resourceURI, int length);
95 int get_secure_information(CAPayload_t payLoad);
96 int get_address_set(const char *pAddress, addressSet_t* outAddress);
97 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
98 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
100 static CAToken_t g_last_request_token = NULL;
102 static const char COAP_PREFIX[] = "coap://";
103 static const char COAPS_PREFIX[] = "coaps://";
104 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
105 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
107 static const char SECURE_INFO_DATA[] =
108 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
109 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
111 static const char NORMAL_INFO_DATA[] =
112 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
113 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
116 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
118 void clearDtlsCredentialInfo()
120 printf("clearDtlsCredentialInfo IN\n");
123 // Initialize sensitive data to zeroes before freeing.
124 if (pskCredsBlob->creds)
126 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
127 free(pskCredsBlob->creds);
130 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
134 printf("clearDtlsCredentialInfo OUT\n");
137 // Internal API. Invoked by CA stack to retrieve credentials from this module
138 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
140 printf("CAGetDtlsPskCredentials IN\n");
143 printf("Invalid credential container");
147 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
148 if (NULL == *credInfo)
150 printf("Failed to allocate credential blob.");
154 size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
155 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
156 if (NULL == (*credInfo)->creds)
158 printf("Failed to allocate credentials.");
164 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
165 (*credInfo)->num = pskCredsBlob->num;
166 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
168 printf("CAGetDtlsPskCredentials OUT\n");
172 CAResult_t SetCredentials()
174 printf("SetCredentials IN\n");
175 pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
176 if (NULL == pskCredsBlob)
178 printf("Memory allocation failed!\n");
179 return CA_MEMORY_ALLOC_FAILED;
181 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
184 pskCredsBlob->num = 1;
186 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
187 if (NULL == pskCredsBlob->creds)
189 printf("Memory allocation failed!\n");
191 return CA_MEMORY_ALLOC_FAILED;
194 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
195 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
197 printf("SetCredentials OUT\n");
204 int ret = system("clear");
205 // shell invoke error: 127, others: -1
206 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
208 printf("Terminal Clear Error: %d\n", ret);
212 printf("=============================================\n");
213 printf("\t\tsample main\n");
214 printf("=============================================\n");
216 CAResult_t res = CAInitialize();
217 if (CA_STATUS_OK != res)
219 printf("CAInitialize fail\n");
224 * Read DTLS PSK credentials from persistent storage and
225 * set in the OC stack.
228 res = SetCredentials();
229 if (CA_STATUS_OK != res)
231 printf("SetCredentials failed\n");
235 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
236 if (CA_STATUS_OK != res)
238 printf("Set credential handler fail\n");
244 CARegisterHandler(request_handler, response_handler, error_handler);
248 CADestroyToken(g_last_request_token);
250 g_last_request_token = NULL;
254 clearDtlsCredentialInfo();
263 char menu = get_menu();
273 printf("quit..!!\n");
276 case 's': // start server
278 start_listening_server();
281 case 't': // send request
286 case 'c': // start client
288 start_discovery_server();
291 case 'r': // send request
296 case 'b': // send notification
301 case 'n': // select network
306 case 'x': // unselect network
311 case 'h': // handle request response
313 handle_request_response();
319 start_discovery_server();
320 send_secure_request();
321 while (g_received == 0)
324 handle_request_response();
330 start_listening_server();
334 handle_request_response();
338 case 'g': // get network information
344 printf("not supported menu!!\n");
350 void start_listening_server()
352 printf("start listening server!!\n");
354 CAResult_t res = CAStartListeningServer();
355 if (CA_STATUS_OK != res)
357 printf("start listening server fail, error code : %d\n", res);
361 printf("start listening server success\n");
365 void start_discovery_server()
367 printf("start discovery client!!\n");
369 CAResult_t res = CAStartDiscoveryServer();
370 if (CA_STATUS_OK != res)
372 printf("start discovery client fail, error code : %d\n", res);
376 printf("start discovery client success\n");
380 bool select_payload_type()
382 char buf[MAX_BUF_LEN]={0};
383 printf("\n=============================================\n");
384 printf("Normal Payload : 0\nBig Payload : 1\n");
385 printf("select Payload type : ");
387 CAResult_t res = get_input_data(buf, sizeof(buf));
388 if (CA_STATUS_OK != res)
390 printf("Payload type selection error\n");
391 printf("Default: Using normal Payload\n");
395 return (buf[0] == '1') ? true : false;
398 CAPayload_t get_binary_payload(size_t *payloadLength)
400 CAPayload_t binaryPayload = NULL;
401 bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
407 return binaryPayload;
412 CAResult_t res = get_network_type();
413 if (CA_STATUS_OK != res)
418 printf("Do you want to send secure request ?.... enter (0/1): ");
420 char secureRequest[MAX_BUF_LEN] = {0};
421 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
426 if (strcmp(secureRequest, "1") == 0)
428 printf("Enter the URI like below....\n");
429 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
431 else if (strcmp(secureRequest, "0") == 0)
433 printf("Enter the URI like below....\n");
434 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
435 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
439 printf("Input data is wrong value\n");
443 char uri[MAX_BUF_LEN] = {'\0'};
444 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
449 // create remote endpoint
450 CAEndpoint_t *endpoint = NULL;
451 CATransportFlags_t flags;
453 printf("URI : %s\n", uri);
454 addressSet_t address = {};
455 parsing_coap_uri(uri, &address, &flags);
457 res = CACreateEndpoint(flags, g_selected_nw_type,
458 (const char*)address.ipAddress, address.port, &endpoint);
459 if (CA_STATUS_OK != res || !endpoint)
461 printf("Failed to create remote endpoint, error code : %d\n", res);
465 printf("\n=============================================\n");
466 printf("0:CON, 1:NON\n");
467 printf("select message type : ");
469 char buf[MAX_BUF_LEN] = { 0 };
470 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
472 CADestroyEndpoint(endpoint);
476 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
479 CAToken_t token = NULL;
480 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
482 res = CAGenerateToken(&token, tokenLength);
483 if ((CA_STATUS_OK != res) || (!token))
485 printf("Token generate error, error code : %d\n", res);
486 CADestroyEndpoint(endpoint);
490 printf("Generated token %s\n", token);
492 // extract relative resourceuri from give uri
493 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
494 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
495 printf("resourceURI : %s\n", resourceURI);
497 // create request data
498 CAInfo_t requestData = { 0 };
499 requestData.token = token;
500 requestData.tokenLength = tokenLength;
501 requestData.resourceUri = (CAURI_t)resourceURI;
503 if (strcmp(secureRequest, "1") == 0)
505 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
506 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
507 if (NULL == requestData.payload)
509 printf("Memory allocation fail\n");
510 CADestroyEndpoint(endpoint);
511 CADestroyToken(token);
514 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
515 (const char *) resourceURI, g_local_secure_port);
516 requestData.payloadSize = length;
520 bool useBigPayload = select_payload_type();
523 size_t payloadLength = 0;
524 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
528 CADestroyToken(token);
529 CADestroyEndpoint(endpoint);
533 requestData.payload = (CAPayload_t) malloc(payloadLength);
534 if (NULL == requestData.payload)
536 printf("Memory allocation failed!");
538 CADestroyToken(token);
539 CADestroyEndpoint(endpoint);
542 memcpy(requestData.payload, binaryPayload, payloadLength);
543 requestData.payloadSize = payloadLength;
550 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
551 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
552 if (NULL == requestData.payload)
554 printf("Memory allocation fail\n");
555 CADestroyEndpoint(endpoint);
556 CADestroyToken(token);
559 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
560 (const char *) resourceURI);
561 requestData.payloadSize = length;
564 requestData.type = msgType;
565 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
567 CARequestInfo_t requestInfo = { 0 };
568 requestInfo.method = CA_GET;
569 requestInfo.info = requestData;
570 requestInfo.isMulticast = false;
573 res = CASendRequest(endpoint, &requestInfo);
574 if (CA_STATUS_OK != res)
576 printf("Could not send request : %d\n", res);
585 CADestroyToken(token);
586 // destroy remote endpoint
587 CADestroyEndpoint(endpoint);
588 free(requestData.payload);
590 printf("=============================================\n");
593 void send_secure_request()
595 char uri[MAX_BUF_LEN];
596 char ipv4addr[CA_IPADDR_SIZE];
598 printf("\n=============================================\n");
599 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
601 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
605 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
607 // create remote endpoint
608 CAEndpoint_t *endpoint = NULL;
609 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
610 if (CA_STATUS_OK != res)
612 printf("Failed to create remote endpoint, error code: %d\n", res);
617 CAToken_t token = NULL;
618 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
620 res = CAGenerateToken(&token, tokenLength);
621 if ((CA_STATUS_OK != res) || (!token))
623 printf("Token generate error, error code : %d\n", res);
627 printf("Generated token %s\n", token);
629 // create request data
630 CAMessageType_t msgType = CA_MSG_NONCONFIRM;
631 CAInfo_t requestData = { 0 };
632 requestData.token = token;
633 requestData.tokenLength = tokenLength;
634 requestData.type = msgType;
636 CARequestInfo_t requestInfo = { 0 };
637 requestInfo.method = CA_GET;
638 requestInfo.info = requestData;
639 requestInfo.isMulticast = false;
642 CASendRequest(endpoint, &requestInfo);
646 CADestroyToken(token);
647 CADestroyEndpoint(endpoint);
648 printf("=============================================\n");
652 void send_request_all()
654 CAResult_t res = get_network_type();
655 if (CA_STATUS_OK != res)
660 printf("\n=============================================\n");
661 printf("ex) /a/light\n");
662 printf("resource uri : ");
664 char resourceURI[MAX_BUF_LEN] = { 0 };
665 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
670 // create remote endpoint
671 CAEndpoint_t *group = NULL;
672 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
673 if (CA_STATUS_OK != res)
675 printf("Create remote endpoint error, error code: %d\n", res);
680 CAToken_t token = NULL;
681 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
683 res = CAGenerateToken(&token, tokenLength);
684 if ((CA_STATUS_OK != res) || (!token))
686 printf("Token generate error!!\n");
687 CADestroyEndpoint(group);
691 printf("generated token %s\n", token);
693 CAInfo_t requestData = { 0 };
694 requestData.token = token;
695 requestData.tokenLength = tokenLength;
696 requestData.payload = (CAPayload_t) "TempJsonPayload";
697 requestData.payloadSize = strlen((const char *) requestData.payload);
698 requestData.type = CA_MSG_NONCONFIRM;
699 requestData.resourceUri = (CAURI_t)resourceURI;
701 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
703 CARequestInfo_t requestInfo = { 0 };
704 requestInfo.method = CA_GET;
705 requestInfo.info = requestData;
706 requestInfo.isMulticast = true;
709 res = CASendRequest(group, &requestInfo);
710 if (CA_STATUS_OK != res)
712 printf("Could not send request to all\n");
713 CADestroyToken(token);
717 CADestroyToken(g_last_request_token);
718 g_last_request_token = token;
726 // destroy remote endpoint
727 CADestroyEndpoint(group);
729 printf("=============================================\n");
732 void send_notification()
734 CAResult_t res = get_network_type();
735 if (CA_STATUS_OK != res)
740 printf("\n=============================================\n");
741 printf("Enter the URI like below....\n");
742 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
743 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
746 char uri[MAX_BUF_LEN] = { 0 };
747 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
752 printf("\n=============================================\n");
753 printf("\tselect message type\n");
757 printf("RESET : 3\n");
760 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
761 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
766 int messageType = messageTypeBuf[0] - '0';
768 CATransportFlags_t flags;
769 addressSet_t address = {};
770 parsing_coap_uri(uri, &address, &flags);
772 // create remote endpoint
773 CAEndpoint_t *endpoint = NULL;
774 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
775 if (CA_STATUS_OK != res)
777 printf("Create remote endpoint error, error code: %d\n", res);
782 CAToken_t token = NULL;
783 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
785 res = CAGenerateToken(&token, tokenLength);
786 if ((CA_STATUS_OK != res) || (!token))
788 printf("Token generate error!!\n");
789 CADestroyEndpoint(endpoint);
793 printf("Generated token %s\n", token);
795 CAInfo_t respondData = { 0 };
796 respondData.token = token;
797 respondData.tokenLength = tokenLength;
798 respondData.payload = (CAPayload_t) "TempNotificationData";
799 respondData.payloadSize = strlen((const char *) respondData.payload);
800 respondData.type = messageType;
801 respondData.resourceUri = (CAURI_t)uri;
803 CAResponseInfo_t responseInfo = { 0 };
804 responseInfo.result = CA_CONTENT;
805 responseInfo.info = respondData;
808 res = CASendNotification(endpoint, &responseInfo);
809 if (CA_STATUS_OK != res)
811 printf("Send notification error, error code: %d\n", res);
815 printf("Send notification success\n");
819 CADestroyToken(token);
820 // destroy remote endpoint
821 CADestroyEndpoint(endpoint);
823 printf("\n=============================================\n");
826 void select_network()
828 printf("\n=============================================\n");
829 printf("\tselect network\n");
831 printf("GATT : 1\n");
832 printf("RFCOMM : 2\n");
835 char buf[MAX_BUF_LEN] = { 0 };
836 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
841 int number = buf[0] - '0';
843 if (number < 0 || number > 3)
845 printf("Invalid network type\n");
849 CAResult_t res = CASelectNetwork(1 << number);
850 if (CA_STATUS_OK != res)
852 printf("Select network error\n");
856 printf("Select network success\n");
859 printf("=============================================\n");
862 void unselect_network()
864 printf("\n=============================================\n");
865 printf("\tunselect enabled network\n");
867 printf("GATT : 1\n");
868 printf("RFCOMM : 2\n");
871 char buf[MAX_BUF_LEN] = { 0 };
872 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
877 int number = buf[0] - '0';
879 if (number < 0 || number > 3)
881 printf("Invalid network type\n");
885 CAResult_t res = CAUnSelectNetwork(1 << number);
886 if (CA_STATUS_OK != res)
888 printf("Unselect network error\n");
892 printf("Unselect network success\n");
895 printf("=============================================\n");
900 printf("\n=============================================\n");
901 printf("\t\tMenu\n");
902 printf("\ts : start server\n");
903 printf("\tc : start client\n");
904 printf("\tr : send request\n");
905 printf("\tt : send request to all\n");
906 printf("\tb : send notification\n");
907 printf("\tn : select network\n");
908 printf("\tx : unselect network\n");
909 printf("\tg : get network information\n");
910 printf("\th : handle request response\n");
911 printf("\tz : run static server\n");
912 printf("\tw : send secure request\n");
913 printf("\tq : quit\n");
914 printf("=============================================\n");
917 char buf[MAX_BUF_LEN] = { 0 };
918 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
920 printf("Failed to get input data\n");
926 void handle_request_response()
928 printf("Handle_request_response\n");
930 CAResult_t res = CAHandleRequestResponse();
931 if (CA_STATUS_OK != res)
933 printf("Handle request error, error code: %d\n", res);
937 printf("Handle request success\n");
941 void get_network_info()
943 CAEndpoint_t *tempInfo = NULL;
944 uint32_t tempSize = 0;
946 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
947 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
949 printf("Network not connected\n");
954 printf("################## Network Information #######################\n");
955 printf("Network info total size is %d\n\n", tempSize);
958 for (index = 0; index < tempSize; index++)
960 printf("Type: %d\n", tempInfo[index].adapter);
961 printf("Address: %s\n", tempInfo[index].addr);
962 if (CA_ADAPTER_IP == tempInfo[index].adapter)
964 printf("Port: %d\n", tempInfo[index].port);
966 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
968 if (tempInfo[index].flags & CA_SECURE)
970 g_local_secure_port = tempInfo[index].port;
971 printf("Secured: in global %d\n\n", g_local_secure_port);
976 printf("##############################################################");
979 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
981 if (NULL == object || NULL == requestInfo)
983 printf("Input parameter is NULL\n");
987 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
988 && (memcmp(g_last_request_token, requestInfo->info.token,
989 CA_MAX_TOKEN_LEN) == 0))
991 printf("token is same. received request of it's own. skip.. \n");
995 printf("##########received request from remote device #############\n");
996 if (CA_ADAPTER_IP == object->adapter)
998 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
999 object->port, object->flags & CA_SECURE);
1003 printf("Remote Address: %s \n", object->addr);
1005 printf("Data: %s\n", requestInfo->info.payload);
1006 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1008 if (requestInfo->info.options)
1010 uint32_t len = requestInfo->info.numOptions;
1012 for (i = 0; i < len; i++)
1014 printf("Option %d\n", i + 1);
1015 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1016 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1017 requestInfo->info.options[i].optionData);
1020 printf("############################################################\n");
1022 //Check if this has secure communication information
1023 if (requestInfo->info.payload &&
1024 (CA_ADAPTER_IP == object->adapter))
1026 int securePort = get_secure_information(requestInfo->info.payload);
1027 if (0 < securePort) //Set the remote endpoint secure details and send response
1029 printf("This is secure resource...\n");
1031 CAEndpoint_t *endpoint = NULL;
1032 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1033 object->port, &endpoint))
1035 printf("Failed to create duplicate of remote endpoint!\n");
1038 endpoint->flags = CA_SECURE;
1043 // if received message is bulk data, create output file
1044 if ((requestInfo->info.payload) &&
1045 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1047 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1050 printf("Send response with URI\n");
1051 send_response(object, &requestInfo->info);
1056 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1058 printf("##########Received response from remote device #############\n");
1059 if (CA_ADAPTER_IP == object->adapter)
1061 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1062 object->port, object->flags & CA_SECURE);
1066 printf("Remote Address: %s \n", object->addr);
1068 printf("response result : %d\n", responseInfo->result);
1069 printf("Data: %s\n", responseInfo->info.payload);
1070 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1071 printf("Token: %s\n", responseInfo->info.token);
1072 if (responseInfo->info.options)
1074 uint32_t len = responseInfo->info.numOptions;
1076 for (i = 0; i < len; i++)
1078 printf("Option %d\n", i + 1);
1079 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1080 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1081 responseInfo->info.options[i].optionData);
1084 printf("############################################################\n");
1087 //Check if this has secure communication information
1088 if (responseInfo->info.payload)
1090 int securePort = get_secure_information(responseInfo->info.payload);
1091 if (0 < securePort) //Set the remote endpoint secure details and send response
1093 printf("This is secure resource...\n");
1097 // if received message is bulk data, create output file
1098 if ((responseInfo->info.payload) &&
1099 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1101 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1105 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1107 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1111 const CAInfo_t *info = &errorInfo->info;
1112 printf("Error Handler, ErrorInfo :\n");
1113 printf("Error Handler result : %d\n", errorInfo->result);
1114 printf("Error Handler token : %s\n", info->token);
1115 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1116 printf("Error Handler type : %d\n", info->type);
1117 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1118 printf("Error Handler payload : %s\n", info->payload);
1120 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1122 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1124 else if(CA_SEND_FAILED == errorInfo->result)
1126 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1128 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1130 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1132 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1134 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1136 else if(CA_STATUS_FAILED == errorInfo->result)
1138 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1141 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1146 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1148 printf("entering send_response\n");
1150 printf("\n=============================================\n");
1151 printf("\tselect message type\n");
1152 printf("CON : 0\n");
1153 printf("NON : 1\n");
1154 printf("ACK : 2\n");
1155 printf("RESET : 3\n");
1156 printf("select : ");
1158 char buf[MAX_BUF_LEN] = { 0 };
1159 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1164 int messageType = buf[0] - '0';
1165 if (0 > messageType || 3 < messageType)
1167 printf("Invalid message type\n");
1171 int responseCode = 0 ;
1172 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1173 if (CA_MSG_RESET != messageType)
1175 printf("\n=============================================\n");
1176 printf("\tselect response code\n");
1177 printf("EMPTY : 0\n");
1178 printf("SUCCESS : 200\n");
1179 printf("CREATED : 201\n");
1180 printf("DELETED : 202\n");
1181 printf("VALID : 203\n");
1182 printf("CHANGED : 204\n");
1183 printf("CONTENT : 205\n");
1184 printf("BAD_REQ : 400\n");
1185 printf("BAD_OPT : 402\n");
1186 printf("NOT_FOUND : 404\n");
1187 printf("INTERNAL_SERVER_ERROR : 500\n");
1188 printf("RETRANSMIT_TIMEOUT : 504\n");
1189 printf("select : ");
1191 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1195 responseCode = atoi(responseCodeBuf);
1197 CAInfo_t responseData = { 0 };
1198 responseData.type = messageType;
1199 responseData.messageId = (info != NULL) ? info->messageId : 0;
1200 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
1202 if(CA_MSG_RESET != messageType)
1204 responseData.token = (info != NULL) ? info->token : NULL;
1205 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1207 if (endpoint->flags & CA_SECURE)
1209 printf("Sending response on secure communication\n");
1211 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1212 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1213 if (NULL == responseData.payload)
1215 printf("Memory allocation fail\n");
1218 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1219 (const char *) responseData.resourceUri, g_local_secure_port);
1220 responseData.payloadSize = length;
1224 printf("Sending response on non-secure communication\n");
1226 bool useBigPayload = select_payload_type();
1229 size_t payloadLength = 0;
1230 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1231 if (NULL == binaryPayload)
1233 free(binaryPayload);
1237 responseData.payload = (CAPayload_t) malloc(payloadLength);
1238 if (NULL == responseData.payload)
1240 printf("Memory allocation failed!");
1241 free(binaryPayload);
1244 memcpy(responseData.payload, binaryPayload, payloadLength);
1245 responseData.payloadSize = payloadLength;
1248 free(binaryPayload);
1252 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1253 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1254 if (NULL == responseData.payload)
1256 printf("Memory allocation fail\n");
1259 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1260 (const char *) responseData.resourceUri);
1261 responseData.payloadSize = length;
1266 CAResponseInfo_t responseInfo = { 0 };
1267 responseInfo.result = responseCode;
1268 responseInfo.info = responseData;
1270 // send response (transportType from remoteEndpoint of request Info)
1271 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1272 if (CA_STATUS_OK != res)
1274 printf("Send response error\n");
1278 printf("Send response success\n");
1281 if (responseData.payload)
1283 free(responseData.payload);
1286 printf("=============================================\n");
1289 int get_secure_information(CAPayload_t payLoad)
1291 printf("Entering get_secure_information\n");
1295 printf("Payload is NULL\n");
1299 char *subString = NULL;
1300 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1302 printf("This is not secure resource\n");
1306 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1308 printf("This secure resource does not have port information\n");
1312 char *startPos = strstr(subString, ":");
1315 printf("Parsing failed !\n");
1319 char *endPos = strstr(startPos, "}");
1322 printf("Parsing failed !\n");
1326 char portStr[6] = {0};
1327 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1329 printf("secured port is: %s\n", portStr);
1330 return atoi(portStr);
1333 void get_resource_uri(char *URI, char *resourceURI, int length)
1335 char *startPos = URI;
1337 if (NULL != (temp = strstr(URI, "://")))
1339 startPos = strchr(temp + 3, '/');
1342 printf("Resource URI is missing\n");
1347 char *endPos = strchr(startPos, '?');
1350 endPos = URI + strlen(URI);
1354 if (endPos - startPos <= length)
1356 memcpy(resourceURI, startPos + 1, endPos - startPos);
1359 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1362 CAResult_t get_network_type()
1364 char buf[MAX_BUF_LEN] = { 0 };
1366 printf("\n=============================================\n");
1367 printf("\tselect network type\n");
1369 printf("GATT : 1\n");
1370 printf("RFCOMM : 2\n");
1371 printf("select : ");
1373 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1375 return CA_NOT_SUPPORTED ;
1378 int number = buf[0] - '0';
1380 number = (number < 0 || number > 3) ? 0 : 1 << number;
1384 g_selected_nw_type = CA_ADAPTER_IP;
1385 return CA_STATUS_OK;
1389 g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
1390 return CA_STATUS_OK;
1394 g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
1395 return CA_STATUS_OK;
1398 return CA_NOT_SUPPORTED;
1401 CAResult_t get_input_data(char *buf, int32_t length)
1403 if (!fgets(buf, length, stdin))
1405 printf("fgets error\n");
1406 return CA_STATUS_FAILED;
1410 if ( (p = strchr(buf, '\n')) != NULL )
1415 return CA_STATUS_OK;
1418 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1420 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1421 char optionData[MAX_OPT_LEN] = { 0 } ;
1423 printf("Option Num : ");
1424 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1428 int optionNum = atoi(optionNumBuf);
1430 CAHeaderOption_t * headerOpt = NULL;
1433 printf("there is no headerOption!\n");
1438 headerOpt = (CAHeaderOption_t *)calloc(1, optionNum * sizeof(CAHeaderOption_t));
1439 if (NULL == headerOpt)
1441 printf("Memory allocation failed!\n");
1446 for (i = 0; i < optionNum; i++)
1448 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1450 printf("[%d] Option ID : ", i + 1);
1451 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1456 int optionID = atoi(getOptionID);
1457 headerOpt[i].optionID = optionID;
1459 printf("[%d] Option Data : ", i + 1);
1460 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1466 memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
1468 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1470 requestData->numOptions = optionNum;
1471 requestData->options = headerOpt;
1476 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1480 printf("parameter is null\n");
1486 uint8_t startIndex = 0;
1487 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1489 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1490 startIndex = COAPS_PREFIX_LEN;
1493 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1495 printf("uri has '%s' prefix\n", COAP_PREFIX);
1496 startIndex = COAP_PREFIX_LEN;
1500 // #2. copy uri for parse
1501 int32_t len = strlen(uri) - startIndex;
1505 printf("uri length is 0!\n");
1509 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1510 if (NULL == cloneUri)
1512 printf("Out of memory\n");
1516 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1517 cloneUri[len] = '\0';
1519 char *pAddress = cloneUri;
1520 printf("pAddress : %s\n", pAddress);
1522 int res = get_address_set(pAddress, address);
1525 printf("address parse error\n");
1534 int get_address_set(const char *pAddress, addressSet_t* outAddress)
1536 if (NULL == pAddress)
1538 printf("parameter is null !\n");
1542 int32_t len = strlen(pAddress);
1546 for (int i = 0; i < len; i++)
1548 if (pAddress[i] == '.')
1553 // found port number start index
1554 if (isIp && pAddress[i] == ':')
1563 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1565 strncpy(outAddress->ipAddress, pAddress, ipLen);
1566 outAddress->ipAddress[ipLen] = '\0';
1568 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1570 strncpy(outAddress->ipAddress, pAddress, len);
1571 outAddress->ipAddress[len] = '\0';
1575 printf("IP Address too long: %d\n", ipLen==0 ? len : ipLen);
1581 outAddress->port = atoi(pAddress + ipLen + 1);
1588 void create_file(CAPayload_t bytes, size_t length)
1590 FILE *fp = fopen("sample_output.txt", "wb");
1593 fwrite(bytes, 1, length, fp);
1598 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1602 printf("parameter is null\n");
1607 CAPayload_t buffer = NULL;
1608 unsigned long fileLen = 0;
1611 file = fopen(name, "rb");
1614 fprintf(stderr, "Unable to open file, %s\n", name);
1619 fseek(file, 0, SEEK_END);
1620 fileLen = ftell(file);
1621 fseek(file, 0, SEEK_SET);
1624 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1627 fprintf(stderr, "Memory error\n");
1632 // Read file contents into buffer
1633 size_t ret = fread(buffer, fileLen, 1, file);
1636 printf("Failed to read data from file, %s\n", name);