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(CATransportFlags_t *flags);
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 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
382 CAResult_t res = get_network_type(&flags);
383 if (CA_STATUS_OK != res)
388 printf("Do you want to send secure request ?.... enter (0/1): ");
390 char secureRequest[MAX_BUF_LEN] = {0};
391 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
396 if (strcmp(secureRequest, "1") == 0)
398 printf("Enter the URI like below....\n");
399 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
401 else if (strcmp(secureRequest, "0") == 0)
403 printf("Enter the URI like below....\n");
404 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
405 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
406 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
410 printf("Input data is wrong value\n");
414 char uri[MAX_BUF_LEN] = {'\0'};
415 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
420 printf("URI : %s\n", uri);
421 addressSet_t address = {{}, 0};
422 parsing_coap_uri(uri, &address, &flags);
424 // create remote endpoint
425 CAEndpoint_t *endpoint = NULL;
426 res = CACreateEndpoint(flags, g_selected_nw_type,
427 (const char*)address.ipAddress, address.port, &endpoint);
428 if (CA_STATUS_OK != res || !endpoint)
430 printf("Failed to create remote endpoint, error code : %d\n", res);
434 printf("\n=============================================\n");
435 printf("0:CON, 1:NON\n");
436 printf("select message type : ");
438 char buf[MAX_BUF_LEN] = { 0 };
439 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
441 CADestroyEndpoint(endpoint);
445 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
448 CAToken_t token = NULL;
449 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
451 res = CAGenerateToken(&token, tokenLength);
452 if ((CA_STATUS_OK != res) || (!token))
454 printf("Token generate error, error code : %d\n", res);
455 CADestroyEndpoint(endpoint);
459 // extract relative resourceuri from give uri
460 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
461 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
462 printf("resourceURI : %s\n", resourceURI);
464 // create request data
465 CAInfo_t requestData = { .type = msgType,
468 .tokenLength = tokenLength,
473 .resourceUri = (CAURI_t)resourceURI };
475 if (strcmp(secureRequest, "1") == 0)
477 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
478 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
479 if (NULL == requestData.payload)
481 printf("Memory allocation fail\n");
484 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
485 (const char *) resourceURI, g_local_secure_port);
486 requestData.payloadSize = length;
490 bool useBigPayload = select_payload_type();
493 size_t payloadLength = 0;
494 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
501 requestData.payload = (CAPayload_t) malloc(payloadLength);
502 if (NULL == requestData.payload)
504 printf("Memory allocation failed!");
508 memcpy(requestData.payload, binaryPayload, payloadLength);
509 requestData.payloadSize = payloadLength;
516 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
517 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
518 if (NULL == requestData.payload)
520 printf("Memory allocation fail\n");
523 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
524 (const char *) resourceURI);
525 requestData.payloadSize = length;
529 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
531 CARequestInfo_t requestInfo = { .method = CA_GET,
533 .isMulticast = false };
536 res = CASendRequest(endpoint, &requestInfo);
537 if (CA_STATUS_OK != res)
539 printf("Could not send request : %d\n", res);
543 free(requestData.payload);
547 CADestroyToken(token);
548 CADestroyEndpoint(endpoint);
549 printf("=============================================\n");
552 void send_secure_request()
554 char uri[MAX_BUF_LEN];
555 char ipv4addr[CA_IPADDR_SIZE];
557 printf("\n=============================================\n");
558 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
560 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
564 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
566 // create remote endpoint
567 CAEndpoint_t *endpoint = NULL;
568 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
569 if (CA_STATUS_OK != res)
571 printf("Failed to create remote endpoint, error code: %d\n", res);
576 CAToken_t token = NULL;
577 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
579 res = CAGenerateToken(&token, tokenLength);
580 if (CA_STATUS_OK != res)
582 printf("Token generate error, error code : %d\n", res);
586 // create request data
587 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
590 .tokenLength = tokenLength,
595 .resourceUri = NULL };
597 CARequestInfo_t requestInfo = { .method = CA_GET,
599 .isMulticast = false };
602 CASendRequest(endpoint, &requestInfo);
606 CADestroyToken(token);
607 CADestroyEndpoint(endpoint);
608 printf("=============================================\n");
612 void send_request_all()
614 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
615 CAResult_t res = get_network_type(&flags);
616 if (CA_STATUS_OK != res)
621 printf("\n=============================================\n");
622 printf("ex) /a/light\n");
623 printf("resource uri : ");
625 char resourceURI[MAX_BUF_LEN] = { 0 };
626 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
631 // create remote endpoint
632 CAEndpoint_t *group = NULL;
633 res = CACreateEndpoint(flags, g_selected_nw_type, NULL, 0, &group);
634 if (CA_STATUS_OK != res)
636 printf("Create remote endpoint error, error code: %d\n", res);
641 CAToken_t token = NULL;
642 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
644 res = CAGenerateToken(&token, tokenLength);
645 if ((CA_STATUS_OK != res) || (!token))
647 printf("Token generate error!!\n");
648 CADestroyEndpoint(group);
652 // create request data
653 CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
654 size_t payloadSize = strlen((const char *) payload);
656 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
659 .tokenLength = tokenLength,
663 .payloadSize = payloadSize,
664 .resourceUri = (CAURI_t) resourceURI };
666 CARequestInfo_t requestInfo = { .method = CA_GET,
668 .isMulticast = true };
670 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
673 res = CASendRequest(group, &requestInfo);
674 if (CA_STATUS_OK != res)
676 printf("Could not send request to all\n");
677 CADestroyToken(token);
681 CADestroyToken(g_last_request_token);
682 g_last_request_token = token;
686 // destroy remote endpoint
687 CADestroyEndpoint(group);
689 printf("=============================================\n");
692 void send_notification()
694 CATransportFlags_t flags = CA_DEFAULT_FLAGS;
695 CAResult_t res = get_network_type(&flags);
696 if (CA_STATUS_OK != res)
701 printf("\n=============================================\n");
702 printf("Enter the URI like below....\n");
703 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
704 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
705 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
708 char uri[MAX_BUF_LEN] = { 0 };
709 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
714 printf("\n=============================================\n");
715 printf("\tselect message type\n");
719 printf("RESET : 3\n");
722 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
723 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
728 int messageType = messageTypeBuf[0] - '0';
730 addressSet_t address = {{}, 0};
731 parsing_coap_uri(uri, &address, &flags);
733 // create remote endpoint
734 CAEndpoint_t *endpoint = NULL;
735 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
736 if (CA_STATUS_OK != res)
738 printf("Create remote endpoint error, error code: %d\n", res);
743 CAToken_t token = NULL;
744 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
746 res = CAGenerateToken(&token, tokenLength);
747 if ((CA_STATUS_OK != res) || (!token))
749 printf("Token generate error!!\n");
750 CADestroyEndpoint(endpoint);
754 // create response data
755 CAPayload_t payload = (CAPayload_t) "TempNotificationData";
756 size_t payloadSize = strlen((const char *) payload);
758 CAInfo_t requestData = { .type = messageType,
761 .tokenLength = tokenLength,
765 .payloadSize = payloadSize,
766 .resourceUri = (CAURI_t) uri };
768 CARequestInfo_t requestInfo = { .method = CA_GET,
769 .info = requestData };
772 res = CASendRequest(endpoint, &requestInfo);
773 if (CA_STATUS_OK != res)
775 printf("Send notification error, error code: %d\n", res);
779 printf("Send notification success\n");
783 CADestroyToken(token);
784 // destroy remote endpoint
785 CADestroyEndpoint(endpoint);
787 printf("\n=============================================\n");
790 void select_network()
792 printf("\n=============================================\n");
793 printf("\tselect network\n");
795 printf("GATT : 1\n");
796 printf("RFCOMM : 2\n");
800 char buf[MAX_BUF_LEN] = { 0 };
801 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
806 int number = buf[0] - '0';
808 if (number < 0 || number > 4)
810 printf("Invalid network type\n");
814 CAResult_t res = CASelectNetwork(1 << number);
815 if (CA_STATUS_OK != res)
817 printf("Select network error\n");
821 printf("Select network success\n");
824 printf("=============================================\n");
827 void unselect_network()
829 printf("\n=============================================\n");
830 printf("\tunselect enabled network\n");
832 printf("GATT : 1\n");
833 printf("RFCOMM : 2\n");
837 char buf[MAX_BUF_LEN] = { 0 };
838 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
843 int number = buf[0] - '0';
845 if (number < 0 || number > 4)
847 printf("Invalid network type\n");
851 CAResult_t res = CAUnSelectNetwork(1 << number);
852 if (CA_STATUS_OK != res)
854 printf("Unselect network error\n");
858 printf("Unselect network success\n");
861 printf("=============================================\n");
866 printf("\n=============================================\n");
867 printf("\t\tMenu\n");
868 printf("\ts : start server\n");
869 printf("\tc : start client\n");
870 printf("\tr : send request\n");
871 printf("\tt : send request to all\n");
872 printf("\tb : send notification\n");
873 printf("\tn : select network\n");
874 printf("\tx : unselect network\n");
875 printf("\tg : get network information\n");
876 printf("\th : handle request response\n");
877 printf("\tz : run static server\n");
878 printf("\tw : send secure request\n");
879 printf("\tq : quit\n");
880 printf("=============================================\n");
883 char buf[MAX_BUF_LEN] = { 0 };
884 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
886 printf("Failed to get input data\n");
892 void handle_request_response()
894 printf("Handle_request_response\n");
896 CAResult_t res = CAHandleRequestResponse();
897 if (CA_STATUS_OK != res)
899 printf("Handle request error, error code: %d\n", res);
903 printf("Handle request success\n");
907 void get_network_info()
909 CAEndpoint_t *tempInfo = NULL;
910 uint32_t tempSize = 0;
912 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
913 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
915 printf("Network not connected\n");
920 printf("################## Network Information #######################\n");
921 printf("Network info total size is %d\n\n", tempSize);
923 for (uint32_t index = 0; index < tempSize; index++)
925 printf("Type: %d\n", tempInfo[index].adapter);
926 printf("Address: %s\n", tempInfo[index].addr);
927 if (CA_ADAPTER_IP == tempInfo[index].adapter)
929 printf("Port: %d\n", tempInfo[index].port);
930 printf("Secured: %s flag : %x\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" :
931 "false", tempInfo[index].flags);
933 if (tempInfo[index].flags & CA_SECURE)
935 g_local_secure_port = tempInfo[index].port;
936 printf("Secured: in global %d\n\n", g_local_secure_port);
942 printf("##############################################################");
945 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
947 if (NULL == object || NULL == requestInfo)
949 printf("Input parameter is NULL\n");
953 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
954 && (memcmp(g_last_request_token, requestInfo->info.token,
955 CA_MAX_TOKEN_LEN) == 0))
957 printf("token is same. received request of it's own. skip.. \n");
961 printf("##########received request from remote device #############\n");
962 if (CA_ADAPTER_IP == object->adapter || CA_ADAPTER_TCP == object->adapter)
964 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
965 object->port, object->flags & CA_SECURE);
969 printf("Remote Address: %s \n", object->addr);
971 printf("Data: %s\n", requestInfo->info.payload);
972 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
973 printf("Resource URI: %s \n", requestInfo->info.resourceUri);
975 if (requestInfo->info.options)
977 uint32_t len = requestInfo->info.numOptions;
979 for (i = 0; i < len; i++)
981 printf("Option %d\n", i + 1);
982 printf("ID : %d\n", requestInfo->info.options[i].optionID);
983 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
984 requestInfo->info.options[i].optionData);
987 printf("############################################################\n");
989 //Check if this has secure communication information
990 if (requestInfo->info.payload && (CA_ADAPTER_IP == object->adapter))
992 int securePort = get_secure_information(requestInfo->info.payload);
993 if (0 < securePort) //Set the remote endpoint secure details and send response
995 printf("This is secure resource...\n");
997 CAEndpoint_t *endpoint = NULL;
998 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
999 object->port, &endpoint))
1001 printf("Failed to create duplicate of remote endpoint!\n");
1004 endpoint->flags = CA_SECURE;
1010 // if received message is bulk data, create output file
1011 if ((requestInfo->info.payload) &&
1012 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1014 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1018 printf("Send response with URI\n");
1019 send_response(object, &requestInfo->info);
1024 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1026 printf("##########Received response from remote device #############\n");
1027 if (CA_ADAPTER_IP == object->adapter)
1029 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1030 object->port, object->flags & CA_SECURE);
1034 printf("Remote Address: %s \n", object->addr);
1036 printf("response result : %d\n", responseInfo->result);
1037 printf("Data: %s\n", responseInfo->info.payload);
1038 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1039 printf("Token: %s\n", responseInfo->info.token);
1040 printf("Resource URI: %s \n", responseInfo->info.resourceUri);
1042 if (responseInfo->info.options)
1044 uint32_t len = responseInfo->info.numOptions;
1046 for (i = 0; i < len; i++)
1048 printf("Option %d\n", i + 1);
1049 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1050 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1051 responseInfo->info.options[i].optionData);
1054 printf("############################################################\n");
1057 //Check if this has secure communication information
1058 if (responseInfo->info.payload)
1060 int securePort = get_secure_information(responseInfo->info.payload);
1061 if (0 < securePort) //Set the remote endpoint secure details and send response
1063 printf("This is secure resource...\n");
1068 // if received message is bulk data, create output file
1069 if ((responseInfo->info.payload) &&
1070 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1072 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1077 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1080 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1084 const CAInfo_t *info = &errorInfo->info;
1085 printf("Error Handler, ErrorInfo :\n");
1086 printf("Error Handler result : %d\n", errorInfo->result);
1087 printf("Error Handler token : %s\n", info->token);
1088 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1089 printf("Error Handler type : %d\n", info->type);
1090 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1091 printf("Error Handler payload : %s\n", info->payload);
1093 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1095 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1097 else if(CA_SEND_FAILED == errorInfo->result)
1099 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1101 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1103 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1105 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1107 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1109 else if(CA_STATUS_FAILED == errorInfo->result)
1111 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1114 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1119 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1121 printf("entering send_response\n");
1123 printf("\n=============================================\n");
1124 printf("\tselect message type\n");
1125 printf("CON : 0\n");
1126 printf("NON : 1\n");
1127 printf("ACK : 2\n");
1128 printf("RESET : 3\n");
1129 printf("select : ");
1131 char buf[MAX_BUF_LEN] = { 0 };
1132 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1137 int messageType = buf[0] - '0';
1138 if (0 > messageType || 3 < messageType)
1140 printf("Invalid message type\n");
1144 int responseCode = 0 ;
1145 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1146 if (CA_MSG_RESET != messageType)
1148 printf("\n=============================================\n");
1149 printf("\tselect response code\n");
1150 printf("EMPTY : 0\n");
1151 printf("CREATED : 201\n");
1152 printf("DELETED : 202\n");
1153 printf("VALID : 203\n");
1154 printf("CHANGED : 204\n");
1155 printf("CONTENT : 205\n");
1156 printf("BAD_REQ : 400\n");
1157 printf("BAD_OPT : 402\n");
1158 printf("NOT_FOUND : 404\n");
1159 printf("INTERNAL_SERVER_ERROR : 500\n");
1160 printf("RETRANSMIT_TIMEOUT : 504\n");
1161 printf("select : ");
1163 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1167 responseCode = atoi(responseCodeBuf);
1170 // create response data
1171 uint16_t messageId = (info != NULL) ? info->messageId : 0;
1172 CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1174 CAInfo_t responseData = { .type = messageType,
1175 .messageId = messageId,
1182 .resourceUri = resourceUri };
1184 if (CA_MSG_RESET == messageType ||
1185 (CA_MSG_ACKNOWLEDGE == messageType && CA_EMPTY == responseCode))
1187 printf("RESET or ACK/EMPTY. there will be not payload/option\n");
1192 responseData.token = (info != NULL) ? info->token : NULL;
1193 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1195 if (endpoint->flags & CA_SECURE)
1197 if(!responseData.resourceUri)
1199 printf("resourceUri not available in SECURE\n");
1202 printf("Sending response on secure communication\n");
1204 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1205 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1206 if (NULL == responseData.payload)
1208 printf("Memory allocation fail\n");
1211 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1212 (const char *) responseData.resourceUri, g_local_secure_port);
1213 responseData.payloadSize = length;
1217 printf("Sending response on non-secure communication\n");
1219 bool useBigPayload = select_payload_type();
1222 size_t payloadLength = 0;
1223 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1224 if (NULL == binaryPayload)
1226 printf("Failed to read binary file");
1230 responseData.payload = (CAPayload_t) malloc(payloadLength);
1231 if (NULL == responseData.payload)
1233 printf("Memory allocation failed!");
1234 free(binaryPayload);
1237 memcpy(responseData.payload, binaryPayload, payloadLength);
1238 responseData.payloadSize = payloadLength;
1241 free(binaryPayload);
1245 if(!responseData.resourceUri)
1247 printf("resourceUri not available in NON-SECURE\n");
1250 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1251 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1252 if (NULL == responseData.payload)
1254 printf("Memory allocation fail\n");
1257 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1258 (const char *) responseData.resourceUri);
1259 responseData.payloadSize = length;
1264 CAResponseInfo_t responseInfo = { .result = responseCode,
1265 .info = responseData };
1267 // send response (transportType from remoteEndpoint of request Info)
1268 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1269 if (CA_STATUS_OK != res)
1271 printf("Send response error\n");
1275 printf("Send response success\n");
1278 free(responseData.payload);
1280 printf("=============================================\n");
1283 int get_secure_information(CAPayload_t payLoad)
1285 printf("Entering get_secure_information\n");
1289 printf("Payload is NULL\n");
1293 char *subString = NULL;
1294 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1296 printf("This is not secure resource\n");
1300 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1302 printf("This secure resource does not have port information\n");
1306 char *startPos = strstr(subString, ":");
1309 printf("Parsing failed !\n");
1313 char *endPos = strstr(startPos, "}");
1316 printf("Parsing failed !\n");
1320 char portStr[6] = {0};
1321 OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1322 printf("secured port is: %s\n", portStr);
1323 return atoi(portStr);
1326 void get_resource_uri(char *URI, char *resourceURI, int length)
1328 char *startPos = URI;
1330 if (NULL != (temp = strstr(URI, "://")))
1332 startPos = strchr(temp + 3, '/');
1335 printf("Resource URI is missing\n");
1340 char *endPos = strchr(startPos, '?');
1343 endPos = URI + strlen(URI);
1347 if (endPos - startPos <= length)
1349 OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1352 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1355 CAResult_t get_network_type(CATransportFlags_t *flags)
1357 char buf[MAX_BUF_LEN] = { 0 };
1359 printf("\n=============================================\n");
1360 printf("\tselect network type\n");
1362 printf("GATT : 1\n");
1363 printf("RFCOMM : 2\n");
1364 printf("TCP : 4\n");
1365 printf("select : ");
1367 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1369 return CA_NOT_SUPPORTED ;
1372 int number = buf[0] - '0';
1374 number = (number < 0 || number > 4) ? 0 : 1 << number;
1380 case CA_ADAPTER_GATT_BTLE:
1381 case CA_ADAPTER_RFCOMM_BTEDR:
1382 case CA_ADAPTER_TCP:
1383 g_selected_nw_type = number;
1384 return CA_STATUS_OK;
1386 return CA_NOT_SUPPORTED;
1390 CAResult_t get_input_data(char *buf, int32_t length)
1392 if (!fgets(buf, length, stdin))
1394 printf("fgets error\n");
1395 return CA_STATUS_FAILED;
1399 if ( (p = strchr(buf, '\n')) != NULL )
1404 return CA_STATUS_OK;
1407 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1409 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1410 char optionData[MAX_OPT_LEN] = { 0 } ;
1412 printf("Option Num : ");
1413 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1417 int optionNum = atoi(optionNumBuf);
1419 CAHeaderOption_t * headerOpt = NULL;
1422 printf("there is no headerOption!\n");
1425 else if (optionNum > MAX_OPT_LEN)
1427 printf("Too many header options!\n");
1432 headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1433 if (NULL == headerOpt)
1435 printf("Memory allocation failed!\n");
1440 for (i = 0; i < optionNum; i++)
1442 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1444 printf("[%d] Option ID : ", i + 1);
1445 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1450 int optionID = atoi(getOptionID);
1451 headerOpt[i].optionID = optionID;
1453 printf("[%d] Option Data : ", i + 1);
1454 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1460 OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1462 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1464 requestData->numOptions = optionNum;
1465 requestData->options = headerOpt;
1470 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1474 printf("parameter is null\n");
1480 uint8_t startIndex = 0;
1481 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1483 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1484 startIndex = COAPS_PREFIX_LEN;
1487 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1489 printf("uri has '%s' prefix\n", COAP_PREFIX);
1490 startIndex = COAP_PREFIX_LEN;
1492 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1494 printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1495 startIndex = COAP_TCP_PREFIX_LEN;
1498 // #2. copy uri for parse
1499 int32_t len = strlen(uri) - startIndex;
1503 printf("uri length is 0!\n");
1507 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1508 if (NULL == cloneUri)
1510 printf("Out of memory\n");
1514 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1515 cloneUri[len] = '\0';
1517 char *pAddress = cloneUri;
1518 printf("pAddress : %s\n", pAddress);
1520 if (!get_address_set(pAddress, address))
1522 printf("address parse error\n");
1529 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1531 if (NULL == pAddress)
1533 printf("parameter is null !\n");
1537 size_t len = strlen(pAddress);
1541 for (size_t i = 0; i < len; i++)
1543 if (pAddress[i] == '.')
1548 // found port number start index
1549 if (isIp && pAddress[i] == ':')
1558 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1560 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1563 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1565 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1570 printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1576 outAddress->port = atoi(pAddress + ipLen + 1);
1584 void create_file(CAPayload_t bytes, size_t length)
1586 FILE *fp = fopen("sample_output.txt", "wb");
1589 fwrite(bytes, 1, length, fp);
1594 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1598 printf("parameter is null\n");
1603 CAPayload_t buffer = NULL;
1607 file = fopen(name, "rb");
1610 fprintf(stderr, "Unable to open file, %s\n", name);
1615 fseek(file, 0, SEEK_END);
1616 fileLen = ftell(file);
1619 fprintf(stderr, "Failed to get file length\n");
1623 fseek(file, 0, SEEK_SET);
1626 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1629 fprintf(stderr, "Memory error\n");
1634 // Read file contents into buffer
1635 size_t ret = fread(buffer, fileLen, 1, file);
1638 printf("Failed to read data from file, %s\n", name);