1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 ******************************************************************/
29 #include "cainterface.h"
30 #include "oic_string.h"
32 #include "ocsecurityconfig.h"
35 #define MAX_BUF_LEN 1024
36 #define MAX_OPT_LEN 16
40 #define SECURE_DEFAULT_PORT 5684
42 #define RESOURCE_URI_LENGTH 14
44 #define SYSTEM_INVOKE_ERROR 127
45 #define SYSTEM_ERROR -1
48 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
55 #define IDENTITY ("1111111111111111")
59 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
62 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
63 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
64 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
68 char ipAddress[CA_IPADDR_SIZE];
74 CAResult_t get_network_type();
75 CAResult_t get_input_data(char *buf, int32_t length);
77 bool select_payload_type();
78 CAPayload_t get_binary_payload(size_t *payloadLength);
79 bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
80 void create_file(CAPayload_t bytes, size_t length);
82 void start_listening_server();
83 void start_discovery_server();
85 void send_request_all();
86 void send_notification();
87 void select_network();
88 void unselect_network();
89 void handle_request_response();
90 void get_network_info();
91 void send_secure_request();
93 void create_tcp_connection();
96 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
97 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
98 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
99 void send_response(const CAEndpoint_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);
102 bool get_address_set(const char *pAddress, addressSet_t* outAddress);
103 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
104 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
106 static CAToken_t g_last_request_token = NULL;
108 static const char COAP_PREFIX[] = "coap://";
109 static const char COAPS_PREFIX[] = "coaps://";
110 static const char COAP_TCP_PREFIX[] = "coap+tcp://";
112 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
113 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
114 static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1;
116 static const char SECURE_INFO_DATA[] =
117 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
118 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
120 static const char NORMAL_INFO_DATA[] =
121 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
122 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
125 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
127 void clearDtlsCredentialInfo()
129 printf("clearDtlsCredentialInfo IN\n");
132 // Initialize sensitive data to zeroes before freeing.
133 if (pskCredsBlob->creds)
135 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
136 free(pskCredsBlob->creds);
139 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
143 printf("clearDtlsCredentialInfo OUT\n");
146 // Internal API. Invoked by CA stack to retrieve credentials from this module
147 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
149 printf("CAGetDtlsPskCredentials IN\n");
152 printf("Invalid credential container");
156 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
157 if (NULL == *credInfo)
159 printf("Failed to allocate credential blob.");
163 size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
164 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
165 if (NULL == (*credInfo)->creds)
167 printf("Failed to allocate credentials.");
173 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
174 (*credInfo)->num = pskCredsBlob->num;
175 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
177 printf("CAGetDtlsPskCredentials OUT\n");
181 CAResult_t SetCredentials()
183 printf("SetCredentials IN\n");
184 pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
185 if (NULL == pskCredsBlob)
187 printf("Memory allocation failed!\n");
188 return CA_MEMORY_ALLOC_FAILED;
190 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
193 pskCredsBlob->num = 1;
195 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
196 if (NULL == pskCredsBlob->creds)
198 printf("Memory allocation failed!\n");
200 return CA_MEMORY_ALLOC_FAILED;
203 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
204 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
206 printf("SetCredentials OUT\n");
213 int ret = system("clear");
214 // shell invoke error: 127, others: -1
215 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
217 printf("Terminal Clear Error: %d\n", ret);
221 printf("=============================================\n");
222 printf("\t\tsample main\n");
223 printf("=============================================\n");
225 CAResult_t res = CAInitialize();
226 if (CA_STATUS_OK != res)
228 printf("CAInitialize fail\n");
233 * Read DTLS PSK credentials from persistent storage and
234 * set in the OC stack.
237 res = SetCredentials();
238 if (CA_STATUS_OK != res)
240 printf("SetCredentials failed\n");
244 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
245 if (CA_STATUS_OK != res)
247 printf("Set credential handler fail\n");
253 CARegisterHandler(request_handler, response_handler, error_handler);
257 CADestroyToken(g_last_request_token);
259 g_last_request_token = NULL;
263 clearDtlsCredentialInfo();
272 char menu = get_menu();
282 printf("quit..!!\n");
285 case 's': // start server
287 start_listening_server();
290 case 't': // send request
295 case 'c': // start client
297 start_discovery_server();
300 case 'r': // send request
305 case 'b': // send notification
310 case 'n': // select network
315 case 'x': // unselect network
320 case 'h': // handle request response
322 handle_request_response();
328 start_discovery_server();
329 send_secure_request();
330 while (g_received == 0)
333 handle_request_response();
339 start_listening_server();
343 handle_request_response();
347 case 'g': // get network information
353 case 'p': // create tcp connection
355 create_tcp_connection();
360 printf("not supported menu!!\n");
366 void start_listening_server()
368 printf("start listening server!!\n");
370 CAResult_t res = CAStartListeningServer();
371 if (CA_STATUS_OK != res)
373 printf("start listening server fail, error code : %d\n", res);
377 printf("start listening server success\n");
381 void start_discovery_server()
383 printf("start discovery client!!\n");
385 CAResult_t res = CAStartDiscoveryServer();
386 if (CA_STATUS_OK != res)
388 printf("start discovery client fail, error code : %d\n", res);
392 printf("start discovery client success\n");
396 bool select_payload_type()
398 char buf[MAX_BUF_LEN]={0};
399 printf("\n=============================================\n");
400 printf("Normal Payload : 0\nBig Payload : 1\n");
401 printf("select Payload type : ");
403 CAResult_t res = get_input_data(buf, sizeof(buf));
404 if (CA_STATUS_OK != res)
406 printf("Payload type selection error\n");
407 printf("Default: Using normal Payload\n");
411 return (buf[0] == '1') ? true : false;
414 CAPayload_t get_binary_payload(size_t *payloadLength)
416 CAPayload_t binaryPayload = NULL;
417 bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
423 return binaryPayload;
428 CAResult_t res = get_network_type();
429 if (CA_STATUS_OK != res)
434 printf("Do you want to send secure request ?.... enter (0/1): ");
436 char secureRequest[MAX_BUF_LEN] = {0};
437 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
442 if (strcmp(secureRequest, "1") == 0)
444 printf("Enter the URI like below....\n");
445 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
447 else if (strcmp(secureRequest, "0") == 0)
449 printf("Enter the URI like below....\n");
450 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
451 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
453 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for CI )\n");
458 printf("Input data is wrong value\n");
462 char uri[MAX_BUF_LEN] = {'\0'};
463 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
468 // create remote endpoint
469 CAEndpoint_t *endpoint = NULL;
470 CATransportFlags_t flags;
472 printf("URI : %s\n", uri);
473 addressSet_t address = {{}, 0};
474 parsing_coap_uri(uri, &address, &flags);
476 res = CACreateEndpoint(flags, g_selected_nw_type,
477 (const char*)address.ipAddress, address.port, &endpoint);
478 if (CA_STATUS_OK != res || !endpoint)
480 printf("Failed to create remote endpoint, error code : %d\n", res);
484 printf("\n=============================================\n");
485 printf("0:CON, 1:NON\n");
486 printf("select message type : ");
488 char buf[MAX_BUF_LEN] = { 0 };
489 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
491 CADestroyEndpoint(endpoint);
495 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
498 CAToken_t token = NULL;
499 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
501 res = CAGenerateToken(&token, tokenLength);
502 if ((CA_STATUS_OK != res) || (!token))
504 printf("Token generate error, error code : %d\n", res);
505 CADestroyEndpoint(endpoint);
509 printf("Generated token %s\n", token);
511 // extract relative resourceuri from give uri
512 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
513 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
514 printf("resourceURI : %s\n", resourceURI);
516 // create request data
517 CAInfo_t requestData = { .type = msgType,
520 .tokenLength = tokenLength,
525 .resourceUri = (CAURI_t)resourceURI };
527 if (strcmp(secureRequest, "1") == 0)
529 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
530 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
531 if (NULL == requestData.payload)
533 printf("Memory allocation fail\n");
534 CADestroyEndpoint(endpoint);
535 CADestroyToken(token);
538 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
539 (const char *) resourceURI, g_local_secure_port);
540 requestData.payloadSize = length;
544 bool useBigPayload = select_payload_type();
547 size_t payloadLength = 0;
548 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
552 CADestroyToken(token);
553 CADestroyEndpoint(endpoint);
557 requestData.payload = (CAPayload_t) malloc(payloadLength);
558 if (NULL == requestData.payload)
560 printf("Memory allocation failed!");
562 CADestroyToken(token);
563 CADestroyEndpoint(endpoint);
566 memcpy(requestData.payload, binaryPayload, payloadLength);
567 requestData.payloadSize = payloadLength;
574 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
575 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
576 if (NULL == requestData.payload)
578 printf("Memory allocation fail\n");
579 CADestroyEndpoint(endpoint);
580 CADestroyToken(token);
583 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
584 (const char *) resourceURI);
585 requestData.payloadSize = length;
589 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
591 CARequestInfo_t requestInfo = { .method = CA_GET,
593 .isMulticast = false };
596 res = CASendRequest(endpoint, &requestInfo);
597 if (CA_STATUS_OK != res)
599 printf("Could not send request : %d\n", res);
608 CADestroyToken(token);
609 // destroy remote endpoint
610 CADestroyEndpoint(endpoint);
611 free(requestData.payload);
613 printf("=============================================\n");
616 void send_secure_request()
618 char uri[MAX_BUF_LEN];
619 char ipv4addr[CA_IPADDR_SIZE];
621 printf("\n=============================================\n");
622 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
624 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
628 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
630 // create remote endpoint
631 CAEndpoint_t *endpoint = NULL;
632 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
633 if (CA_STATUS_OK != res)
635 printf("Failed to create remote endpoint, error code: %d\n", res);
640 CAToken_t token = NULL;
641 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
643 res = CAGenerateToken(&token, tokenLength);
644 if (CA_STATUS_OK != res)
646 printf("Token generate error, error code : %d\n", res);
650 printf("Generated token %s\n", token);
652 // create request data
653 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
656 .tokenLength = tokenLength,
661 .resourceUri = NULL };
663 CARequestInfo_t requestInfo = { .method = CA_GET,
665 .isMulticast = false };
668 CASendRequest(endpoint, &requestInfo);
672 CADestroyToken(token);
673 CADestroyEndpoint(endpoint);
674 printf("=============================================\n");
678 void send_request_all()
680 CAResult_t res = get_network_type();
681 if (CA_STATUS_OK != res)
686 printf("\n=============================================\n");
687 printf("ex) /a/light\n");
688 printf("resource uri : ");
690 char resourceURI[MAX_BUF_LEN] = { 0 };
691 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
696 // create remote endpoint
697 CAEndpoint_t *group = NULL;
698 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
699 if (CA_STATUS_OK != res)
701 printf("Create remote endpoint error, error code: %d\n", res);
706 CAToken_t token = NULL;
707 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
709 res = CAGenerateToken(&token, tokenLength);
710 if ((CA_STATUS_OK != res) || (!token))
712 printf("Token generate error!!\n");
713 CADestroyEndpoint(group);
717 printf("generated token %s\n", token);
719 // create request data
720 CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
721 size_t payloadSize = strlen((const char *) payload);
723 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
726 .tokenLength = tokenLength,
730 .payloadSize = payloadSize,
731 .resourceUri = (CAURI_t) resourceURI };
733 CARequestInfo_t requestInfo = { .method = CA_GET,
735 .isMulticast = true };
737 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
740 res = CASendRequest(group, &requestInfo);
741 if (CA_STATUS_OK != res)
743 printf("Could not send request to all\n");
744 CADestroyToken(token);
748 CADestroyToken(g_last_request_token);
749 g_last_request_token = token;
757 // destroy remote endpoint
758 CADestroyEndpoint(group);
760 printf("=============================================\n");
763 void send_notification()
765 CAResult_t res = get_network_type();
766 if (CA_STATUS_OK != res)
771 printf("\n=============================================\n");
772 printf("Enter the URI like below....\n");
773 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
774 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
776 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for CI )\n");
780 char uri[MAX_BUF_LEN] = { 0 };
781 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
786 printf("\n=============================================\n");
787 printf("\tselect message type\n");
791 printf("RESET : 3\n");
794 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
795 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
800 int messageType = messageTypeBuf[0] - '0';
802 CATransportFlags_t flags;
803 addressSet_t address = {{}, 0};
804 parsing_coap_uri(uri, &address, &flags);
806 // create remote endpoint
807 CAEndpoint_t *endpoint = NULL;
808 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
809 if (CA_STATUS_OK != res)
811 printf("Create remote endpoint error, error code: %d\n", res);
816 CAToken_t token = NULL;
817 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
819 res = CAGenerateToken(&token, tokenLength);
820 if ((CA_STATUS_OK != res) || (!token))
822 printf("Token generate error!!\n");
823 CADestroyEndpoint(endpoint);
827 printf("Generated token %s\n", token);
829 // create response data
830 CAPayload_t payload = (CAPayload_t) "TempNotificationData";
831 size_t payloadSize = strlen((const char *) payload);
833 CAInfo_t respondData = { .type = messageType,
836 .tokenLength = tokenLength,
840 .payloadSize = payloadSize,
841 .resourceUri = (CAURI_t)uri };
843 CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
844 .info = respondData };
847 res = CASendNotification(endpoint, &responseInfo);
848 if (CA_STATUS_OK != res)
850 printf("Send notification error, error code: %d\n", res);
854 printf("Send notification success\n");
858 CADestroyToken(token);
859 // destroy remote endpoint
860 CADestroyEndpoint(endpoint);
862 printf("\n=============================================\n");
865 void select_network()
867 printf("\n=============================================\n");
868 printf("\tselect network\n");
870 printf("GATT : 1\n");
871 printf("RFCOMM : 2\n");
877 char buf[MAX_BUF_LEN] = { 0 };
878 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
883 int number = buf[0] - '0';
885 if (number < 0 || number > 5)
887 printf("Invalid network type\n");
891 CAResult_t res = CASelectNetwork(1 << number);
892 if (CA_STATUS_OK != res)
894 printf("Select network error\n");
898 printf("Select network success\n");
901 printf("=============================================\n");
904 void unselect_network()
906 printf("\n=============================================\n");
907 printf("\tunselect enabled network\n");
909 printf("GATT : 1\n");
910 printf("RFCOMM : 2\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 > 5)
926 printf("Invalid network type\n");
930 CAResult_t res = CAUnSelectNetwork(1 << number);
931 if (CA_STATUS_OK != res)
933 printf("Unselect network error\n");
937 printf("Unselect network success\n");
940 printf("=============================================\n");
945 printf("\n=============================================\n");
946 printf("\t\tMenu\n");
947 printf("\ts : start server\n");
948 printf("\tc : start client\n");
949 printf("\tr : send request\n");
950 printf("\tt : send request to all\n");
951 printf("\tb : send notification\n");
952 printf("\tn : select network\n");
953 printf("\tx : unselect network\n");
954 printf("\tg : get network information\n");
955 printf("\th : handle request response\n");
956 printf("\tz : run static server\n");
957 printf("\tw : send secure request\n");
959 printf("\tp : create tcp connection\n");
961 printf("\tq : quit\n");
962 printf("=============================================\n");
965 char buf[MAX_BUF_LEN] = { 0 };
966 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
968 printf("Failed to get input data\n");
974 void handle_request_response()
976 printf("Handle_request_response\n");
978 CAResult_t res = CAHandleRequestResponse();
979 if (CA_STATUS_OK != res)
981 printf("Handle request error, error code: %d\n", res);
985 printf("Handle request success\n");
989 void get_network_info()
991 CAEndpoint_t *tempInfo = NULL;
992 uint32_t tempSize = 0;
994 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
995 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
997 printf("Network not connected\n");
1002 printf("################## Network Information #######################\n");
1003 printf("Network info total size is %d\n\n", tempSize);
1005 for (uint32_t index = 0; index < tempSize; index++)
1007 printf("Type: %d\n", tempInfo[index].adapter);
1008 printf("Address: %s\n", tempInfo[index].addr);
1009 if (CA_ADAPTER_IP == tempInfo[index].adapter)
1011 printf("Port: %d\n", tempInfo[index].port);
1013 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
1015 if (tempInfo[index].flags & CA_SECURE)
1017 g_local_secure_port = tempInfo[index].port;
1018 printf("Secured: in global %d\n\n", g_local_secure_port);
1023 printf("##############################################################");
1026 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
1028 if (NULL == object || NULL == requestInfo)
1030 printf("Input parameter is NULL\n");
1034 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1035 && (memcmp(g_last_request_token, requestInfo->info.token,
1036 CA_MAX_TOKEN_LEN) == 0))
1038 printf("token is same. received request of it's own. skip.. \n");
1042 printf("##########received request from remote device #############\n");
1043 if (CA_ADAPTER_IP == object->adapter)
1045 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1046 object->port, object->flags & CA_SECURE);
1050 printf("Remote Address: %s \n", object->addr);
1052 printf("Data: %s\n", requestInfo->info.payload);
1053 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1055 if (requestInfo->info.options)
1057 uint32_t len = requestInfo->info.numOptions;
1059 for (i = 0; i < len; i++)
1061 printf("Option %d\n", i + 1);
1062 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1063 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1064 requestInfo->info.options[i].optionData);
1067 printf("############################################################\n");
1069 //Check if this has secure communication information
1070 if (requestInfo->info.payload &&
1071 (CA_ADAPTER_IP == object->adapter))
1073 int securePort = get_secure_information(requestInfo->info.payload);
1074 if (0 < securePort) //Set the remote endpoint secure details and send response
1076 printf("This is secure resource...\n");
1078 CAEndpoint_t *endpoint = NULL;
1079 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1080 object->port, &endpoint))
1082 printf("Failed to create duplicate of remote endpoint!\n");
1085 endpoint->flags = CA_SECURE;
1091 // if received message is bulk data, create output file
1092 if ((requestInfo->info.payload) &&
1093 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1095 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1099 printf("Send response with URI\n");
1100 send_response(object, &requestInfo->info);
1105 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1107 printf("##########Received response from remote device #############\n");
1108 if (CA_ADAPTER_IP == object->adapter)
1110 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1111 object->port, object->flags & CA_SECURE);
1115 printf("Remote Address: %s \n", object->addr);
1117 printf("response result : %d\n", responseInfo->result);
1118 printf("Data: %s\n", responseInfo->info.payload);
1119 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1120 printf("Token: %s\n", responseInfo->info.token);
1121 if (responseInfo->info.options)
1123 uint32_t len = responseInfo->info.numOptions;
1125 for (i = 0; i < len; i++)
1127 printf("Option %d\n", i + 1);
1128 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1129 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1130 responseInfo->info.options[i].optionData);
1133 printf("############################################################\n");
1136 //Check if this has secure communication information
1137 if (responseInfo->info.payload)
1139 int securePort = get_secure_information(responseInfo->info.payload);
1140 if (0 < securePort) //Set the remote endpoint secure details and send response
1142 printf("This is secure resource...\n");
1147 // if received message is bulk data, create output file
1148 if ((responseInfo->info.payload) &&
1149 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1151 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1156 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1159 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1163 const CAInfo_t *info = &errorInfo->info;
1164 printf("Error Handler, ErrorInfo :\n");
1165 printf("Error Handler result : %d\n", errorInfo->result);
1166 printf("Error Handler token : %s\n", info->token);
1167 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1168 printf("Error Handler type : %d\n", info->type);
1169 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1170 printf("Error Handler payload : %s\n", info->payload);
1172 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1174 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1176 else if(CA_SEND_FAILED == errorInfo->result)
1178 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1180 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1182 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1184 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1186 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1188 else if(CA_STATUS_FAILED == errorInfo->result)
1190 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1193 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1198 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1200 printf("entering send_response\n");
1202 printf("\n=============================================\n");
1203 printf("\tselect message type\n");
1204 printf("CON : 0\n");
1205 printf("NON : 1\n");
1206 printf("ACK : 2\n");
1207 printf("RESET : 3\n");
1208 printf("select : ");
1210 char buf[MAX_BUF_LEN] = { 0 };
1211 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1216 int messageType = buf[0] - '0';
1217 if (0 > messageType || 3 < messageType)
1219 printf("Invalid message type\n");
1223 int responseCode = 0 ;
1224 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1225 if (CA_MSG_RESET != messageType)
1227 printf("\n=============================================\n");
1228 printf("\tselect response code\n");
1229 printf("EMPTY : 0\n");
1230 printf("SUCCESS : 200\n");
1231 printf("CREATED : 201\n");
1232 printf("DELETED : 202\n");
1233 printf("VALID : 203\n");
1234 printf("CHANGED : 204\n");
1235 printf("CONTENT : 205\n");
1236 printf("BAD_REQ : 400\n");
1237 printf("BAD_OPT : 402\n");
1238 printf("NOT_FOUND : 404\n");
1239 printf("INTERNAL_SERVER_ERROR : 500\n");
1240 printf("RETRANSMIT_TIMEOUT : 504\n");
1241 printf("select : ");
1243 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1247 responseCode = atoi(responseCodeBuf);
1250 // create response data
1251 uint16_t messageId = (info != NULL) ? info->messageId : 0;
1252 CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1254 CAInfo_t responseData = { .type = messageType,
1255 .messageId = messageId,
1262 .resourceUri = resourceUri };
1264 if(CA_MSG_RESET != messageType)
1266 responseData.token = (info != NULL) ? info->token : NULL;
1267 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1269 if (endpoint->flags & CA_SECURE)
1271 if(!responseData.resourceUri)
1273 printf("resourceUri not available in SECURE\n");
1276 printf("Sending response on secure communication\n");
1278 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1279 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1280 if (NULL == responseData.payload)
1282 printf("Memory allocation fail\n");
1285 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1286 (const char *) responseData.resourceUri, g_local_secure_port);
1287 responseData.payloadSize = length;
1291 printf("Sending response on non-secure communication\n");
1293 bool useBigPayload = select_payload_type();
1296 size_t payloadLength = 0;
1297 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1298 if (NULL == binaryPayload)
1300 free(binaryPayload);
1304 responseData.payload = (CAPayload_t) malloc(payloadLength);
1305 if (NULL == responseData.payload)
1307 printf("Memory allocation failed!");
1308 free(binaryPayload);
1311 memcpy(responseData.payload, binaryPayload, payloadLength);
1312 responseData.payloadSize = payloadLength;
1315 free(binaryPayload);
1319 if(!responseData.resourceUri)
1321 printf("resourceUri not available in NON-SECURE\n");
1324 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1325 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1326 if (NULL == responseData.payload)
1328 printf("Memory allocation fail\n");
1331 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1332 (const char *) responseData.resourceUri);
1333 responseData.payloadSize = length;
1338 CAResponseInfo_t responseInfo = { .result = responseCode,
1339 .info = responseData };
1341 // send response (transportType from remoteEndpoint of request Info)
1342 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1343 if (CA_STATUS_OK != res)
1345 printf("Send response error\n");
1349 printf("Send response success\n");
1352 if (responseData.payload)
1354 free(responseData.payload);
1357 printf("=============================================\n");
1360 int get_secure_information(CAPayload_t payLoad)
1362 printf("Entering get_secure_information\n");
1366 printf("Payload is NULL\n");
1370 char *subString = NULL;
1371 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1373 printf("This is not secure resource\n");
1377 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1379 printf("This secure resource does not have port information\n");
1383 char *startPos = strstr(subString, ":");
1386 printf("Parsing failed !\n");
1390 char *endPos = strstr(startPos, "}");
1393 printf("Parsing failed !\n");
1397 char portStr[6] = {0};
1398 OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1399 printf("secured port is: %s\n", portStr);
1400 return atoi(portStr);
1403 void get_resource_uri(char *URI, char *resourceURI, int length)
1405 char *startPos = URI;
1407 if (NULL != (temp = strstr(URI, "://")))
1409 startPos = strchr(temp + 3, '/');
1412 printf("Resource URI is missing\n");
1417 char *endPos = strchr(startPos, '?');
1420 endPos = URI + strlen(URI);
1424 if (endPos - startPos <= length)
1426 OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1429 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1432 CAResult_t get_network_type()
1434 char buf[MAX_BUF_LEN] = { 0 };
1436 printf("\n=============================================\n");
1437 printf("\tselect network type\n");
1439 printf("GATT : 1\n");
1440 printf("RFCOMM : 2\n");
1444 printf("select : ");
1446 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1448 return CA_NOT_SUPPORTED ;
1451 int number = buf[0] - '0';
1453 number = (number < 0 || number > 5) ? 0 : 1 << number;
1458 case CA_ADAPTER_GATT_BTLE:
1459 case CA_ADAPTER_RFCOMM_BTEDR:
1461 case CA_ADAPTER_CLOUD_INTERFACE:
1463 g_selected_nw_type = number;
1464 return CA_STATUS_OK;
1466 return CA_NOT_SUPPORTED;
1470 CAResult_t get_input_data(char *buf, int32_t length)
1472 if (!fgets(buf, length, stdin))
1474 printf("fgets error\n");
1475 return CA_STATUS_FAILED;
1479 if ( (p = strchr(buf, '\n')) != NULL )
1484 return CA_STATUS_OK;
1487 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1489 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1490 char optionData[MAX_OPT_LEN] = { 0 } ;
1492 printf("Option Num : ");
1493 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1497 int optionNum = atoi(optionNumBuf);
1499 CAHeaderOption_t * headerOpt = NULL;
1502 printf("there is no headerOption!\n");
1505 else if (optionNum > MAX_OPT_LEN)
1507 printf("Too many header options!\n");
1512 headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1513 if (NULL == headerOpt)
1515 printf("Memory allocation failed!\n");
1520 for (i = 0; i < optionNum; i++)
1522 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1524 printf("[%d] Option ID : ", i + 1);
1525 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1530 int optionID = atoi(getOptionID);
1531 headerOpt[i].optionID = optionID;
1533 printf("[%d] Option Data : ", i + 1);
1534 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1540 OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1542 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1544 requestData->numOptions = optionNum;
1545 requestData->options = headerOpt;
1550 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1554 printf("parameter is null\n");
1560 uint8_t startIndex = 0;
1561 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1563 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1564 startIndex = COAPS_PREFIX_LEN;
1567 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1569 printf("uri has '%s' prefix\n", COAP_PREFIX);
1570 startIndex = COAP_PREFIX_LEN;
1574 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1576 printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1577 startIndex = COAP_TCP_PREFIX_LEN;
1578 *flags = CA_IPV4_TCP;
1582 // #2. copy uri for parse
1583 int32_t len = strlen(uri) - startIndex;
1587 printf("uri length is 0!\n");
1591 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1592 if (NULL == cloneUri)
1594 printf("Out of memory\n");
1598 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1599 cloneUri[len] = '\0';
1601 char *pAddress = cloneUri;
1602 printf("pAddress : %s\n", pAddress);
1604 if (!get_address_set(pAddress, address))
1606 printf("address parse error\n");
1615 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1617 if (NULL == pAddress)
1619 printf("parameter is null !\n");
1623 size_t len = strlen(pAddress);
1627 for (size_t i = 0; i < len; i++)
1629 if (pAddress[i] == '.')
1634 // found port number start index
1635 if (isIp && pAddress[i] == ':')
1644 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1646 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1649 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1651 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1656 printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1662 outAddress->port = atoi(pAddress + ipLen + 1);
1672 void create_file(CAPayload_t bytes, size_t length)
1674 FILE *fp = fopen("sample_output.txt", "wb");
1677 fwrite(bytes, 1, length, fp);
1682 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1686 printf("parameter is null\n");
1691 CAPayload_t buffer = NULL;
1692 unsigned long fileLen = 0;
1695 file = fopen(name, "rb");
1698 fprintf(stderr, "Unable to open file, %s\n", name);
1703 fseek(file, 0, SEEK_END);
1704 fileLen = ftell(file);
1705 fseek(file, 0, SEEK_SET);
1708 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1711 fprintf(stderr, "Memory error\n");
1716 // Read file contents into buffer
1717 size_t ret = fread(buffer, fileLen, 1, file);
1720 printf("Failed to read data from file, %s\n", name);
1735 void create_tcp_connection()
1737 printf("Enter the CI Server information....\n");
1739 char address[MAX_BUF_LEN] = {'\0'};
1740 if (CA_STATUS_OK != get_input_data(address, MAX_BUF_LEN))
1745 char port[MAX_BUF_LEN] = {'\0'};
1746 if (CA_STATUS_OK != get_input_data(port, MAX_BUF_LEN))
1751 int portNum = atoi(port);
1752 CACIServerInfo_t serverInfo = { .u4tcp.port = portNum };
1753 strncpy(serverInfo.addr, address, strlen(address));
1755 CAResult_t res = CACreateTCPConnection(&serverInfo);
1756 if (CA_STATUS_OK != res)
1758 printf("Failed to create TCP Connection");