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
47 #define BLOCK_SIZE(arg) (1 << ((arg) + 4))
53 #define IDENTITY ("1111111111111111")
57 #define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
60 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
61 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
62 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
66 char ipAddress[CA_IPADDR_SIZE];
72 CAResult_t get_network_type();
73 CAResult_t get_input_data(char *buf, int32_t length);
75 bool select_payload_type();
76 CAPayload_t get_binary_payload(size_t *payloadLength);
77 bool read_file(const char* name, CAPayload_t* bytes, size_t* length);
78 void create_file(CAPayload_t bytes, size_t length);
80 void start_listening_server();
81 void start_discovery_server();
83 void send_request_all();
84 void send_notification();
85 void select_network();
86 void unselect_network();
87 void handle_request_response();
88 void get_network_info();
89 void send_secure_request();
91 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
92 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
93 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
94 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
95 void get_resource_uri(char *URI, char *resourceURI, int length);
96 int get_secure_information(CAPayload_t payLoad);
97 bool get_address_set(const char *pAddress, addressSet_t* outAddress);
98 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
99 CAHeaderOption_t* get_option_data(CAInfo_t* requestData);
101 static CAToken_t g_last_request_token = NULL;
103 static const char COAP_PREFIX[] = "coap://";
104 static const char COAPS_PREFIX[] = "coaps://";
105 static const uint16_t COAP_PREFIX_LEN = sizeof(COAP_PREFIX) - 1;
106 static const uint16_t COAPS_PREFIX_LEN = sizeof(COAPS_PREFIX) - 1;
108 static const char SECURE_INFO_DATA[] =
109 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
110 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":"
112 static const char NORMAL_INFO_DATA[] =
113 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
114 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
117 static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
119 void clearDtlsCredentialInfo()
121 printf("clearDtlsCredentialInfo IN\n");
124 // Initialize sensitive data to zeroes before freeing.
125 if (pskCredsBlob->creds)
127 memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
128 free(pskCredsBlob->creds);
131 memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
135 printf("clearDtlsCredentialInfo OUT\n");
138 // Internal API. Invoked by CA stack to retrieve credentials from this module
139 void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
141 printf("CAGetDtlsPskCredentials IN\n");
144 printf("Invalid credential container");
148 *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
149 if (NULL == *credInfo)
151 printf("Failed to allocate credential blob.");
155 size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
156 (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
157 if (NULL == (*credInfo)->creds)
159 printf("Failed to allocate credentials.");
165 memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
166 (*credInfo)->num = pskCredsBlob->num;
167 memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
169 printf("CAGetDtlsPskCredentials OUT\n");
173 CAResult_t SetCredentials()
175 printf("SetCredentials IN\n");
176 pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
177 if (NULL == pskCredsBlob)
179 printf("Memory allocation failed!\n");
180 return CA_MEMORY_ALLOC_FAILED;
182 memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
185 pskCredsBlob->num = 1;
187 pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
188 if (NULL == pskCredsBlob->creds)
190 printf("Memory allocation failed!\n");
192 return CA_MEMORY_ALLOC_FAILED;
195 memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
196 memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
198 printf("SetCredentials OUT\n");
205 int ret = system("clear");
206 // shell invoke error: 127, others: -1
207 if (SYSTEM_INVOKE_ERROR == ret || SYSTEM_ERROR == ret)
209 printf("Terminal Clear Error: %d\n", ret);
213 printf("=============================================\n");
214 printf("\t\tsample main\n");
215 printf("=============================================\n");
217 CAResult_t res = CAInitialize();
218 if (CA_STATUS_OK != res)
220 printf("CAInitialize fail\n");
225 * Read DTLS PSK credentials from persistent storage and
226 * set in the OC stack.
229 res = SetCredentials();
230 if (CA_STATUS_OK != res)
232 printf("SetCredentials failed\n");
236 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
237 if (CA_STATUS_OK != res)
239 printf("Set credential handler fail\n");
245 CARegisterHandler(request_handler, response_handler, error_handler);
249 CADestroyToken(g_last_request_token);
251 g_last_request_token = NULL;
255 clearDtlsCredentialInfo();
264 char menu = get_menu();
274 printf("quit..!!\n");
277 case 's': // start server
279 start_listening_server();
282 case 't': // send request
287 case 'c': // start client
289 start_discovery_server();
292 case 'r': // send request
297 case 'b': // send notification
302 case 'n': // select network
307 case 'x': // unselect network
312 case 'h': // handle request response
314 handle_request_response();
320 start_discovery_server();
321 send_secure_request();
322 while (g_received == 0)
325 handle_request_response();
331 start_listening_server();
335 handle_request_response();
339 case 'g': // get network information
345 printf("not supported menu!!\n");
351 void start_listening_server()
353 printf("start listening server!!\n");
355 CAResult_t res = CAStartListeningServer();
356 if (CA_STATUS_OK != res)
358 printf("start listening server fail, error code : %d\n", res);
362 printf("start listening server success\n");
366 void start_discovery_server()
368 printf("start discovery client!!\n");
370 CAResult_t res = CAStartDiscoveryServer();
371 if (CA_STATUS_OK != res)
373 printf("start discovery client fail, error code : %d\n", res);
377 printf("start discovery client success\n");
381 bool select_payload_type()
383 char buf[MAX_BUF_LEN]={0};
384 printf("\n=============================================\n");
385 printf("Normal Payload : 0\nBig Payload : 1\n");
386 printf("select Payload type : ");
388 CAResult_t res = get_input_data(buf, sizeof(buf));
389 if (CA_STATUS_OK != res)
391 printf("Payload type selection error\n");
392 printf("Default: Using normal Payload\n");
396 return (buf[0] == '1') ? true : false;
399 CAPayload_t get_binary_payload(size_t *payloadLength)
401 CAPayload_t binaryPayload = NULL;
402 bool result = read_file("sample_input.txt", &binaryPayload, payloadLength);
408 return binaryPayload;
413 CAResult_t res = get_network_type();
414 if (CA_STATUS_OK != res)
419 printf("Do you want to send secure request ?.... enter (0/1): ");
421 char secureRequest[MAX_BUF_LEN] = {0};
422 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
427 if (strcmp(secureRequest, "1") == 0)
429 printf("Enter the URI like below....\n");
430 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
432 else if (strcmp(secureRequest, "0") == 0)
434 printf("Enter the URI like below....\n");
435 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
436 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
440 printf("Input data is wrong value\n");
444 char uri[MAX_BUF_LEN] = {'\0'};
445 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
450 // create remote endpoint
451 CAEndpoint_t *endpoint = NULL;
452 CATransportFlags_t flags;
454 printf("URI : %s\n", uri);
455 addressSet_t address = {{}, 0};
456 parsing_coap_uri(uri, &address, &flags);
458 res = CACreateEndpoint(flags, g_selected_nw_type,
459 (const char*)address.ipAddress, address.port, &endpoint);
460 if (CA_STATUS_OK != res || !endpoint)
462 printf("Failed to create remote endpoint, error code : %d\n", res);
466 printf("\n=============================================\n");
467 printf("0:CON, 1:NON\n");
468 printf("select message type : ");
470 char buf[MAX_BUF_LEN] = { 0 };
471 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
473 CADestroyEndpoint(endpoint);
477 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
480 CAToken_t token = NULL;
481 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
483 res = CAGenerateToken(&token, tokenLength);
484 if ((CA_STATUS_OK != res) || (!token))
486 printf("Token generate error, error code : %d\n", res);
487 CADestroyEndpoint(endpoint);
491 printf("Generated token %s\n", token);
493 // extract relative resourceuri from give uri
494 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
495 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
496 printf("resourceURI : %s\n", resourceURI);
498 // create request data
499 CAInfo_t requestData = { .type = msgType,
502 .tokenLength = tokenLength,
507 .resourceUri = (CAURI_t)resourceURI };
509 if (strcmp(secureRequest, "1") == 0)
511 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
512 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
513 if (NULL == requestData.payload)
515 printf("Memory allocation fail\n");
516 CADestroyEndpoint(endpoint);
517 CADestroyToken(token);
520 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
521 (const char *) resourceURI, g_local_secure_port);
522 requestData.payloadSize = length;
526 bool useBigPayload = select_payload_type();
529 size_t payloadLength = 0;
530 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
534 CADestroyToken(token);
535 CADestroyEndpoint(endpoint);
539 requestData.payload = (CAPayload_t) malloc(payloadLength);
540 if (NULL == requestData.payload)
542 printf("Memory allocation failed!");
544 CADestroyToken(token);
545 CADestroyEndpoint(endpoint);
548 memcpy(requestData.payload, binaryPayload, payloadLength);
549 requestData.payloadSize = payloadLength;
556 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
557 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
558 if (NULL == requestData.payload)
560 printf("Memory allocation fail\n");
561 CADestroyEndpoint(endpoint);
562 CADestroyToken(token);
565 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
566 (const char *) resourceURI);
567 requestData.payloadSize = length;
571 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
573 CARequestInfo_t requestInfo = { .method = CA_GET,
575 .isMulticast = false };
578 res = CASendRequest(endpoint, &requestInfo);
579 if (CA_STATUS_OK != res)
581 printf("Could not send request : %d\n", res);
590 CADestroyToken(token);
591 // destroy remote endpoint
592 CADestroyEndpoint(endpoint);
593 free(requestData.payload);
595 printf("=============================================\n");
598 void send_secure_request()
600 char uri[MAX_BUF_LEN];
601 char ipv4addr[CA_IPADDR_SIZE];
603 printf("\n=============================================\n");
604 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
606 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
610 snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", COAPS_PREFIX, ipv4addr);
612 // create remote endpoint
613 CAEndpoint_t *endpoint = NULL;
614 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
615 if (CA_STATUS_OK != res)
617 printf("Failed to create remote endpoint, error code: %d\n", res);
622 CAToken_t token = NULL;
623 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
625 res = CAGenerateToken(&token, tokenLength);
626 if (CA_STATUS_OK != res)
628 printf("Token generate error, error code : %d\n", res);
632 printf("Generated token %s\n", token);
634 // create request data
635 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
638 .tokenLength = tokenLength,
643 .resourceUri = NULL };
645 CARequestInfo_t requestInfo = { .method = CA_GET,
647 .isMulticast = false };
650 CASendRequest(endpoint, &requestInfo);
654 CADestroyToken(token);
655 CADestroyEndpoint(endpoint);
656 printf("=============================================\n");
660 void send_request_all()
662 CAResult_t res = get_network_type();
663 if (CA_STATUS_OK != res)
668 printf("\n=============================================\n");
669 printf("ex) /a/light\n");
670 printf("resource uri : ");
672 char resourceURI[MAX_BUF_LEN] = { 0 };
673 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
678 // create remote endpoint
679 CAEndpoint_t *group = NULL;
680 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &group);
681 if (CA_STATUS_OK != res)
683 printf("Create remote endpoint error, error code: %d\n", res);
688 CAToken_t token = NULL;
689 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
691 res = CAGenerateToken(&token, tokenLength);
692 if ((CA_STATUS_OK != res) || (!token))
694 printf("Token generate error!!\n");
695 CADestroyEndpoint(group);
699 printf("generated token %s\n", token);
701 // create request data
702 CAPayload_t payload = (CAPayload_t) "TempJsonPayload";
703 size_t payloadSize = strlen((const char *) payload);
705 CAInfo_t requestData = { .type = CA_MSG_NONCONFIRM,
708 .tokenLength = tokenLength,
712 .payloadSize = payloadSize,
713 .resourceUri = (CAURI_t) resourceURI };
715 CARequestInfo_t requestInfo = { .method = CA_GET,
717 .isMulticast = true };
719 CAHeaderOption_t* headerOpt = get_option_data(&requestData);
722 res = CASendRequest(group, &requestInfo);
723 if (CA_STATUS_OK != res)
725 printf("Could not send request to all\n");
726 CADestroyToken(token);
730 CADestroyToken(g_last_request_token);
731 g_last_request_token = token;
739 // destroy remote endpoint
740 CADestroyEndpoint(group);
742 printf("=============================================\n");
745 void send_notification()
747 CAResult_t res = get_network_type();
748 if (CA_STATUS_OK != res)
753 printf("\n=============================================\n");
754 printf("Enter the URI like below....\n");
755 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
756 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
759 char uri[MAX_BUF_LEN] = { 0 };
760 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
765 printf("\n=============================================\n");
766 printf("\tselect message type\n");
770 printf("RESET : 3\n");
773 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
774 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
779 int messageType = messageTypeBuf[0] - '0';
781 CATransportFlags_t flags;
782 addressSet_t address = {{}, 0};
783 parsing_coap_uri(uri, &address, &flags);
785 // create remote endpoint
786 CAEndpoint_t *endpoint = NULL;
787 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
788 if (CA_STATUS_OK != res)
790 printf("Create remote endpoint error, error code: %d\n", res);
795 CAToken_t token = NULL;
796 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
798 res = CAGenerateToken(&token, tokenLength);
799 if ((CA_STATUS_OK != res) || (!token))
801 printf("Token generate error!!\n");
802 CADestroyEndpoint(endpoint);
806 printf("Generated token %s\n", token);
808 // create response data
809 CAPayload_t payload = (CAPayload_t) "TempNotificationData";
810 size_t payloadSize = strlen((const char *) payload);
812 CAInfo_t respondData = { .type = messageType,
815 .tokenLength = tokenLength,
819 .payloadSize = payloadSize,
820 .resourceUri = (CAURI_t)uri };
822 CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
823 .info = respondData };
826 res = CASendNotification(endpoint, &responseInfo);
827 if (CA_STATUS_OK != res)
829 printf("Send notification error, error code: %d\n", res);
833 printf("Send notification success\n");
837 CADestroyToken(token);
838 // destroy remote endpoint
839 CADestroyEndpoint(endpoint);
841 printf("\n=============================================\n");
844 void select_network()
846 printf("\n=============================================\n");
847 printf("\tselect network\n");
849 printf("GATT : 1\n");
850 printf("RFCOMM : 2\n");
853 char buf[MAX_BUF_LEN] = { 0 };
854 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
859 int number = buf[0] - '0';
861 if (number < 0 || number > 3)
863 printf("Invalid network type\n");
867 CAResult_t res = CASelectNetwork(1 << number);
868 if (CA_STATUS_OK != res)
870 printf("Select network error\n");
874 printf("Select network success\n");
877 printf("=============================================\n");
880 void unselect_network()
882 printf("\n=============================================\n");
883 printf("\tunselect enabled network\n");
885 printf("GATT : 1\n");
886 printf("RFCOMM : 2\n");
889 char buf[MAX_BUF_LEN] = { 0 };
890 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
895 int number = buf[0] - '0';
897 if (number < 0 || number > 3)
899 printf("Invalid network type\n");
903 CAResult_t res = CAUnSelectNetwork(1 << number);
904 if (CA_STATUS_OK != res)
906 printf("Unselect network error\n");
910 printf("Unselect network success\n");
913 printf("=============================================\n");
918 printf("\n=============================================\n");
919 printf("\t\tMenu\n");
920 printf("\ts : start server\n");
921 printf("\tc : start client\n");
922 printf("\tr : send request\n");
923 printf("\tt : send request to all\n");
924 printf("\tb : send notification\n");
925 printf("\tn : select network\n");
926 printf("\tx : unselect network\n");
927 printf("\tg : get network information\n");
928 printf("\th : handle request response\n");
929 printf("\tz : run static server\n");
930 printf("\tw : send secure request\n");
931 printf("\tq : quit\n");
932 printf("=============================================\n");
935 char buf[MAX_BUF_LEN] = { 0 };
936 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
938 printf("Failed to get input data\n");
944 void handle_request_response()
946 printf("Handle_request_response\n");
948 CAResult_t res = CAHandleRequestResponse();
949 if (CA_STATUS_OK != res)
951 printf("Handle request error, error code: %d\n", res);
955 printf("Handle request success\n");
959 void get_network_info()
961 CAEndpoint_t *tempInfo = NULL;
962 uint32_t tempSize = 0;
964 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
965 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
967 printf("Network not connected\n");
972 printf("################## Network Information #######################\n");
973 printf("Network info total size is %d\n\n", tempSize);
975 for (uint32_t index = 0; index < tempSize; index++)
977 printf("Type: %d\n", tempInfo[index].adapter);
978 printf("Address: %s\n", tempInfo[index].addr);
979 if (CA_ADAPTER_IP == tempInfo[index].adapter)
981 printf("Port: %d\n", tempInfo[index].port);
983 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
985 if (tempInfo[index].flags & CA_SECURE)
987 g_local_secure_port = tempInfo[index].port;
988 printf("Secured: in global %d\n\n", g_local_secure_port);
993 printf("##############################################################");
996 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
998 if (NULL == object || NULL == requestInfo)
1000 printf("Input parameter is NULL\n");
1004 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
1005 && (memcmp(g_last_request_token, requestInfo->info.token,
1006 CA_MAX_TOKEN_LEN) == 0))
1008 printf("token is same. received request of it's own. skip.. \n");
1012 printf("##########received request from remote device #############\n");
1013 if (CA_ADAPTER_IP == object->adapter)
1015 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1016 object->port, object->flags & CA_SECURE);
1020 printf("Remote Address: %s \n", object->addr);
1022 printf("Data: %s\n", requestInfo->info.payload);
1023 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
1025 if (requestInfo->info.options)
1027 uint32_t len = requestInfo->info.numOptions;
1029 for (i = 0; i < len; i++)
1031 printf("Option %d\n", i + 1);
1032 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1033 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1034 requestInfo->info.options[i].optionData);
1037 printf("############################################################\n");
1039 //Check if this has secure communication information
1040 if (requestInfo->info.payload &&
1041 (CA_ADAPTER_IP == object->adapter))
1043 int securePort = get_secure_information(requestInfo->info.payload);
1044 if (0 < securePort) //Set the remote endpoint secure details and send response
1046 printf("This is secure resource...\n");
1048 CAEndpoint_t *endpoint = NULL;
1049 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1050 object->port, &endpoint))
1052 printf("Failed to create duplicate of remote endpoint!\n");
1055 endpoint->flags = CA_SECURE;
1060 // if received message is bulk data, create output file
1061 if ((requestInfo->info.payload) &&
1062 (requestInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1064 create_file(requestInfo->info.payload, requestInfo->info.payloadSize);
1067 printf("Send response with URI\n");
1068 send_response(object, &requestInfo->info);
1073 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1075 printf("##########Received response from remote device #############\n");
1076 if (CA_ADAPTER_IP == object->adapter)
1078 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1079 object->port, object->flags & CA_SECURE);
1083 printf("Remote Address: %s \n", object->addr);
1085 printf("response result : %d\n", responseInfo->result);
1086 printf("Data: %s\n", responseInfo->info.payload);
1087 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1088 printf("Token: %s\n", responseInfo->info.token);
1089 if (responseInfo->info.options)
1091 uint32_t len = responseInfo->info.numOptions;
1093 for (i = 0; i < len; i++)
1095 printf("Option %d\n", i + 1);
1096 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1097 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1098 responseInfo->info.options[i].optionData);
1101 printf("############################################################\n");
1104 //Check if this has secure communication information
1105 if (responseInfo->info.payload)
1107 int securePort = get_secure_information(responseInfo->info.payload);
1108 if (0 < securePort) //Set the remote endpoint secure details and send response
1110 printf("This is secure resource...\n");
1114 // if received message is bulk data, create output file
1115 if ((responseInfo->info.payload) &&
1116 (responseInfo->info.payloadSize > BLOCK_SIZE(CA_DEFAULT_BLOCK_SIZE)))
1118 create_file(responseInfo->info.payload, responseInfo->info.payloadSize);
1122 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1125 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1129 const CAInfo_t *info = &errorInfo->info;
1130 printf("Error Handler, ErrorInfo :\n");
1131 printf("Error Handler result : %d\n", errorInfo->result);
1132 printf("Error Handler token : %s\n", info->token);
1133 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1134 printf("Error Handler type : %d\n", info->type);
1135 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1136 printf("Error Handler payload : %s\n", info->payload);
1138 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1140 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1142 else if(CA_SEND_FAILED == errorInfo->result)
1144 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1146 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1148 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1150 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1152 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1154 else if(CA_STATUS_FAILED == errorInfo->result)
1156 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1159 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1164 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1166 printf("entering send_response\n");
1168 printf("\n=============================================\n");
1169 printf("\tselect message type\n");
1170 printf("CON : 0\n");
1171 printf("NON : 1\n");
1172 printf("ACK : 2\n");
1173 printf("RESET : 3\n");
1174 printf("select : ");
1176 char buf[MAX_BUF_LEN] = { 0 };
1177 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1182 int messageType = buf[0] - '0';
1183 if (0 > messageType || 3 < messageType)
1185 printf("Invalid message type\n");
1189 int responseCode = 0 ;
1190 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1191 if (CA_MSG_RESET != messageType)
1193 printf("\n=============================================\n");
1194 printf("\tselect response code\n");
1195 printf("EMPTY : 0\n");
1196 printf("SUCCESS : 200\n");
1197 printf("CREATED : 201\n");
1198 printf("DELETED : 202\n");
1199 printf("VALID : 203\n");
1200 printf("CHANGED : 204\n");
1201 printf("CONTENT : 205\n");
1202 printf("BAD_REQ : 400\n");
1203 printf("BAD_OPT : 402\n");
1204 printf("NOT_FOUND : 404\n");
1205 printf("INTERNAL_SERVER_ERROR : 500\n");
1206 printf("RETRANSMIT_TIMEOUT : 504\n");
1207 printf("select : ");
1209 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1213 responseCode = atoi(responseCodeBuf);
1216 // create response data
1217 uint16_t messageId = (info != NULL) ? info->messageId : 0;
1218 CAURI_t resourceUri = (info != NULL) ? info->resourceUri : 0;
1220 CAInfo_t responseData = { .type = messageType,
1221 .messageId = messageId,
1228 .resourceUri = resourceUri };
1230 if(CA_MSG_RESET != messageType)
1232 responseData.token = (info != NULL) ? info->token : NULL;
1233 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1235 if (endpoint->flags & CA_SECURE)
1237 if(!responseData.resourceUri)
1239 printf("resourceUri not available in SECURE\n");
1242 printf("Sending response on secure communication\n");
1244 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri);
1245 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1246 if (NULL == responseData.payload)
1248 printf("Memory allocation fail\n");
1251 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1252 (const char *) responseData.resourceUri, g_local_secure_port);
1253 responseData.payloadSize = length;
1257 printf("Sending response on non-secure communication\n");
1259 bool useBigPayload = select_payload_type();
1262 size_t payloadLength = 0;
1263 CAPayload_t binaryPayload = get_binary_payload(&payloadLength);
1264 if (NULL == binaryPayload)
1266 free(binaryPayload);
1270 responseData.payload = (CAPayload_t) malloc(payloadLength);
1271 if (NULL == responseData.payload)
1273 printf("Memory allocation failed!");
1274 free(binaryPayload);
1277 memcpy(responseData.payload, binaryPayload, payloadLength);
1278 responseData.payloadSize = payloadLength;
1281 free(binaryPayload);
1285 if(!responseData.resourceUri)
1287 printf("resourceUri not available in NON-SECURE\n");
1290 uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1291 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1292 if (NULL == responseData.payload)
1294 printf("Memory allocation fail\n");
1297 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1298 (const char *) responseData.resourceUri);
1299 responseData.payloadSize = length;
1304 CAResponseInfo_t responseInfo = { .result = responseCode,
1305 .info = responseData };
1307 // send response (transportType from remoteEndpoint of request Info)
1308 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1309 if (CA_STATUS_OK != res)
1311 printf("Send response error\n");
1315 printf("Send response success\n");
1318 if (responseData.payload)
1320 free(responseData.payload);
1323 printf("=============================================\n");
1326 int get_secure_information(CAPayload_t payLoad)
1328 printf("Entering get_secure_information\n");
1332 printf("Payload is NULL\n");
1336 char *subString = NULL;
1337 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1339 printf("This is not secure resource\n");
1343 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1345 printf("This secure resource does not have port information\n");
1349 char *startPos = strstr(subString, ":");
1352 printf("Parsing failed !\n");
1356 char *endPos = strstr(startPos, "}");
1359 printf("Parsing failed !\n");
1363 char portStr[6] = {0};
1364 OICStrcpyPartial(portStr, sizeof(portStr), startPos + 1, (endPos - 1) - startPos);
1365 printf("secured port is: %s\n", portStr);
1366 return atoi(portStr);
1369 void get_resource_uri(char *URI, char *resourceURI, int length)
1371 char *startPos = URI;
1373 if (NULL != (temp = strstr(URI, "://")))
1375 startPos = strchr(temp + 3, '/');
1378 printf("Resource URI is missing\n");
1383 char *endPos = strchr(startPos, '?');
1386 endPos = URI + strlen(URI);
1390 if (endPos - startPos <= length)
1392 OICStrcpyPartial(resourceURI, length, startPos + 1, endPos - startPos);
1395 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1398 CAResult_t get_network_type()
1400 char buf[MAX_BUF_LEN] = { 0 };
1402 printf("\n=============================================\n");
1403 printf("\tselect network type\n");
1405 printf("GATT : 1\n");
1406 printf("RFCOMM : 2\n");
1407 printf("select : ");
1409 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1411 return CA_NOT_SUPPORTED ;
1414 int number = buf[0] - '0';
1416 number = (number < 0 || number > 3) ? 0 : 1 << number;
1420 g_selected_nw_type = CA_ADAPTER_IP;
1421 return CA_STATUS_OK;
1425 g_selected_nw_type = CA_ADAPTER_GATT_BTLE;
1426 return CA_STATUS_OK;
1430 g_selected_nw_type = CA_ADAPTER_RFCOMM_BTEDR;
1431 return CA_STATUS_OK;
1434 return CA_NOT_SUPPORTED;
1437 CAResult_t get_input_data(char *buf, int32_t length)
1439 if (!fgets(buf, length, stdin))
1441 printf("fgets error\n");
1442 return CA_STATUS_FAILED;
1446 if ( (p = strchr(buf, '\n')) != NULL )
1451 return CA_STATUS_OK;
1454 CAHeaderOption_t* get_option_data(CAInfo_t* requestData)
1456 char optionNumBuf[MAX_BUF_LEN] = { 0 };
1457 char optionData[MAX_OPT_LEN] = { 0 } ;
1459 printf("Option Num : ");
1460 if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
1464 int optionNum = atoi(optionNumBuf);
1466 CAHeaderOption_t * headerOpt = NULL;
1469 printf("there is no headerOption!\n");
1472 else if (optionNum > MAX_OPT_LEN)
1474 printf("Too many header options!\n");
1479 headerOpt = (CAHeaderOption_t *)calloc(optionNum, sizeof(CAHeaderOption_t));
1480 if (NULL == headerOpt)
1482 printf("Memory allocation failed!\n");
1487 for (i = 0; i < optionNum; i++)
1489 char getOptionID[MAX_BUF_LEN] = { 0 } ;
1491 printf("[%d] Option ID : ", i + 1);
1492 if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
1497 int optionID = atoi(getOptionID);
1498 headerOpt[i].optionID = optionID;
1500 printf("[%d] Option Data : ", i + 1);
1501 if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
1507 OICStrcpy(headerOpt[i].optionData, sizeof(headerOpt[i].optionData), optionData);
1509 headerOpt[i].optionLength = (uint16_t) strlen(optionData);
1511 requestData->numOptions = optionNum;
1512 requestData->options = headerOpt;
1517 void parsing_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1521 printf("parameter is null\n");
1527 uint8_t startIndex = 0;
1528 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1530 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1531 startIndex = COAPS_PREFIX_LEN;
1534 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1536 printf("uri has '%s' prefix\n", COAP_PREFIX);
1537 startIndex = COAP_PREFIX_LEN;
1541 // #2. copy uri for parse
1542 int32_t len = strlen(uri) - startIndex;
1546 printf("uri length is 0!\n");
1550 char *cloneUri = (char *) calloc(len + 1, sizeof(char));
1551 if (NULL == cloneUri)
1553 printf("Out of memory\n");
1557 memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
1558 cloneUri[len] = '\0';
1560 char *pAddress = cloneUri;
1561 printf("pAddress : %s\n", pAddress);
1563 if (!get_address_set(pAddress, address))
1565 printf("address parse error\n");
1574 bool get_address_set(const char *pAddress, addressSet_t* outAddress)
1576 if (NULL == pAddress)
1578 printf("parameter is null !\n");
1582 size_t len = strlen(pAddress);
1586 for (size_t i = 0; i < len; i++)
1588 if (pAddress[i] == '.')
1593 // found port number start index
1594 if (isIp && pAddress[i] == ':')
1603 if(ipLen && ipLen < sizeof(outAddress->ipAddress))
1605 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1608 else if (!ipLen && len < sizeof(outAddress->ipAddress))
1610 OICStrcpyPartial(outAddress->ipAddress, sizeof(outAddress->ipAddress),
1615 printf("IP Address too long: %zu\n", (ipLen == 0) ? len : ipLen);
1621 outAddress->port = atoi(pAddress + ipLen + 1);
1631 void create_file(CAPayload_t bytes, size_t length)
1633 FILE *fp = fopen("sample_output.txt", "wb");
1636 fwrite(bytes, 1, length, fp);
1641 bool read_file(const char* name, CAPayload_t* bytes, size_t* length)
1645 printf("parameter is null\n");
1650 CAPayload_t buffer = NULL;
1651 unsigned long fileLen = 0;
1654 file = fopen(name, "rb");
1657 fprintf(stderr, "Unable to open file, %s\n", name);
1662 fseek(file, 0, SEEK_END);
1663 fileLen = ftell(file);
1664 fseek(file, 0, SEEK_SET);
1667 buffer = calloc(1, sizeof(uint8_t) * fileLen + 1);
1670 fprintf(stderr, "Memory error\n");
1675 // Read file contents into buffer
1676 size_t ret = fread(buffer, fileLen, 1, file);
1679 printf("Failed to read data from file, %s\n", name);