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 #define MAX_BUF_LEN 1024
33 #define MAX_OPT_LEN 16
37 #define SECURE_DEFAULT_PORT 5684
39 #define RESOURCE_URI_LENGTH 14
41 #define SYSTEM_INVOKE_ERROR 127
42 #define SYSTEM_ERROR -1
45 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
48 // Iotivity Device Identity.
49 const unsigned char IDENTITY[] = ("1111111111111111");
51 // PSK between this device and peer device.
52 const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
55 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
56 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
57 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
61 char ipAddress[CA_IPADDR_SIZE];
67 CAResult_t get_network_type();
68 CAResult_t get_input_data(char *buf, int32_t length);
70 bool select_payload_type();
71 CAPayload_t get_binary_payload(size_t *payloadLength);
72 bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
73 void create_file(CAPayload_t bytes, size_t length);
75 void start_listening_server();
76 void start_discovery_server();
78 void send_request_all();
79 void send_notification();
80 void select_network();
81 void unselect_network();
82 void handle_request_response();
83 void get_network_info();
84 void send_secure_request();
86 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
87 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
88 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
89 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
90 void get_resource_uri(char *URI, char *resourceURI, int length);
91 int get_secure_information(CAPayload_t payLoad);
92 bool get_address_set(const char *pAddress, addressSet_t* outAddress);
93 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
94 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
96 static CAToken_t g_last_request_token = NULL;
98 static const char COAP_PREFIX[] = "coap://";
99 static const char COAPS_PREFIX[] = "coaps://";
100 static const char COAP_TCP_PREFIX[] = "coap+tcp://";
102 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
103 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
104 static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1;
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\":"
110 static const char NORMAL_INFO_DATA[] =
111 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
112 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
116 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
121 int * GetCRLResource()
125 #endif //__WITH_X509__
127 // Internal API. Invoked by CA stack to retrieve credentials from this module
128 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
129 const unsigned char *desc, size_t desc_len,
130 unsigned char *result, size_t result_length)
132 printf("CAGetDtlsPskCredentials IN\n");
143 case CA_DTLS_PSK_HINT:
144 case CA_DTLS_PSK_IDENTITY:
146 if (result_length < sizeof(IDENTITY))
148 printf("ERROR : Wrong value for result for storing IDENTITY");
152 memcpy(result, IDENTITY, sizeof(IDENTITY));
153 ret = sizeof(IDENTITY);
156 case CA_DTLS_PSK_KEY:
158 if ((desc_len == sizeof(IDENTITY)) &&
159 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
161 if (result_length < sizeof(RS_CLIENT_PSK))
163 printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
167 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
168 ret = sizeof(RS_CLIENT_PSK);
174 printf("Wrong value passed for PSK_CRED_TYPE.");
178 printf("CAGetDtlsPskCredentials OUT\n");
182 #endif //__WITH_DTLS__
186 int ret = system("clear");
187 // shell invoke error: 127, others: -1
188 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
190 printf("Terminal Clear Error: %d\n", ret);
194 printf("=============================================\n");
195 printf("\t\tsample main\n");
196 printf("=============================================\n");
198 CAResult_t res = CAInitialize();
199 if (CA_STATUS_OK != res)
201 printf("CAInitialize fail\n");
205 // Set the PSK Credentials callback handler.
207 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
208 if (CA_STATUS_OK != res)
210 printf("Register credential handler fail\n");
216 CARegisterHandler(request_handler, response_handler, error_handler);
220 CADestroyToken(g_last_request_token);
222 g_last_request_token = NULL;
232 char menu = get_menu();
242 printf("quit..!!\n");
245 case 's': // start server
247 start_listening_server();
250 case 't': // send request
255 case 'c': // start client
257 start_discovery_server();
260 case 'r': // send request
265 case 'b': // send notification
270 case 'n': // select network
275 case 'x': // unselect network
280 case 'h': // handle request response
282 handle_request_response();
288 start_discovery_server();
289 send_secure_request();
290 while (g_received == 0)
293 handle_request_response();
299 start_listening_server();
303 handle_request_response();
307 case 'g': // get network information
313 printf("not supported menu!!\n");
319 void start_listening_server()
321 printf("start listening server!!\n");
323 CAResult_t res = CAStartListeningServer();
324 if (CA_STATUS_OK != res)
326 printf("start listening server fail, error code : %d\n", res);
330 printf("start listening server success\n");
334 void start_discovery_server()
336 printf("start discovery client!!\n");
338 CAResult_t res = CAStartDiscoveryServer();
339 if (CA_STATUS_OK != res)
341 printf("start discovery client fail, error code : %d\n", res);
345 printf("start discovery client success\n");
349 bool select_payload_type()
351 char buf[MAX_BUF_LEN]={0};
352 printf("\n=============================================\n");
353 printf("Normal Payload : 0\nBig Payload : 1\n");
354 printf("select Payload type : ");
356 CAResult_t res = get_input_data(buf, sizeof(buf));
357 if (CA_STATUS_OK != res)
359 printf("Payload type selection error\n");
360 printf("Default: Using normal Payload\n");
364 return (buf[0] == '1') ? true : false;
367 CAPayload_t get_binary_payload(size_t *payloadLength)
369 CAPayload_t binaryPayload = NULL;
370 bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
376 return binaryPayload;
381 CAResult_t res = get_network_type();
382 if (CA_STATUS_OK != res)
387 printf("Do you want to send secure request ?.... enter (0/1): ");
389 char secureRequest[MAX_BUF_LEN] = {0};
390 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
395 if (strcmp(secureRequest, "1") == 0)
397 printf("Enter the URI like below....\n");
398 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
400 else if (strcmp(secureRequest, "0") == 0)
402 printf("Enter the URI like below....\n");
403 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
404 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
405 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
409 printf("Input data is wrong value\n");
413 char uri[MAX_BUF_LEN] = {'\0'};
414 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
419 // create remote endpoint
420 CAEndpoint_t *endpoint = NULL;
421 CATransportFlags_t flags;
423 printf("URI : %s\n", uri);
424 addressSet_t address = {{}, 0};
425 parsing_coap_uri(uri, &address, &flags);
427 res = CACreateEndpoint(flags, g_selected_nw_type,
428 (const char*)address.ipAddress, address.port, &endpoint);
429 if (CA_STATUS_OK != res || !endpoint)
431 printf("Failed to create remote endpoint, error code : %d\n", res);
435 printf("\n=============================================\n");
436 printf("0:CON, 1:NON\n");
437 printf("select message type : ");
439 char buf[MAX_BUF_LEN] = { 0 };
440 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
442 CADestroyEndpoint(endpoint);
446 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
449 CAToken_t token = NULL;
450 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
452 res = CAGenerateToken(&token, tokenLength);
453 if ((CA_STATUS_OK != res) || (!token))
455 printf("Token generate error, error code : %d\n", res);
456 CADestroyEndpoint(endpoint);
460 printf("Generated token %s\n", token);
462 // extract relative resourceuri from give uri
463 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
464 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
465 printf("resourceURI : %s\n", resourceURI);
467 // create request data
468 CAInfo_t requestData = { .type = msgType,
471 .tokenLength = tokenLength,
476 .resourceUri = (CAURI_t)resourceURI };
478 if (strcmp(secureRequest, "1") == 0)
480 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
481 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
482 if (NULL == requestData.payload)
484 printf("Memory allocation fail\n");
485 CADestroyEndpoint(endpoint);
486 CADestroyToken(token);
489 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
490 (const char *) resourceURI, g_local_secure_port);
491 requestData.payloadSize = length;
495 bool useBigPayload = select_payload_type();
498 size_t payloadLength = 0;
499 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
503 CADestroyToken(token);
504 CADestroyEndpoint(endpoint);
508 requestData.payload = (CAPayload_t) malloc(payloadLength);
509 if (NULL == requestData.payload)
511 printf("Memory allocation failed!");
513 CADestroyToken(token);
514 CADestroyEndpoint(endpoint);
517 memcpy(requestData.payload, binaryPayload, payloadLength);
518 requestData.payloadSize = payloadLength;
525 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
526 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
527 if (NULL == requestData.payload)
529 printf("Memory allocation fail\n");
530 CADestroyEndpoint(endpoint);
531 CADestroyToken(token);
534 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
535 (const char *) resourceURI);
536 requestData.payloadSize = length;
540 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
542 CARequestInfo_t requestInfo = { .method = CA_GET,
544 .isMulticast = false };
547 res = CASendRequest(endpoint, &requestInfo);
548 if (CA_STATUS_OK != res)
550 printf("Could not send request : %d\n", res);
559 CADestroyToken(token);
560 // destroy remote endpoint
561 CADestroyEndpoint(endpoint);
562 free(requestData.payload);
564 printf("=============================================\n");
567 void send_secure_request()
569 char uri[MAX_BUF_LEN];
570 char ipv4addr[CA_IPADDR_SIZE];
572 printf("\n=============================================\n");
573 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
575 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
579 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
581 // create remote endpoint
582 CAEndpoint_t *endpoint = NULL;
583 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
584 if (CA_STATUS_OK != res)
586 printf("Failed to create remote endpoint, error code: %d\n", res);
591 CAToken_t token = NULL;
592 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
594 res = CAGenerateToken(&token, tokenLength);
595 if (CA_STATUS_OK != res)
597 printf("Token generate error, error code : %d\n", res);
601 printf("Generated token %s\n", token);
603 // create request data
604 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
607 .tokenLength = tokenLength,
612 .resourceUri = NULL };
614 CARequestInfo_t requestInfo = { .method = CA_GET,
616 .isMulticast = false };
619 CASendRequest(endpoint, &requestInfo);
623 CADestroyToken(token);
624 CADestroyEndpoint(endpoint);
625 printf("=============================================\n");
629 void send_request_all()
631 CAResult_t res = get_network_type();
632 if (CA_STATUS_OK != res)
637 printf("\n=============================================\n");
638 printf("ex) /a/light\n");
639 printf("resource uri : ");
641 char resourceURI[MAX_BUF_LEN] = { 0 };
642 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
647 // create remote endpoint
648 CAEndpoint_t *group = NULL;
649 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
650 if (CA_STATUS_OK != res)
652 printf("Create remote endpoint error, error code: %d\n", res);
657 CAToken_t token = NULL;
658 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
660 res = CAGenerateToken(&token, tokenLength);
661 if ((CA_STATUS_OK != res) || (!token))
663 printf("Token generate error!!\n");
664 CADestroyEndpoint(group);
668 printf("generated token %s\n", token);
670 // create request data
671 CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
672 size_t payloadSize = strlen((const char *) payload);
674 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
677 .tokenLength = tokenLength,
681 .payloadSize = payloadSize,
682 .resourceUri = (CAURI_t) resourceURI };
684 CARequestInfo_t requestInfo = { .method = CA_GET,
686 .isMulticast = true };
688 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
691 res = CASendRequest(group, &requestInfo);
692 if (CA_STATUS_OK != res)
694 printf("Could not send request to all\n");
695 CADestroyToken(token);
699 CADestroyToken(g_last_request_token);
700 g_last_request_token = token;
708 // destroy remote endpoint
709 CADestroyEndpoint(group);
711 printf("=============================================\n");
714 void send_notification()
716 CAResult_t res = get_network_type();
717 if (CA_STATUS_OK != res)
722 printf("\n=============================================\n");
723 printf("Enter the URI like below....\n");
724 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
725 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
726 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
729 char uri[MAX_BUF_LEN] = { 0 };
730 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
735 printf("\n=============================================\n");
736 printf("\tselect message type\n");
740 printf("RESET : 3\n");
743 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
744 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
749 int messageType = messageTypeBuf[0] - '0';
751 CATransportFlags_t flags;
752 addressSet_t address = {{}, 0};
753 parsing_coap_uri(uri, &address, &flags);
755 // create remote endpoint
756 CAEndpoint_t *endpoint = NULL;
757 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
758 if (CA_STATUS_OK != res)
760 printf("Create remote endpoint error, error code: %d\n", res);
765 CAToken_t token = NULL;
766 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
768 res = CAGenerateToken(&token, tokenLength);
769 if ((CA_STATUS_OK != res) || (!token))
771 printf("Token generate error!!\n");
772 CADestroyEndpoint(endpoint);
776 printf("Generated token %s\n", token);
778 // create response data
779 CAPayload_t payload = (CAPayload_t) "TempNotificationData";
780 size_t payloadSize = strlen((const char *) payload);
782 CAInfo_t requestData = { .type = messageType,
785 .tokenLength = tokenLength,
789 .payloadSize = payloadSize,
790 .resourceUri = (CAURI_t) uri };
792 CARequestInfo_t requestInfo = { .method = CA_GET,
793 .info = requestData };
796 res = CASendRequest(endpoint, &requestInfo);
797 if (CA_STATUS_OK != res)
799 printf("Send notification error, error code: %d\n", res);
803 printf("Send notification success\n");
807 CADestroyToken(token);
808 // destroy remote endpoint
809 CADestroyEndpoint(endpoint);
811 printf("\n=============================================\n");
814 void select_network()
816 printf("\n=============================================\n");
817 printf("\tselect network\n");
819 printf("GATT : 1\n");
820 printf("RFCOMM : 2\n");
824 char buf[MAX_BUF_LEN] = { 0 };
825 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
830 int number = buf[0] - '0';
832 if (number < 0 || number > 4)
834 printf("Invalid network type\n");
838 CAResult_t res = CASelectNetwork(1 << number);
839 if (CA_STATUS_OK != res)
841 printf("Select network error\n");
845 printf("Select network success\n");
848 printf("=============================================\n");
851 void unselect_network()
853 printf("\n=============================================\n");
854 printf("\tunselect enabled network\n");
856 printf("GATT : 1\n");
857 printf("RFCOMM : 2\n");
861 char buf[MAX_BUF_LEN] = { 0 };
862 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
867 int number = buf[0] - '0';
869 if (number < 0 || number > 4)
871 printf("Invalid network type\n");
875 CAResult_t res = CAUnSelectNetwork(1 << number);
876 if (CA_STATUS_OK != res)
878 printf("Unselect network error\n");
882 printf("Unselect network success\n");
885 printf("=============================================\n");
890 printf("\n=============================================\n");
891 printf("\t\tMenu\n");
892 printf("\ts : start server\n");
893 printf("\tc : start client\n");
894 printf("\tr : send request\n");
895 printf("\tt : send request to all\n");
896 printf("\tb : send notification\n");
897 printf("\tn : select network\n");
898 printf("\tx : unselect network\n");
899 printf("\tg : get network information\n");
900 printf("\th : handle request response\n");
901 printf("\tz : run static server\n");
902 printf("\tw : send secure request\n");
903 printf("\tq : quit\n");
904 printf("=============================================\n");
907 char buf[MAX_BUF_LEN] = { 0 };
908 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
910 printf("Failed to get input data\n");
916 void handle_request_response()
918 printf("Handle_request_response\n");
920 CAResult_t res = CAHandleRequestResponse();
921 if (CA_STATUS_OK != res)
923 printf("Handle request error, error code: %d\n", res);
927 printf("Handle request success\n");
931 void get_network_info()
933 CAEndpoint_t *tempInfo = NULL;
934 uint32_t tempSize = 0;
936 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
937 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
939 printf("Network not connected\n");
944 printf("################## Network Information #######################\n");
945 printf("Network info total size is %d\n\n", tempSize);
947 for (uint32_t index = 0; index < tempSize; index++)
949 printf("Type: %d\n", tempInfo[index].adapter);
950 printf("Address: %s\n", tempInfo[index].addr);
951 if (CA_ADAPTER_IP == tempInfo[index].adapter)
953 printf("Port: %d\n", tempInfo[index].port);
954 printf("Secured: %s flag : %x\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" :
955 "false", tempInfo[index].flags);
957 if (tempInfo[index].flags & CA_SECURE)
959 g_local_secure_port = tempInfo[index].port;
960 printf("Secured: in global %d\n\n", g_local_secure_port);
966 printf("##############################################################");
969 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
971 if (NULL == object || NULL == requestInfo)
973 printf("Input parameter is NULL\n");
977 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
978 && (memcmp(g_last_request_token, requestInfo->info.token,
979 CA_MAX_TOKEN_LEN) == 0))
981 printf("token is same. received request of it's own. skip.. \n");
985 printf("##########received request from remote device #############\n");
986 if (CA_ADAPTER_IP == object->adapter)
988 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
989 object->port, object->flags & CA_SECURE);
993 printf("Remote Address: %s \n", object->addr);
995 printf("Data: %s\n", requestInfo->info.payload);
996 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
998 if (requestInfo->info.options)
1000 uint32_t len = requestInfo->info.numOptions;
1002 for (i = 0; i < len; i++)
1004 printf("Option %d\n", i + 1);
1005 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1006 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1007 requestInfo->info.options[i].optionData);
1010 printf("############################################################\n");
1012 //Check if this has secure communication information
1013 if (requestInfo->info.payload &&
1014 (CA_ADAPTER_IP == object->adapter))
1016 int securePort = get_secure_information(requestInfo->info.payload);
1017 if (0 < securePort) //Set the remote endpoint secure details and send response
1019 printf("This is secure resource...\n");
1021 CAEndpoint_t *endpoint = NULL;
1022 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1023 object->port, &endpoint))
1025 printf("Failed to create duplicate of remote endpoint!\n");
1028 endpoint->flags = CA_SECURE;
1034 // if received message is bulk data, create output file
1035 if ((requestInfo->info.payload) &&
1036 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1038 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1042 printf("Send response with URI\n");
1043 send_response(object, &requestInfo->info);
1048 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1050 printf("##########Received response from remote device #############\n");
1051 if (CA_ADAPTER_IP == object->adapter)
1053 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1054 object->port, object->flags & CA_SECURE);
1058 printf("Remote Address: %s \n", object->addr);
1060 printf("response result : %d\n", responseInfo->result);
1061 printf("Data: %s\n", responseInfo->info.payload);
1062 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1063 printf("Token: %s\n", responseInfo->info.token);
1064 if (responseInfo->info.options)
1066 uint32_t len = responseInfo->info.numOptions;
1068 for (i = 0; i < len; i++)
1070 printf("Option %d\n", i + 1);
1071 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1072 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1073 responseInfo->info.options[i].optionData);
1076 printf("############################################################\n");
1079 //Check if this has secure communication information
1080 if (responseInfo->info.payload)
1082 int securePort = get_secure_information(responseInfo->info.payload);
1083 if (0 < securePort) //Set the remote endpoint secure details and send response
1085 printf("This is secure resource...\n");
1090 // if received message is bulk data, create output file
1091 if ((responseInfo->info.payload) &&
1092 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1094 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1099 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1102 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1106 const CAInfo_t *info = &errorInfo->info;
1107 printf("Error Handler, ErrorInfo :\n");
1108 printf("Error Handler result : %d\n", errorInfo->result);
1109 printf("Error Handler token : %s\n", info->token);
1110 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1111 printf("Error Handler type : %d\n", info->type);
1112 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1113 printf("Error Handler payload : %s\n", info->payload);
1115 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1117 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1119 else if(CA_SEND_FAILED == errorInfo->result)
1121 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1123 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1125 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1127 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1129 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1131 else if(CA_STATUS_FAILED == errorInfo->result)
1133 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1136 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1141 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1143 printf("entering send_response\n");
1145 printf("\n=============================================\n");
1146 printf("\tselect message type\n");
1147 printf("CON : 0\n");
1148 printf("NON : 1\n");
1149 printf("ACK : 2\n");
1150 printf("RESET : 3\n");
1151 printf("select : ");
1153 char buf[MAX_BUF_LEN] = { 0 };
1154 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1159 int messageType = buf[0] - '0';
1160 if (0 > messageType || 3 < messageType)
1162 printf("Invalid message type\n");
1166 int responseCode = 0 ;
1167 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1168 if (CA_MSG_RESET != messageType)
1170 printf("\n=============================================\n");
1171 printf("\tselect response code\n");
1172 printf("EMPTY : 0\n");
1173 printf("CREATED : 201\n");
1174 printf("DELETED : 202\n");
1175 printf("VALID : 203\n");
1176 printf("CHANGED : 204\n");
1177 printf("CONTENT : 205\n");
1178 printf("BAD_REQ : 400\n");
1179 printf("BAD_OPT : 402\n");
1180 printf("NOT_FOUND : 404\n");
1181 printf("INTERNAL_SERVER_ERROR : 500\n");
1182 printf("RETRANSMIT_TIMEOUT : 504\n");
1183 printf("select : ");
1185 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1189 responseCode = atoi(responseCodeBuf);
1192 // create response data
1193 uint16_t messageId = (info != NULL) ? info->messageId : 0;
1194 CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1196 CAInfo_t responseData = { .type = messageType,
1197 .messageId = messageId,
1204 .resourceUri = resourceUri };
1206 if (CA_MSG_RESET == messageType ||
1207 (CA_MSG_ACKNOWLEDGE == messageType && CA_EMPTY == responseCode))
1209 printf("RESET or ACK/EMPTY. there will be not payload/option\n");
1214 responseData.token = (info != NULL) ? info->token : NULL;
1215 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1217 if (endpoint->flags & CA_SECURE)
1219 if(!responseData.resourceUri)
1221 printf("resourceUri not available in SECURE\n");
1224 printf("Sending response on secure communication\n");
1226 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1227 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1228 if (NULL == responseData.payload)
1230 printf("Memory allocation fail\n");
1233 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1234 (const char *) responseData.resourceUri, g_local_secure_port);
1235 responseData.payloadSize = length;
1239 printf("Sending response on non-secure communication\n");
1241 bool useBigPayload = select_payload_type();
1244 size_t payloadLength = 0;
1245 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1246 if (NULL == binaryPayload)
1248 free(binaryPayload);
1252 responseData.payload = (CAPayload_t) malloc(payloadLength);
1253 if (NULL == responseData.payload)
1255 printf("Memory allocation failed!");
1256 free(binaryPayload);
1259 memcpy(responseData.payload, binaryPayload, payloadLength);
1260 responseData.payloadSize = payloadLength;
1263 free(binaryPayload);
1267 if(!responseData.resourceUri)
1269 printf("resourceUri not available in NON-SECURE\n");
1272 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1273 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1274 if (NULL == responseData.payload)
1276 printf("Memory allocation fail\n");
1279 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1280 (const char *) responseData.resourceUri);
1281 responseData.payloadSize = length;
1286 CAResponseInfo_t responseInfo = { .result = responseCode,
1287 .info = responseData };
1289 // send response (transportType from remoteEndpoint of request Info)
1290 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1291 if (CA_STATUS_OK != res)
1293 printf("Send response error\n");
1297 printf("Send response success\n");
1300 if (responseData.payload)
1302 free(responseData.payload);
1305 printf("=============================================\n");
1308 int get_secure_information(CAPayload_t payLoad)
1310 printf("Entering get_secure_information\n");
1314 printf("Payload is NULL\n");
1318 char *subString = NULL;
1319 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1321 printf("This is not secure resource\n");
1325 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1327 printf("This secure resource does not have port information\n");
1331 char *startPos = strstr(subString, ":");
1334 printf("Parsing failed !\n");
1338 char *endPos = strstr(startPos, "}");
1341 printf("Parsing failed !\n");
1345 char portStr[6] = {0};
1346 OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1347 printf("secured port is: %s\n", portStr);
1348 return atoi(portStr);
1351 void get_resource_uri(char *URI, char *resourceURI, int length)
1353 char *startPos = URI;
1355 if (NULL != (temp = strstr(URI, "://")))
1357 startPos = strchr(temp + 3, '/');
1360 printf("Resource URI is missing\n");
1365 char *endPos = strchr(startPos, '?');
1368 endPos = URI + strlen(URI);
1372 if (endPos - startPos <= length)
1374 OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1377 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1380 CAResult_t get_network_type()
1382 char buf[MAX_BUF_LEN] = { 0 };
1384 printf("\n=============================================\n");
1385 printf("\tselect network type\n");
1387 printf("GATT : 1\n");
1388 printf("RFCOMM : 2\n");
1389 printf("TCP : 4\n");
1390 printf("select : ");
1392 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1394 return CA_NOT_SUPPORTED ;
1397 int number = buf[0] - '0';
1399 number = (number < 0 || number > 4) ? 0 : 1 << number;
1404 case CA_ADAPTER_GATT_BTLE:
1405 case CA_ADAPTER_RFCOMM_BTEDR:
1406 case CA_ADAPTER_TCP:
1407 g_selected_nw_type = number;
1408 return CA_STATUS_OK;
1410 return CA_NOT_SUPPORTED;
1414 CAResult_t get_input_data(char *buf, int32_t length)
1416 if (!fgets(buf, length, stdin))
1418 printf("fgets error\n");
1419 return CA_STATUS_FAILED;
1423 if ( (p = strchr(buf, '\n')) != NULL )
1428 return CA_STATUS_OK;
1431 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1433 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1434 char optionData[MAX_OPT_LEN] = { 0 } ;
1436 printf("Option Num : ");
1437 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1441 int optionNum = atoi(optionNumBuf);
1443 CAHeaderOption_t * headerOpt = NULL;
1446 printf("there is no headerOption!\n");
1449 else if (optionNum > MAX_OPT_LEN)
1451 printf("Too many header options!\n");
1456 headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1457 if (NULL == headerOpt)
1459 printf("Memory allocation failed!\n");
1464 for (i = 0; i < optionNum; i++)
1466 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1468 printf("[%d] Option ID : ", i + 1);
1469 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1474 int optionID = atoi(getOptionID);
1475 headerOpt[i].optionID = optionID;
1477 printf("[%d] Option Data : ", i + 1);
1478 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1484 OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1486 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1488 requestData->numOptions = optionNum;
1489 requestData->options = headerOpt;
1494 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1498 printf("parameter is null\n");
1504 uint8_t startIndex = 0;
1505 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1507 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1508 startIndex = COAPS_PREFIX_LEN;
1511 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1513 printf("uri has '%s' prefix\n", COAP_PREFIX);
1514 startIndex = COAP_PREFIX_LEN;
1517 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1519 printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1520 startIndex = COAP_TCP_PREFIX_LEN;
1524 // #2. copy uri for parse
1525 int32_t len = strlen(uri) - startIndex;
1529 printf("uri length is 0!\n");
1533 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1534 if (NULL == cloneUri)
1536 printf("Out of memory\n");
1540 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1541 cloneUri[len] = '\0';
1543 char *pAddress = cloneUri;
1544 printf("pAddress : %s\n", pAddress);
1546 if (!get_address_set(pAddress, address))
1548 printf("address parse error\n");
1557 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1559 if (NULL == pAddress)
1561 printf("parameter is null !\n");
1565 size_t len = strlen(pAddress);
1569 for (size_t i = 0; i < len; i++)
1571 if (pAddress[i] == '.')
1576 // found port number start index
1577 if (isIp && pAddress[i] == ':')
1586 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1588 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1591 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1593 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1598 printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1604 outAddress->port = atoi(pAddress + ipLen + 1);
1614 void create_file(CAPayload_t bytes, size_t length)
1616 FILE *fp = fopen("sample_output.txt", "wb");
1619 fwrite(bytes, 1, length, fp);
1624 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1628 printf("parameter is null\n");
1633 CAPayload_t buffer = NULL;
1634 unsigned long fileLen = 0;
1637 file = fopen(name, "rb");
1640 fprintf(stderr, "Unable to open file, %s\n", name);
1645 fseek(file, 0, SEEK_END);
1646 fileLen = ftell(file);
1647 fseek(file, 0, SEEK_SET);
1650 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1653 fprintf(stderr, "Memory error\n");
1658 // Read file contents into buffer
1659 size_t ret = fread(buffer, fileLen, 1, file);
1662 printf("Failed to read data from file, %s\n", name);