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"
33 * @brief maximum buffer length
35 #define MAX_BUF_LEN 1024
39 * @brief maximum option length
41 #define MAX_OPT_LEN 16
45 * @brief maximum port length
50 * @def SECURE_DEFAULT_PORT
51 * @brief default secured port
53 #define SECURE_DEFAULT_PORT 5684
55 #define RESOURCE_URI_LENGTH 14
57 #define COAP_PREFIX "coap://"
58 #define COAP_PREFIX_LEN 7
59 #define COAPS_PREFIX "coaps://"
60 #define COAPS_PREFIX_LEN 8
62 #define COAP_TCP_PREFIX "coap+tcp://"
63 #define COAP_TCP_PREFIX_LEN 11
65 // Iotivity Device Identity.
66 const unsigned char IDENTITY[] = ("1111111111111111");
68 // PSK between this device and peer device.
69 const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
72 * Max size for big payload.
74 #define BIG_PAYLOAD_SIZE 15000
76 static GMainLoop *g_mainloop = NULL;
80 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
81 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
82 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
86 char ipAddress[CA_IPADDR_SIZE];
92 CAResult_t get_network_type();
93 CAResult_t get_input_data(char *buf, int32_t length);
95 bool select_payload();
96 void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen);
98 void start_listening_server();
99 void start_discovery_server();
101 void send_request_all();
102 void send_notification();
103 void select_network();
104 void unselect_network();
105 void handle_request_response();
106 void get_network_info();
107 void send_secure_request();
109 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
110 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
111 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
112 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
113 void get_resource_uri(char *URI, char *resourceURI, int length);
114 int get_secure_information(CAPayload_t payLoad);
115 int get_address_set(const char *uri, addressSet_t* outAddress);
116 void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
118 static CAToken_t g_last_request_token = NULL;
119 static const char SECURE_COAPS_PREFIX[] = "coaps://";
120 static const char SECURE_INFO_DATA[] =
121 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
122 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
123 static const char NORMAL_INFO_DATA[] =
124 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
125 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
128 // Internal API. Invoked by CA stack to retrieve credentials from this module.
129 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
130 const unsigned char *desc, size_t desc_len,
131 unsigned char *result, size_t result_length)
133 printf("CAGetDtlsPskCredentials IN\n");
144 case CA_DTLS_PSK_HINT:
145 case CA_DTLS_PSK_IDENTITY:
147 if (result_length < sizeof(IDENTITY))
149 printf("ERROR : Wrong value for result for storing IDENTITY");
153 memcpy(result, IDENTITY, sizeof(IDENTITY));
154 ret = sizeof(IDENTITY);
157 case CA_DTLS_PSK_KEY:
159 if ((desc_len == sizeof(IDENTITY)) &&
160 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
162 if (result_length < sizeof(RS_CLIENT_PSK))
164 printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
168 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
169 ret = sizeof(RS_CLIENT_PSK);
175 printf("Wrong value passed for PSK_CRED_TYPE.");
179 printf("CAGetDtlsPskCredentials OUT\n");
184 void GMainLoopThread()
186 g_main_loop_run(g_mainloop);
189 CAResult_t Initialize()
191 g_mainloop = g_main_loop_new(NULL, FALSE);
194 printf("g_main_loop_new failed\n");
195 return CA_STATUS_FAILED;
198 int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
201 printf("pthread_create failed in initialize\n");
202 return CA_STATUS_FAILED;
205 CAResult_t res = CAInitialize();
206 if (res != CA_STATUS_OK)
208 printf("CAInitialize fail\n");
215 int ret = system("clear");
216 // shell invoke error: 127, others: -1
217 if (127 == ret || -1 == ret)
219 printf("Terminal Clear Error: %d\n", ret);
222 printf("=============================================\n");
223 printf("\t\tsample main\n");
224 printf("=============================================\n");
226 CAResult_t res = Initialize();
227 if (CA_STATUS_OK != res)
229 printf("Initialization is failed\n");
233 // Set the PSK Credentials callback handler.
235 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
236 if (CA_STATUS_OK != res)
238 printf("Set credential handler fail\n");
244 CARegisterHandler(request_handler, response_handler, error_handler);
248 CADestroyToken(g_last_request_token);
258 char menu = get_menu();
268 printf("quit..!!\n");
271 case 's': // start server
273 start_listening_server();
276 case 't': // send request
281 case 'c': // start client
283 start_discovery_server();
286 case 'r': // send request
291 case 'b': // send notification
296 case 'n': // select network
301 case 'x': // unselect network
306 case 'h': // handle request response
308 handle_request_response();
314 start_discovery_server();
315 send_secure_request();
316 while (g_received == 0)
319 handle_request_response();
325 start_listening_server();
329 handle_request_response();
333 case 'g': // get network information
339 printf("Not supported menu!!\n");
346 void start_listening_server()
348 printf("Start listening server!!\n");
350 CAResult_t res = CAStartListeningServer();
351 if (CA_STATUS_OK != res)
353 printf("Start listening server fail, error code : %d\n", res);
357 printf("Start listening server success\n");
361 void start_discovery_server()
363 printf("Start discovery client!!\n");
365 CAResult_t res = CAStartDiscoveryServer();
366 if (CA_STATUS_OK != res)
368 printf("Start discovery client fail, error code : %d\n", res);
372 printf("Start discovery client success\n");
376 bool select_payload()
378 char buf[MAX_BUF_LEN]={0};
379 printf("\n=============================================\n");
380 printf("0:Normal Payload\n1:Big Payload(~15KB)\n");
381 printf("select Payload type : ");
383 CAResult_t res = get_input_data(buf, sizeof(buf));
384 if (CA_STATUS_OK != res)
386 printf("Payload type selection error\n");
387 printf("Default: Using normal Payload\n");
391 return (buf[0] == '1') ? true : false;
394 void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen)
397 * bigBuffer to be filled with binary data. For our sample application to verify, we may fill with
398 * any arbitrary value. Hence filling with '1' here.
400 memset(bigBuffer, '1', bigBufferLen-1);
401 //Last byte making NULL
402 bigBuffer[bigBufferLen-1] = '\0';
407 CAResult_t res = get_network_type();
408 if (CA_STATUS_OK != res)
413 printf("Do you want to send secure request ?.... enter (0/1): ");
415 char secureRequest[MAX_BUF_LEN] = {0};
416 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
421 if (strcmp(secureRequest, "1") == 0)
423 printf("Enter the URI like below....\n");
424 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
426 else if (strcmp(secureRequest, "0") == 0)
428 printf("Enter the URI like below....\n");
429 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
430 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
431 printf("coap+tcp://10:11:12:13:45:45/resource_uri ( for TCP )\n");
435 printf("Input data is wrong value\n");
439 char uri[MAX_BUF_LEN] = {'\0'};
440 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
445 // create remote endpoint
446 CAEndpoint_t *endpoint = NULL;
447 CATransportFlags_t flags;
449 printf("URI : %s\n", uri);
450 addressSet_t address = {};
451 parse_coap_uri(uri, &address, &flags);
453 res = CACreateEndpoint(flags, g_selected_nw_type,
454 (const char*)address.ipAddress, address.port, &endpoint);
455 if (CA_STATUS_OK != res || !endpoint)
457 printf("Failed to create remote endpoint, error code : %d\n", res);
461 printf("\n=============================================\n");
462 printf("0:CON, 1:NON\n");
463 printf("select message type : ");
465 char buf[MAX_BUF_LEN] = { 0 };
466 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
468 CADestroyEndpoint(endpoint);
472 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
475 CAToken_t token = NULL;
476 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
478 res = CAGenerateToken(&token, tokenLength);
479 if ((CA_STATUS_OK != res) || (!token))
481 printf("Token generate error, error code : %d\n", res);
482 CADestroyEndpoint(endpoint);
486 printf("Generated token %s\n", token);
488 // extract relative resourceuri from give uri
489 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
490 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
491 printf("resourceURI : %s\n", resourceURI);
493 // create request data
494 CAInfo_t requestData = { 0 };
495 requestData.token = token;
496 requestData.tokenLength = tokenLength;
497 requestData.resourceUri = (CAURI_t)resourceURI;
499 if (strcmp(secureRequest, "1") == 0)
501 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
502 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
503 if (NULL == requestData.payload)
505 printf("Memory allocation fail\n");
506 CADestroyEndpoint(endpoint);
507 CADestroyToken(token);
510 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
511 (const char *) resourceURI, g_local_secure_port);
515 bool useBigPayload = select_payload();
518 requestData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
519 if (NULL == requestData.payload)
521 printf("Memory allocation fail\n");
522 CADestroyEndpoint(endpoint);
523 CADestroyToken(token);
526 populate_binary_payload(requestData.payload, BIG_PAYLOAD_SIZE);
530 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
531 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
532 if (NULL == requestData.payload)
534 printf("Memory allocation fail\n");
535 CADestroyEndpoint(endpoint);
536 CADestroyToken(token);
539 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
540 (const char *) resourceURI);
543 requestData.payloadSize = strlen((char *)requestData.payload)+1;
544 requestData.type = msgType;
546 CARequestInfo_t requestInfo = { 0 };
547 requestInfo.method = CA_GET;
548 requestInfo.info = requestData;
549 requestInfo.isMulticast = false;
552 res = CASendRequest(endpoint, &requestInfo);
553 if (CA_STATUS_OK != res)
555 printf("Could not send request : %d\n", res);
559 CADestroyToken(token);
560 // destroy remote endpoint
561 CADestroyEndpoint(endpoint);
562 free(requestData.payload);
565 printf("=============================================\n");
568 void send_secure_request()
570 char ipv4addr[CA_IPADDR_SIZE];
572 printf("\n=============================================\n");
573 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
575 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
579 printf("%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
581 // create remote endpoint
582 CAEndpoint_t *endpoint = NULL;
583 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
584 if (CA_STATUS_OK != res)
586 printf("Failed to create remote endpoint, error code: %d\n", res);
591 CAToken_t token = NULL;
592 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
594 res = CAGenerateToken(&token, tokenLength);
595 if ((CA_STATUS_OK != res) || (!token))
597 printf("Token generate error, error code : %d\n", res);
601 printf("Generated token %s\n", token);
603 // create request data
604 CAMessageType_t msgType = CA_MSG_NONCONFIRM;
605 CAInfo_t requestData = { 0 };
606 requestData.token = token;
607 requestData.tokenLength = tokenLength;
608 requestData.type = msgType;
609 requestData.payload = "Temp Json Payload";
610 requestData.payloadSize = strlen(requestData.payload)+1;
612 CARequestInfo_t requestInfo = { 0 };
613 requestInfo.method = CA_GET;
614 requestInfo.info = requestData;
615 requestInfo.isMulticast = false;
618 CASendRequest(endpoint, &requestInfo);
622 CADestroyToken(token);
623 CADestroyEndpoint(endpoint);
624 printf("=============================================\n");
628 void send_request_all()
630 CAResult_t res = get_network_type();
631 if (CA_STATUS_OK != res)
636 printf("\n=============================================\n");
637 printf("ex) /a/light\n");
638 printf("resource uri : ");
640 char resourceURI[MAX_BUF_LEN] = { 0 };
641 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
646 // create remote endpoint
647 CAEndpoint_t *endpoint = NULL;
648 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &endpoint);
649 if (CA_STATUS_OK != res)
651 printf("Create remote endpoint error, error code: %d\n", res);
656 CAToken_t token = NULL;
657 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
659 res = CAGenerateToken(&token, tokenLength);
660 if ((CA_STATUS_OK != res) || (!token))
662 printf("Token generate error!!\n");
663 CADestroyEndpoint(endpoint);
667 printf("generated token %s\n", token);
669 CAInfo_t requestData = { 0 };
670 requestData.token = token;
671 requestData.tokenLength = tokenLength;
672 requestData.payload = (CAPayload_t) "TempJsonPayload";
673 requestData.payloadSize = strlen((const char *) requestData.payload);
674 requestData.type = CA_MSG_NONCONFIRM;
675 requestData.resourceUri = (CAURI_t)resourceURI;
677 CARequestInfo_t requestInfo = { 0 };
678 requestInfo.method = CA_GET;
679 requestInfo.info = requestData;
680 requestInfo.isMulticast = true;
683 res = CASendRequest(endpoint, &requestInfo);
684 if (CA_STATUS_OK != res)
686 printf("Could not send request to all\n");
690 CADestroyToken(g_last_request_token);
691 g_last_request_token = token;
694 // destroy remote endpoint
695 CADestroyEndpoint(endpoint);
697 printf("=============================================\n");
700 void send_notification()
702 CAResult_t res = get_network_type();
703 if (CA_STATUS_OK != res)
708 printf("\n=============================================\n");
709 printf("Enter the URI like below....\n");
710 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
711 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
714 char uri[MAX_BUF_LEN] = { 0 };
715 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
720 printf("\n=============================================\n");
721 printf("\tselect message type\n");
725 printf("RESET : 3\n");
729 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
730 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
735 int messageType = messageTypeBuf[0] - '0';
740 printf("CONFIRM messagetype is selected\n");
743 printf("NONCONFIRM messagetype is selected\n");
746 printf("Invalid Selection\n");
750 CATransportFlags_t flags;
751 addressSet_t address = {};
752 parse_coap_uri(uri, &address, &flags);
754 // create remote endpoint
755 CAEndpoint_t *endpoint = NULL;
756 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
757 if (CA_STATUS_OK != res)
759 printf("Create remote endpoint error, error code: %d\n", res);
764 CAToken_t token = NULL;
765 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
767 res = CAGenerateToken(&token, tokenLength);
768 if ((CA_STATUS_OK != res) || (!token))
770 printf("Token generate error!!\n");
771 CADestroyEndpoint(endpoint);
775 printf("Generated token %s\n", token);
777 CAInfo_t requestData = { 0 };
778 requestData.token = token;
779 requestData.tokenLength = tokenLength;
780 requestData.payload = (CAPayload_t) "TempNotificationData";
781 requestData.payloadSize = strlen((const char *) requestData.payload);
782 requestData.type = messageType;
783 requestData.resourceUri = (CAURI_t)uri;
785 CARequestInfo_t requestInfo = { 0 };
786 requestInfo.method = CA_GET;
787 requestInfo.info = requestData;
790 res = CASendRequest(endpoint, &requestInfo);
791 if (CA_STATUS_OK != res)
793 printf("Send notification error, error code: %d\n", res);
797 printf("Send notification success\n");
801 CADestroyToken(token);
802 // destroy remote endpoint
803 CADestroyEndpoint(endpoint);
805 printf("\n=============================================\n");
808 void select_network()
810 printf("\n=============================================\n");
811 printf("\tselect network\n");
813 printf("GATT : 1\n");
814 printf("RFCOMM : 2\n");
818 char buf[MAX_BUF_LEN] = { 0 };
819 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
824 int number = buf[0] - '0';
826 if (number < 0 || number > 4)
828 printf("Invalid network type\n");
832 CAResult_t res = CASelectNetwork(1 << number);
833 if (CA_STATUS_OK != res)
835 printf("Select network error\n");
836 g_selected_nw_type = 1 << number;
840 printf("Select network success\n");
842 printf("=============================================\n");
845 void unselect_network()
847 printf("\n=============================================\n");
848 printf("\tunselect enabled network\n");
850 printf("GATT : 1\n");
851 printf("RFCOMM : 2\n");
855 char buf[MAX_BUF_LEN] = { 0 };
856 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
861 int number = buf[0] - '0';
863 if (number < 0 || number > 4)
865 printf("Invalid network type\n");
869 CAResult_t res = CAUnSelectNetwork(1 << number);
870 if (CA_STATUS_OK != res)
872 printf("Unselect network error\n");
876 printf("Unselect network success\n");
879 printf("=============================================\n");
884 printf("\n=============================================\n");
885 printf("\t\tMenu\n");
886 printf("\ts : start server\n");
887 printf("\tc : start client\n");
888 printf("\tr : send request\n");
889 printf("\tt : send request to all\n");
890 printf("\tb : send notification\n");
891 printf("\tn : select network\n");
892 printf("\tx : unselect network\n");
893 printf("\tg : get network information\n");
894 printf("\th : handle request response\n");
895 printf("\tz : run static server\n");
896 printf("\tw : send secure request\n");
897 printf("\tq : quit\n");
898 printf("=============================================\n");
901 char buf[MAX_BUF_LEN] = { 0 };
902 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
904 printf("Failed to get input data\n");
910 void handle_request_response()
912 printf("Handle_request_response\n");
914 CAResult_t res = CAHandleRequestResponse();
915 if (CA_STATUS_OK != res)
917 printf("Handle request error, error code: %d\n", res);
921 printf("Handle request success\n");
925 void get_network_info()
927 CAEndpoint_t *tempInfo = NULL;
928 uint32_t tempSize = 0;
930 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
931 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
933 printf("Network not connected\n");
938 printf("################## Network Information #######################\n");
939 printf("Network info total size is %d\n\n", tempSize);
942 for (index = 0; index < tempSize; index++)
944 printf("Type: %d\n", tempInfo[index].adapter);
945 if (CA_ADAPTER_IP == tempInfo[index].adapter)
947 printf("Address: %s\n", tempInfo[index].addr);
948 printf("Port: %d\n", tempInfo[index].port);
952 printf("Address: %s\n", tempInfo[index].addr);
955 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
957 if (tempInfo[index].flags & CA_SECURE)
959 g_local_secure_port = tempInfo[index].port;
960 printf("Secured: in global %d\n\n", g_local_secure_port);
965 printf("##############################################################");
968 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
970 if (NULL == object || NULL == requestInfo)
972 printf("Input parameter is NULL\n");
976 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
977 && (strncmp(g_last_request_token, requestInfo->info.token,
978 requestInfo->info.tokenLength) == 0))
980 printf("Token is same. received request of it's own. skip.. \n");
984 printf("##########received request from remote device #############\n");
985 if (CA_ADAPTER_IP == object->adapter)
987 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
988 object->port, object->flags & CA_SECURE);
992 printf("Remote Address: %s \n", object->addr);
994 printf("Data: %s\n", requestInfo->info.payload);
995 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
997 if (requestInfo->info.options)
999 uint32_t len = requestInfo->info.numOptions;
1001 for (i = 0; i < len; i++)
1003 printf("Option %d\n", i + 1);
1004 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1005 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1006 requestInfo->info.options[i].optionData);
1009 printf("############################################################\n");
1011 //Check if this has secure communication information
1012 if (requestInfo->info.payload &&
1013 (CA_ADAPTER_IP == object->adapter))
1015 int securePort = get_secure_information(requestInfo->info.payload);
1016 if (0 < securePort) //Set the remote endpoint secure details and send response
1018 printf("This is secure resource...\n");
1020 CAEndpoint_t *endpoint = NULL;
1021 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1022 object->port, &endpoint))
1024 printf("Failed to create duplicate of remote endpoint!\n");
1027 endpoint->flags = CA_SECURE;
1032 printf("Send response with URI\n");
1033 send_response(object, &requestInfo->info);
1038 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1040 printf("##########Received response from remote device #############\n");
1041 if (CA_ADAPTER_IP == object->adapter)
1043 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1044 object->port, object->flags & CA_SECURE);
1048 printf("Remote Address: %s \n", object->addr);
1051 printf("resource uri : %s\n", responseInfo->info.resourceUri);
1052 printf("response result : %d\n", responseInfo->result);
1053 printf("Data: %s\n", responseInfo->info.payload);
1054 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1055 printf("Token: %s\n", responseInfo->info.token);
1056 if (responseInfo->info.options)
1058 uint32_t len = responseInfo->info.numOptions;
1060 for (i = 0; i < len; i++)
1062 printf("Option %d\n", i + 1);
1063 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1064 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1065 responseInfo->info.options[i].optionData);
1068 printf("############################################################\n");
1071 //Check if this has secure communication information
1072 if (responseInfo->info.payload)
1074 int securePort = get_secure_information(responseInfo->info.payload);
1075 if (0 < securePort) //Set the remote endpoint secure details and send response
1077 printf("This is secure resource...\n");
1082 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1084 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1088 const CAInfo_t *info = &errorInfo->info;
1089 printf("Error Handler, ErrorInfo :\n");
1090 printf("Error Handler result : %d\n", errorInfo->result);
1091 printf("Error Handler token : %s\n", info->token);
1092 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1093 printf("Error Handler type : %d\n", info->type);
1094 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1095 printf("Error Handler payload : %s\n", info->payload);
1097 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1099 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1101 else if(CA_SEND_FAILED == errorInfo->result)
1103 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1105 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1107 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1109 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1111 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1113 else if(CA_STATUS_FAILED == errorInfo->result)
1115 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1118 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1123 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1125 printf("entering send_response\n");
1127 printf("\n=============================================\n");
1128 printf("\tselect message type\n");
1129 printf("CON : 0\n");
1130 printf("NON : 1\n");
1131 printf("ACK : 2\n");
1132 printf("RESET : 3\n");
1133 printf("select : ");
1135 char buf[MAX_BUF_LEN] = { 0 };
1136 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1141 int messageType = buf[0] - '0';
1142 int responseCode = 0 ;
1143 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1144 if (CA_MSG_RESET != messageType)
1146 printf("\n=============================================\n");
1147 printf("\tselect response code\n");
1148 printf("EMPTY : 0\n");
1149 printf("CREATED : 201\n");
1150 printf("DELETED : 202\n");
1151 printf("VALID : 203\n");
1152 printf("CHANGED : 204\n");
1153 printf("CONTENT : 205\n");
1154 printf("BAD_REQ : 400\n");
1155 printf("BAD_OPT : 402\n");
1156 printf("NOT_FOUND : 404\n");
1157 printf("INTERNAL_SERVER_ERROR : 500\n");
1158 printf("RETRANSMIT_TIMEOUT : 504\n");
1159 printf("select : ");
1161 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1165 responseCode = atoi(responseCodeBuf);
1167 CAInfo_t responseData = { 0 };
1168 responseData.type = messageType;
1169 responseData.messageId = (info != NULL) ? info->messageId : 0;
1170 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
1172 if(CA_MSG_RESET != messageType)
1174 responseData.token = (info != NULL) ? info->token : NULL;
1175 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1177 if (endpoint->flags & CA_SECURE)
1179 printf("Sending response on secure communication\n");
1181 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri)
1182 + sizeof(g_local_secure_port);
1183 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1184 if (NULL == responseData.payload)
1186 printf("Memory allocation fail\n");
1189 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1190 (const char *) responseData.resourceUri, g_local_secure_port);
1194 printf("Sending response on non-secure communication\n");
1196 bool useBigPayload = select_payload();
1199 responseData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
1200 if (NULL == responseData.payload)
1202 printf("Memory allocation fail\n");
1205 populate_binary_payload(responseData.payload, BIG_PAYLOAD_SIZE);
1209 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1210 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1211 if (NULL == responseData.payload)
1213 printf("Memory allocation fail\n");
1216 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1217 (const char *) responseData.resourceUri);
1221 responseData.payloadSize = strlen((char *)responseData.payload)+1;
1222 CAResponseInfo_t responseInfo = { 0 };
1223 responseInfo.result = responseCode;
1224 responseInfo.info = responseData;
1226 // send response (transportType from remoteEndpoint of request Info)
1227 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1228 if (CA_STATUS_OK != res)
1230 printf("Send response error\n");
1234 printf("Send response success\n");
1237 printf("=============================================\n");
1240 int get_secure_information(CAPayload_t payLoad)
1242 printf("Entering get_secure_information\n");
1246 printf("Payload is NULL\n");
1250 char *subString = NULL;
1251 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1253 printf("This is not secure resource\n");
1257 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1259 printf("This secure resource does not have port information\n");
1263 char *startPos = strstr(subString, ":");
1266 printf("Parsing failed !\n");
1270 char *endPos = strstr(startPos, "}");
1273 printf("Parsing failed !\n");
1277 char portStr[6] = {0};
1278 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1280 printf("secured port is: %s\n", portStr);
1281 return atoi(portStr);
1284 void get_resource_uri(char *URI, char *resourceURI, int length)
1286 char *startPos = URI;
1288 if (NULL != (temp = strstr(URI, "://")))
1290 startPos = strchr(temp + 3, '/');
1293 printf("Resource URI is missing\n");
1298 char *endPos = strchr(startPos, '?');
1301 endPos = URI + strlen(URI);
1305 if (endPos - startPos <= length)
1307 memcpy(resourceURI, startPos + 1, endPos - startPos);
1310 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1313 CAResult_t get_network_type()
1315 printf("\n=============================================\n");
1316 printf("\tselect network type\n");
1318 printf("GATT : 1\n");
1319 printf("RFCOMM : 2\n");
1320 printf("TCP : 4\n");
1321 printf("select : ");
1323 char buf[MAX_BUF_LEN] = { 0 };
1324 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1326 return CA_NOT_SUPPORTED ;
1329 int number = buf[0] - '0';
1330 if (0 > number || 4 < number)
1332 printf("\nInvalid Network type");
1333 return CA_NOT_SUPPORTED;
1336 g_selected_nw_type = 1 << number;
1338 return CA_STATUS_OK;
1341 CAResult_t get_input_data(char *buf, int32_t length)
1343 if (!fgets(buf, length, stdin))
1345 printf("fgets error\n");
1346 return CA_STATUS_FAILED;
1350 if ((p = strchr(buf, '\n')) != NULL)
1355 return CA_STATUS_OK;
1359 void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1363 printf("parameter is null\n");
1369 uint8_t startIndex = 0;
1370 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1372 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1373 startIndex = COAPS_PREFIX_LEN;
1376 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1378 printf("uri has '%s' prefix\n", COAP_PREFIX);
1379 startIndex = COAP_PREFIX_LEN;
1382 else if (strncmp(COAP_TCP_PREFIX, uri, COAP_TCP_PREFIX_LEN) == 0)
1384 printf("uri has '%s' prefix\n", COAP_TCP_PREFIX);
1385 startIndex = COAP_TCP_PREFIX_LEN;
1389 // #2. copy uri for parse
1390 int32_t len = strlen(uri) - startIndex;
1394 printf("uri length is 0!\n");
1398 int res = get_address_set(uri + startIndex, address);
1401 printf("address parse error\n");
1408 int get_address_set(const char *uri, addressSet_t* outAddress)
1410 if (NULL == uri || NULL == outAddress)
1412 printf("parameter is null !\n");
1416 int32_t len = strlen(uri);
1419 printf("uri length is 0!\n");
1425 for (int i = 0; i < len; i++)
1432 // found port number start index
1433 if (isIp && uri[i] == ':')
1436 outAddress->port = atoi(uri + ipLen + 1);
1445 outAddress->ipAddress[i] = uri[i];