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 request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
94 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
95 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
96 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
97 void get_resource_uri(char *URI, char *resourceURI, int length);
98 int get_secure_information(CAPayload_t payLoad);
99 bool get_address_set(const char *pAddress, addressSet_t* outAddress);
100 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
101 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
103 static CAToken_t g_last_request_token = NULL;
105 static const char COAP_PREFIX[] = "coap://";
106 static const char COAPS_PREFIX[] = "coaps://";
107 static const char COAP_TCP_PREFIX[] = "coap+tcp://";
109 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
110 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
111 static const uint16_t COAP_TCP_PREFIX_LEN = sizeof(COAP_TCP_PREFIX) - 1;
113 static const char SECURE_INFO_DATA[] =
114 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
115 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
117 static const char NORMAL_INFO_DATA[] =
118 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
119 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
122 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
124 void clearDtlsCredentialInfo()
126 printf("clearDtlsCredentialInfo IN\n");
129 // Initialize sensitive data to zeroes before freeing.
130 if (pskCredsBlob->creds)
132 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
133 free(pskCredsBlob->creds);
136 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
140 printf("clearDtlsCredentialInfo OUT\n");
144 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
149 int * GetCRLResource()
155 // Internal API. Invoked by CA stack to retrieve credentials from this module
156 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
158 printf("CAGetDtlsPskCredentials IN\n");
161 printf("Invalid credential container");
165 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
166 if (NULL == *credInfo)
168 printf("Failed to allocate credential blob.");
172 size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
173 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
174 if (NULL == (*credInfo)->creds)
176 printf("Failed to allocate credentials.");
182 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
183 (*credInfo)->num = pskCredsBlob->num;
184 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
186 printf("CAGetDtlsPskCredentials OUT\n");
190 CAResult_t SetCredentials()
192 printf("SetCredentials IN\n");
193 pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
194 if (NULL == pskCredsBlob)
196 printf("Memory allocation failed!\n");
197 return CA_MEMORY_ALLOC_FAILED;
199 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
202 pskCredsBlob->num = 1;
204 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
205 if (NULL == pskCredsBlob->creds)
207 printf("Memory allocation failed!\n");
209 return CA_MEMORY_ALLOC_FAILED;
212 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
213 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
215 printf("SetCredentials OUT\n");
222 int ret = system("clear");
223 // shell invoke error: 127, others: -1
224 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
226 printf("Terminal Clear Error: %d\n", ret);
230 printf("=============================================\n");
231 printf("\t\tsample main\n");
232 printf("=============================================\n");
234 CAResult_t res = CAInitialize();
235 if (CA_STATUS_OK != res)
237 printf("CAInitialize fail\n");
242 * Read DTLS PSK credentials from persistent storage and
243 * set in the OC stack.
246 res = SetCredentials();
247 if (CA_STATUS_OK != res)
249 printf("SetCredentials failed\n");
253 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
254 if (CA_STATUS_OK != res)
256 printf("Set credential handler fail\n");
262 CARegisterHandler(request_handler, response_handler, error_handler);
266 CADestroyToken(g_last_request_token);
268 g_last_request_token = NULL;
272 clearDtlsCredentialInfo();
281 char menu = get_menu();
291 printf("quit..!!\n");
294 case 's': // start server
296 start_listening_server();
299 case 't': // send request
304 case 'c': // start client
306 start_discovery_server();
309 case 'r': // send request
314 case 'b': // send notification
319 case 'n': // select network
324 case 'x': // unselect network
329 case 'h': // handle request response
331 handle_request_response();
337 start_discovery_server();
338 send_secure_request();
339 while (g_received == 0)
342 handle_request_response();
348 start_listening_server();
352 handle_request_response();
356 case 'g': // get network information
362 printf("not supported menu!!\n");
368 void start_listening_server()
370 printf("start listening server!!\n");
372 CAResult_t res = CAStartListeningServer();
373 if (CA_STATUS_OK != res)
375 printf("start listening server fail, error code : %d\n", res);
379 printf("start listening server success\n");
383 void start_discovery_server()
385 printf("start discovery client!!\n");
387 CAResult_t res = CAStartDiscoveryServer();
388 if (CA_STATUS_OK != res)
390 printf("start discovery client fail, error code : %d\n", res);
394 printf("start discovery client success\n");
398 bool select_payload_type()
400 char buf[MAX_BUF_LEN]={0};
401 printf("\n=============================================\n");
402 printf("Normal Payload : 0\nBig Payload : 1\n");
403 printf("select Payload type : ");
405 CAResult_t res = get_input_data(buf, sizeof(buf));
406 if (CA_STATUS_OK != res)
408 printf("Payload type selection error\n");
409 printf("Default: Using normal Payload\n");
413 return (buf[0] == '1') ? true : false;
416 CAPayload_t get_binary_payload(size_t *payloadLength)
418 CAPayload_t binaryPayload = NULL;
419 bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
425 return binaryPayload;
430 CAResult_t res = get_network_type();
431 if (CA_STATUS_OK != res)
436 printf("Do you want to send secure request ?.... enter (0/1): ");
438 char secureRequest[MAX_BUF_LEN] = {0};
439 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
444 if (strcmp(secureRequest, "1") == 0)
446 printf("Enter the URI like below....\n");
447 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
449 else if (strcmp(secureRequest, "0") == 0)
451 printf("Enter the URI like below....\n");
452 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
453 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
454 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\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");
775 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
778 char uri[MAX_BUF_LEN] = { 0 };
779 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
784 printf("\n=============================================\n");
785 printf("\tselect message type\n");
789 printf("RESET : 3\n");
792 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
793 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
798 int messageType = messageTypeBuf[0] - '0';
800 CATransportFlags_t flags;
801 addressSet_t address = {{}, 0};
802 parsing_coap_uri(uri, &address, &flags);
804 // create remote endpoint
805 CAEndpoint_t *endpoint = NULL;
806 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
807 if (CA_STATUS_OK != res)
809 printf("Create remote endpoint error, error code: %d\n", res);
814 CAToken_t token = NULL;
815 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
817 res = CAGenerateToken(&token, tokenLength);
818 if ((CA_STATUS_OK != res) || (!token))
820 printf("Token generate error!!\n");
821 CADestroyEndpoint(endpoint);
825 printf("Generated token %s\n", token);
827 // create response data
828 CAPayload_t payload = (CAPayload_t) "TempNotificationData";
829 size_t payloadSize = strlen((const char *) payload);
831 CAInfo_t respondData = { .type = messageType,
834 .tokenLength = tokenLength,
838 .payloadSize = payloadSize,
839 .resourceUri = (CAURI_t)uri };
841 CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
842 .info = respondData };
845 res = CASendNotification(endpoint, &responseInfo);
846 if (CA_STATUS_OK != res)
848 printf("Send notification error, error code: %d\n", res);
852 printf("Send notification success\n");
856 CADestroyToken(token);
857 // destroy remote endpoint
858 CADestroyEndpoint(endpoint);
860 printf("\n=============================================\n");
863 void select_network()
865 printf("\n=============================================\n");
866 printf("\tselect network\n");
868 printf("GATT : 1\n");
869 printf("RFCOMM : 2\n");
873 char buf[MAX_BUF_LEN] = { 0 };
874 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
879 int number = buf[0] - '0';
881 if (number < 0 || number > 4)
883 printf("Invalid network type\n");
887 CAResult_t res = CASelectNetwork(1 << number);
888 if (CA_STATUS_OK != res)
890 printf("Select network error\n");
894 printf("Select network success\n");
897 printf("=============================================\n");
900 void unselect_network()
902 printf("\n=============================================\n");
903 printf("\tunselect enabled network\n");
905 printf("GATT : 1\n");
906 printf("RFCOMM : 2\n");
910 char buf[MAX_BUF_LEN] = { 0 };
911 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
916 int number = buf[0] - '0';
918 if (number < 0 || number > 4)
920 printf("Invalid network type\n");
924 CAResult_t res = CAUnSelectNetwork(1 << number);
925 if (CA_STATUS_OK != res)
927 printf("Unselect network error\n");
931 printf("Unselect network success\n");
934 printf("=============================================\n");
939 printf("\n=============================================\n");
940 printf("\t\tMenu\n");
941 printf("\ts : start server\n");
942 printf("\tc : start client\n");
943 printf("\tr : send request\n");
944 printf("\tt : send request to all\n");
945 printf("\tb : send notification\n");
946 printf("\tn : select network\n");
947 printf("\tx : unselect network\n");
948 printf("\tg : get network information\n");
949 printf("\th : handle request response\n");
950 printf("\tz : run static server\n");
951 printf("\tw : send secure request\n");
952 printf("\tq : quit\n");
953 printf("=============================================\n");
956 char buf[MAX_BUF_LEN] = { 0 };
957 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
959 printf("Failed to get input data\n");
965 void handle_request_response()
967 printf("Handle_request_response\n");
969 CAResult_t res = CAHandleRequestResponse();
970 if (CA_STATUS_OK != res)
972 printf("Handle request error, error code: %d\n", res);
976 printf("Handle request success\n");
980 void get_network_info()
982 CAEndpoint_t *tempInfo = NULL;
983 uint32_t tempSize = 0;
985 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
986 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
988 printf("Network not connected\n");
993 printf("################## Network Information #######################\n");
994 printf("Network info total size is %d\n\n", tempSize);
996 for (uint32_t index = 0; index < tempSize; index++)
998 printf("Type: %d\n", tempInfo[index].adapter);
999 printf("Address: %s\n", tempInfo[index].addr);
1000 if (CA_ADAPTER_IP == tempInfo[index].adapter)
1002 printf("Port: %d\n", tempInfo[index].port);
1003 printf("Secured: %s flag : %x\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" :
1004 "false", tempInfo[index].flags);
1006 if (tempInfo[index].flags & CA_SECURE)
1008 g_local_secure_port = tempInfo[index].port;
1009 printf("Secured: in global %d\n\n", g_local_secure_port);
1015 printf("##############################################################");
1018 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
1020 if (NULL == object || NULL == requestInfo)
1022 printf("Input parameter is NULL\n");
1026 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1027 && (memcmp(g_last_request_token, requestInfo->info.token,
1028 CA_MAX_TOKEN_LEN) == 0))
1030 printf("token is same. received request of it's own. skip.. \n");
1034 printf("##########received request from remote device #############\n");
1035 if (CA_ADAPTER_IP == object->adapter)
1037 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1038 object->port, object->flags & CA_SECURE);
1042 printf("Remote Address: %s \n", object->addr);
1044 printf("Data: %s\n", requestInfo->info.payload);
1045 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1047 if (requestInfo->info.options)
1049 uint32_t len = requestInfo->info.numOptions;
1051 for (i = 0; i < len; i++)
1053 printf("Option %d\n", i + 1);
1054 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1055 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1056 requestInfo->info.options[i].optionData);
1059 printf("############################################################\n");
1061 //Check if this has secure communication information
1062 if (requestInfo->info.payload &&
1063 (CA_ADAPTER_IP == object->adapter))
1065 int securePort = get_secure_information(requestInfo->info.payload);
1066 if (0 < securePort) //Set the remote endpoint secure details and send response
1068 printf("This is secure resource...\n");
1070 CAEndpoint_t *endpoint = NULL;
1071 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1072 object->port, &endpoint))
1074 printf("Failed to create duplicate of remote endpoint!\n");
1077 endpoint->flags = CA_SECURE;
1083 // if received message is bulk data, create output file
1084 if ((requestInfo->info.payload) &&
1085 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1087 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1091 printf("Send response with URI\n");
1092 send_response(object, &requestInfo->info);
1097 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1099 printf("##########Received response from remote device #############\n");
1100 if (CA_ADAPTER_IP == object->adapter)
1102 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1103 object->port, object->flags & CA_SECURE);
1107 printf("Remote Address: %s \n", object->addr);
1109 printf("response result : %d\n", responseInfo->result);
1110 printf("Data: %s\n", responseInfo->info.payload);
1111 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1112 printf("Token: %s\n", responseInfo->info.token);
1113 if (responseInfo->info.options)
1115 uint32_t len = responseInfo->info.numOptions;
1117 for (i = 0; i < len; i++)
1119 printf("Option %d\n", i + 1);
1120 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1121 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1122 responseInfo->info.options[i].optionData);
1125 printf("############################################################\n");
1128 //Check if this has secure communication information
1129 if (responseInfo->info.payload)
1131 int securePort = get_secure_information(responseInfo->info.payload);
1132 if (0 < securePort) //Set the remote endpoint secure details and send response
1134 printf("This is secure resource...\n");
1139 // if received message is bulk data, create output file
1140 if ((responseInfo->info.payload) &&
1141 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1143 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1148 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1151 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1155 const CAInfo_t *info = &errorInfo->info;
1156 printf("Error Handler, ErrorInfo :\n");
1157 printf("Error Handler result : %d\n", errorInfo->result);
1158 printf("Error Handler token : %s\n", info->token);
1159 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1160 printf("Error Handler type : %d\n", info->type);
1161 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1162 printf("Error Handler payload : %s\n", info->payload);
1164 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1166 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1168 else if(CA_SEND_FAILED == errorInfo->result)
1170 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1172 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1174 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1176 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1178 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1180 else if(CA_STATUS_FAILED == errorInfo->result)
1182 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1185 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1190 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1192 printf("entering send_response\n");
1194 printf("\n=============================================\n");
1195 printf("\tselect message type\n");
1196 printf("CON : 0\n");
1197 printf("NON : 1\n");
1198 printf("ACK : 2\n");
1199 printf("RESET : 3\n");
1200 printf("select : ");
1202 char buf[MAX_BUF_LEN] = { 0 };
1203 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1208 int messageType = buf[0] - '0';
1209 if (0 > messageType || 3 < messageType)
1211 printf("Invalid message type\n");
1215 int responseCode = 0 ;
1216 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1217 if (CA_MSG_RESET != messageType)
1219 printf("\n=============================================\n");
1220 printf("\tselect response code\n");
1221 printf("EMPTY : 0\n");
1222 printf("CREATED : 201\n");
1223 printf("DELETED : 202\n");
1224 printf("VALID : 203\n");
1225 printf("CHANGED : 204\n");
1226 printf("CONTENT : 205\n");
1227 printf("BAD_REQ : 400\n");
1228 printf("BAD_OPT : 402\n");
1229 printf("NOT_FOUND : 404\n");
1230 printf("INTERNAL_SERVER_ERROR : 500\n");
1231 printf("RETRANSMIT_TIMEOUT : 504\n");
1232 printf("select : ");
1234 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1238 responseCode = atoi(responseCodeBuf);
1241 // create response data
1242 uint16_t messageId = (info != NULL) ? info->messageId : 0;
1243 CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1245 CAInfo_t responseData = { .type = messageType,
1246 .messageId = messageId,
1253 .resourceUri = resourceUri };
1255 if(CA_MSG_RESET != messageType)
1257 responseData.token = (info != NULL) ? info->token : NULL;
1258 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1260 if (endpoint->flags & CA_SECURE)
1262 if(!responseData.resourceUri)
1264 printf("resourceUri not available in SECURE\n");
1267 printf("Sending response on secure communication\n");
1269 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1270 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1271 if (NULL == responseData.payload)
1273 printf("Memory allocation fail\n");
1276 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1277 (const char *) responseData.resourceUri, g_local_secure_port);
1278 responseData.payloadSize = length;
1282 printf("Sending response on non-secure communication\n");
1284 bool useBigPayload = select_payload_type();
1287 size_t payloadLength = 0;
1288 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1289 if (NULL == binaryPayload)
1291 free(binaryPayload);
1295 responseData.payload = (CAPayload_t) malloc(payloadLength);
1296 if (NULL == responseData.payload)
1298 printf("Memory allocation failed!");
1299 free(binaryPayload);
1302 memcpy(responseData.payload, binaryPayload, payloadLength);
1303 responseData.payloadSize = payloadLength;
1306 free(binaryPayload);
1310 if(!responseData.resourceUri)
1312 printf("resourceUri not available in NON-SECURE\n");
1315 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1316 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1317 if (NULL == responseData.payload)
1319 printf("Memory allocation fail\n");
1322 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1323 (const char *) responseData.resourceUri);
1324 responseData.payloadSize = length;
1329 CAResponseInfo_t responseInfo = { .result = responseCode,
1330 .info = responseData };
1332 // send response (transportType from remoteEndpoint of request Info)
1333 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1334 if (CA_STATUS_OK != res)
1336 printf("Send response error\n");
1340 printf("Send response success\n");
1343 if (responseData.payload)
1345 free(responseData.payload);
1348 printf("=============================================\n");
1351 int get_secure_information(CAPayload_t payLoad)
1353 printf("Entering get_secure_information\n");
1357 printf("Payload is NULL\n");
1361 char *subString = NULL;
1362 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1364 printf("This is not secure resource\n");
1368 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1370 printf("This secure resource does not have port information\n");
1374 char *startPos = strstr(subString, ":");
1377 printf("Parsing failed !\n");
1381 char *endPos = strstr(startPos, "}");
1384 printf("Parsing failed !\n");
1388 char portStr[6] = {0};
1389 OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1390 printf("secured port is: %s\n", portStr);
1391 return atoi(portStr);
1394 void get_resource_uri(char *URI, char *resourceURI, int length)
1396 char *startPos = URI;
1398 if (NULL != (temp = strstr(URI, "://")))
1400 startPos = strchr(temp + 3, '/');
1403 printf("Resource URI is missing\n");
1408 char *endPos = strchr(startPos, '?');
1411 endPos = URI + strlen(URI);
1415 if (endPos - startPos <= length)
1417 OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1420 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1423 CAResult_t get_network_type()
1425 char buf[MAX_BUF_LEN] = { 0 };
1427 printf("\n=============================================\n");
1428 printf("\tselect network type\n");
1430 printf("GATT : 1\n");
1431 printf("RFCOMM : 2\n");
1432 printf("TCP : 4\n");
1433 printf("select : ");
1435 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1437 return CA_NOT_SUPPORTED ;
1440 int number = buf[0] - '0';
1442 number = (number < 0 || number > 4) ? 0 : 1 << number;
1447 case CA_ADAPTER_GATT_BTLE:
1448 case CA_ADAPTER_RFCOMM_BTEDR:
1449 case CA_ADAPTER_TCP:
1450 g_selected_nw_type = number;
1451 return CA_STATUS_OK;
1453 return CA_NOT_SUPPORTED;
1457 CAResult_t get_input_data(char *buf, int32_t length)
1459 if (!fgets(buf, length, stdin))
1461 printf("fgets error\n");
1462 return CA_STATUS_FAILED;
1466 if ( (p = strchr(buf, '\n')) != NULL )
1471 return CA_STATUS_OK;
1474 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1476 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1477 char optionData[MAX_OPT_LEN] = { 0 } ;
1479 printf("Option Num : ");
1480 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1484 int optionNum = atoi(optionNumBuf);
1486 CAHeaderOption_t * headerOpt = NULL;
1489 printf("there is no headerOption!\n");
1492 else if (optionNum > MAX_OPT_LEN)
1494 printf("Too many header options!\n");
1499 headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1500 if (NULL == headerOpt)
1502 printf("Memory allocation failed!\n");
1507 for (i = 0; i < optionNum; i++)
1509 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1511 printf("[%d] Option ID : ", i + 1);
1512 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1517 int optionID = atoi(getOptionID);
1518 headerOpt[i].optionID = optionID;
1520 printf("[%d] Option Data : ", i + 1);
1521 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1527 OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1529 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1531 requestData->numOptions = optionNum;
1532 requestData->options = headerOpt;
1537 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1541 printf("parameter is null\n");
1547 uint8_t startIndex = 0;
1548 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1550 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1551 startIndex = COAPS_PREFIX_LEN;
1554 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1556 printf("uri has '%s' prefix\n", COAP_PREFIX);
1557 startIndex = COAP_PREFIX_LEN;
1560 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1562 printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1563 startIndex = COAP_TCP_PREFIX_LEN;
1567 // #2. copy uri for parse
1568 int32_t len = strlen(uri) - startIndex;
1572 printf("uri length is 0!\n");
1576 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1577 if (NULL == cloneUri)
1579 printf("Out of memory\n");
1583 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1584 cloneUri[len] = '\0';
1586 char *pAddress = cloneUri;
1587 printf("pAddress : %s\n", pAddress);
1589 if (!get_address_set(pAddress, address))
1591 printf("address parse error\n");
1600 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1602 if (NULL == pAddress)
1604 printf("parameter is null !\n");
1608 size_t len = strlen(pAddress);
1612 for (size_t i = 0; i < len; i++)
1614 if (pAddress[i] == '.')
1619 // found port number start index
1620 if (isIp && pAddress[i] == ':')
1629 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1631 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1634 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1636 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1641 printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1647 outAddress->port = atoi(pAddress + ipLen + 1);
1657 void create_file(CAPayload_t bytes, size_t length)
1659 FILE *fp = fopen("sample_output.txt", "wb");
1662 fwrite(bytes, 1, length, fp);
1667 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1671 printf("parameter is null\n");
1676 CAPayload_t buffer = NULL;
1677 unsigned long fileLen = 0;
1680 file = fopen(name, "rb");
1683 fprintf(stderr, "Unable to open file, %s\n", name);
1688 fseek(file, 0, SEEK_END);
1689 fileLen = ftell(file);
1690 fseek(file, 0, SEEK_SET);
1693 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1696 fprintf(stderr, "Memory error\n");
1701 // Read file contents into buffer
1702 size_t ret = fread(buffer, fileLen, 1, file);
1705 printf("Failed to read data from file, %s\n", name);