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 // Iotivity Device Identity.
63 const unsigned char IDENTITY[] = ("1111111111111111");
65 // PSK between this device and peer device.
66 const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
69 * Max size for big payload.
71 #define BIG_PAYLOAD_SIZE 15000
73 static GMainLoop *g_mainloop = NULL;
77 uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
78 CATransportAdapter_t g_selected_nw_type = CA_ADAPTER_IP;
79 const char *MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
83 char ipAddress[CA_IPADDR_SIZE];
89 CAResult_t get_network_type();
90 CAResult_t get_input_data(char *buf, int32_t length);
92 bool select_payload();
93 void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen);
95 void start_listening_server();
96 void start_discovery_server();
98 void send_request_all();
99 void send_notification();
100 void select_network();
101 void unselect_network();
102 void handle_request_response();
103 void get_network_info();
104 void send_secure_request();
106 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo);
107 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
108 void error_handler(const CAEndpoint_t *object, const CAErrorInfo_t* errorInfo);
109 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info);
110 void get_resource_uri(char *URI, char *resourceURI, int length);
111 int get_secure_information(CAPayload_t payLoad);
112 int get_address_set(const char *uri, addressSet_t* outAddress);
113 void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags);
115 static CAToken_t g_last_request_token = NULL;
116 static const char SECURE_COAPS_PREFIX[] = "coaps://";
117 static const char SECURE_INFO_DATA[] =
118 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
119 "\"if\":[\"oic.if.baseline\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
120 static const char NORMAL_INFO_DATA[] =
121 "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
122 "\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
125 // Internal API. Invoked by CA stack to retrieve credentials from this module.
126 int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
127 const unsigned char *desc, size_t desc_len,
128 unsigned char *result, size_t result_length)
130 printf("CAGetDtlsPskCredentials IN\n");
141 case CA_DTLS_PSK_HINT:
142 case CA_DTLS_PSK_IDENTITY:
144 if (result_length < sizeof(IDENTITY))
146 printf("ERROR : Wrong value for result for storing IDENTITY");
150 memcpy(result, IDENTITY, sizeof(IDENTITY));
151 ret = sizeof(IDENTITY);
154 case CA_DTLS_PSK_KEY:
156 if ((desc_len == sizeof(IDENTITY)) &&
157 memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
159 if (result_length < sizeof(RS_CLIENT_PSK))
161 printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
165 memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
166 ret = sizeof(RS_CLIENT_PSK);
172 printf("Wrong value passed for PSK_CRED_TYPE.");
176 printf("CAGetDtlsPskCredentials OUT\n");
181 void GMainLoopThread()
183 g_main_loop_run(g_mainloop);
186 CAResult_t Initialize()
188 g_mainloop = g_main_loop_new(NULL, FALSE);
191 printf("g_main_loop_new failed\n");
192 return CA_STATUS_FAILED;
195 int result = pthread_create(&thread, NULL, (void *) &GMainLoopThread, NULL);
198 printf("pthread_create failed in initialize\n");
199 return CA_STATUS_FAILED;
202 CAResult_t res = CAInitialize();
203 if (res != CA_STATUS_OK)
205 printf("CAInitialize fail\n");
212 int ret = system("clear");
213 // shell invoke error: 127, others: -1
214 if (127 == ret || -1 == ret)
216 printf("Terminal Clear Error: %d\n", ret);
219 printf("=============================================\n");
220 printf("\t\tsample main\n");
221 printf("=============================================\n");
223 CAResult_t res = Initialize();
224 if (CA_STATUS_OK != res)
226 printf("Initialization is failed\n");
230 // Set the PSK Credentials callback handler.
232 res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
233 if (CA_STATUS_OK != res)
235 printf("Set credential handler fail\n");
241 CARegisterHandler(request_handler, response_handler, error_handler);
245 CADestroyToken(g_last_request_token);
255 char menu = get_menu();
265 printf("quit..!!\n");
268 case 's': // start server
270 start_listening_server();
273 case 't': // send request
278 case 'c': // start client
280 start_discovery_server();
283 case 'r': // send request
288 case 'b': // send notification
293 case 'n': // select network
298 case 'x': // unselect network
303 case 'h': // handle request response
305 handle_request_response();
311 start_discovery_server();
312 send_secure_request();
313 while (g_received == 0)
316 handle_request_response();
322 start_listening_server();
326 handle_request_response();
330 case 'g': // get network information
336 printf("Not supported menu!!\n");
343 void start_listening_server()
345 printf("Start listening server!!\n");
347 CAResult_t res = CAStartListeningServer();
348 if (CA_STATUS_OK != res)
350 printf("Start listening server fail, error code : %d\n", res);
354 printf("Start listening server success\n");
358 void start_discovery_server()
360 printf("Start discovery client!!\n");
362 CAResult_t res = CAStartDiscoveryServer();
363 if (CA_STATUS_OK != res)
365 printf("Start discovery client fail, error code : %d\n", res);
369 printf("Start discovery client success\n");
373 bool select_payload()
375 char buf[MAX_BUF_LEN]={0};
376 printf("\n=============================================\n");
377 printf("0:Normal Payload\n1:Big Payload(~15KB)\n");
378 printf("select Payload type : ");
380 CAResult_t res = get_input_data(buf, sizeof(buf));
381 if (CA_STATUS_OK != res)
383 printf("Payload type selection error\n");
384 printf("Default: Using normal Payload\n");
388 return (buf[0] == '1') ? true : false;
391 void populate_binary_payload(uint8_t *bigBuffer, size_t bigBufferLen)
394 * bigBuffer to be filled with binary data. For our sample application to verify, we may fill with
395 * any arbitrary value. Hence filling with '1' here.
397 memset(bigBuffer, '1', bigBufferLen-1);
398 //Last byte making NULL
399 bigBuffer[bigBufferLen-1] = '\0';
404 CAResult_t res = get_network_type();
405 if (CA_STATUS_OK != res)
410 printf("Do you want to send secure request ?.... enter (0/1): ");
412 char secureRequest[MAX_BUF_LEN] = {0};
413 if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
418 if (strcmp(secureRequest, "1") == 0)
420 printf("Enter the URI like below....\n");
421 printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
423 else if (strcmp(secureRequest, "0") == 0)
425 printf("Enter the URI like below....\n");
426 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
427 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
431 printf("Input data is wrong value\n");
435 char uri[MAX_BUF_LEN] = {'\0'};
436 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
441 // create remote endpoint
442 CAEndpoint_t *endpoint = NULL;
443 CATransportFlags_t flags;
445 printf("URI : %s\n", uri);
446 addressSet_t address = {};
447 parse_coap_uri(uri, &address, &flags);
449 res = CACreateEndpoint(flags, g_selected_nw_type,
450 (const char*)address.ipAddress, address.port, &endpoint);
451 if (CA_STATUS_OK != res || !endpoint)
453 printf("Failed to create remote endpoint, error code : %d\n", res);
457 printf("\n=============================================\n");
458 printf("0:CON, 1:NON\n");
459 printf("select message type : ");
461 char buf[MAX_BUF_LEN] = { 0 };
462 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
464 CADestroyEndpoint(endpoint);
468 CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
471 CAToken_t token = NULL;
472 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
474 res = CAGenerateToken(&token, tokenLength);
475 if ((CA_STATUS_OK != res) || (!token))
477 printf("Token generate error, error code : %d\n", res);
478 CADestroyEndpoint(endpoint);
482 printf("Generated token %s\n", token);
484 // extract relative resourceuri from give uri
485 char resourceURI[RESOURCE_URI_LENGTH + 1] = {0};
486 get_resource_uri(uri, resourceURI, RESOURCE_URI_LENGTH);
487 printf("resourceURI : %s\n", resourceURI);
489 // create request data
490 CAInfo_t requestData = { 0 };
491 requestData.token = token;
492 requestData.tokenLength = tokenLength;
493 requestData.resourceUri = (CAURI_t)resourceURI;
495 if (strcmp(secureRequest, "1") == 0)
497 size_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
498 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
499 if (NULL == requestData.payload)
501 printf("Memory allocation fail\n");
502 CADestroyEndpoint(endpoint);
503 CADestroyToken(token);
506 snprintf((char *) requestData.payload, length, SECURE_INFO_DATA,
507 (const char *) resourceURI, g_local_secure_port);
511 bool useBigPayload = select_payload();
514 requestData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
515 if (NULL == requestData.payload)
517 printf("Memory allocation fail\n");
518 CADestroyEndpoint(endpoint);
519 CADestroyToken(token);
522 populate_binary_payload(requestData.payload, BIG_PAYLOAD_SIZE);
526 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
527 requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
528 if (NULL == requestData.payload)
530 printf("Memory allocation fail\n");
531 CADestroyEndpoint(endpoint);
532 CADestroyToken(token);
535 snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA,
536 (const char *) resourceURI);
539 requestData.payloadSize = strlen((char *)requestData.payload)+1;
540 requestData.type = msgType;
542 CARequestInfo_t requestInfo = { 0 };
543 requestInfo.method = CA_GET;
544 requestInfo.info = requestData;
545 requestInfo.isMulticast = false;
548 res = CASendRequest(endpoint, &requestInfo);
549 if (CA_STATUS_OK != res)
551 printf("Could not send request : %d\n", res);
555 CADestroyToken(token);
556 // destroy remote endpoint
557 CADestroyEndpoint(endpoint);
558 free(requestData.payload);
561 printf("=============================================\n");
564 void send_secure_request()
566 char ipv4addr[CA_IPADDR_SIZE];
568 printf("\n=============================================\n");
569 printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
571 if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
575 printf("%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
577 // create remote endpoint
578 CAEndpoint_t *endpoint = NULL;
579 CAResult_t res = CACreateEndpoint(0, CA_ADAPTER_IP, ipv4addr, SECURE_DEFAULT_PORT, &endpoint);
580 if (CA_STATUS_OK != res)
582 printf("Failed to create remote endpoint, error code: %d\n", res);
587 CAToken_t token = NULL;
588 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
590 res = CAGenerateToken(&token, tokenLength);
591 if ((CA_STATUS_OK != res) || (!token))
593 printf("Token generate error, error code : %d\n", res);
597 printf("Generated token %s\n", token);
599 // create request data
600 CAMessageType_t msgType = CA_MSG_NONCONFIRM;
601 CAInfo_t requestData = { 0 };
602 requestData.token = token;
603 requestData.tokenLength = tokenLength;
604 requestData.type = msgType;
605 requestData.payload = "Temp Json Payload";
606 requestData.payloadSize = strlen(requestData.payload)+1;
608 CARequestInfo_t requestInfo = { 0 };
609 requestInfo.method = CA_GET;
610 requestInfo.info = requestData;
611 requestInfo.isMulticast = false;
614 CASendRequest(endpoint, &requestInfo);
618 CADestroyToken(token);
619 CADestroyEndpoint(endpoint);
620 printf("=============================================\n");
624 void send_request_all()
626 CAResult_t res = get_network_type();
627 if (CA_STATUS_OK != res)
632 printf("\n=============================================\n");
633 printf("ex) /a/light\n");
634 printf("resource uri : ");
636 char resourceURI[MAX_BUF_LEN] = { 0 };
637 if (CA_STATUS_OK != get_input_data(resourceURI, MAX_BUF_LEN))
642 // create remote endpoint
643 CAEndpoint_t *endpoint = NULL;
644 res = CACreateEndpoint(CA_IPV4, g_selected_nw_type, NULL, 0, &endpoint);
645 if (CA_STATUS_OK != res)
647 printf("Create remote endpoint error, error code: %d\n", res);
652 CAToken_t token = NULL;
653 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
655 res = CAGenerateToken(&token, tokenLength);
656 if ((CA_STATUS_OK != res) || (!token))
658 printf("Token generate error!!\n");
659 CADestroyEndpoint(endpoint);
663 printf("generated token %s\n", token);
665 CAInfo_t requestData = { 0 };
666 requestData.token = token;
667 requestData.tokenLength = tokenLength;
668 requestData.payload = (CAPayload_t) "TempJsonPayload";
669 requestData.payloadSize = strlen((const char *) requestData.payload);
670 requestData.type = CA_MSG_NONCONFIRM;
671 requestData.resourceUri = (CAURI_t)resourceURI;
673 CARequestInfo_t requestInfo = { 0 };
674 requestInfo.method = CA_GET;
675 requestInfo.info = requestData;
676 requestInfo.isMulticast = true;
679 res = CASendRequest(endpoint, &requestInfo);
680 if (CA_STATUS_OK != res)
682 printf("Could not send request to all\n");
683 CADestroyEndpoint(endpoint);
687 CADestroyToken(g_last_request_token);
688 g_last_request_token = token;
691 // destroy remote endpoint
692 CADestroyEndpoint(endpoint);
694 printf("=============================================\n");
697 void send_notification()
699 CAResult_t res = get_network_type();
700 if (CA_STATUS_OK != res)
705 printf("\n=============================================\n");
706 printf("Enter the URI like below....\n");
707 printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
708 printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
711 char uri[MAX_BUF_LEN] = { 0 };
712 if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
717 printf("\n=============================================\n");
718 printf("\tselect message type\n");
722 printf("RESET : 3\n");
726 char messageTypeBuf[MAX_BUF_LEN] = { 0 };
727 if (CA_STATUS_OK != get_input_data(messageTypeBuf, MAX_BUF_LEN))
732 int messageType = messageTypeBuf[0] - '0';
737 printf("CONFIRM messagetype is selected\n");
740 printf("NONCONFIRM messagetype is selected\n");
743 printf("Invalid Selection\n");
747 CATransportFlags_t flags;
748 addressSet_t address = {};
749 parse_coap_uri(uri, &address, &flags);
751 // create remote endpoint
752 CAEndpoint_t *endpoint = NULL;
753 res = CACreateEndpoint(flags, g_selected_nw_type, address.ipAddress, address.port, &endpoint);
754 if (CA_STATUS_OK != res)
756 printf("Create remote endpoint error, error code: %d\n", res);
761 CAToken_t token = NULL;
762 uint8_t tokenLength = CA_MAX_TOKEN_LEN;
764 res = CAGenerateToken(&token, tokenLength);
765 if ((CA_STATUS_OK != res) || (!token))
767 printf("Token generate error!!\n");
768 CADestroyEndpoint(endpoint);
772 printf("Generated token %s\n", token);
774 CAInfo_t respondData = { 0 };
775 respondData.token = token;
776 respondData.tokenLength = tokenLength;
777 respondData.payload = (CAPayload_t) "TempNotificationData";
778 respondData.payloadSize = strlen((const char *) respondData.payload);
779 respondData.type = messageType;
780 respondData.resourceUri = (CAURI_t)uri;
782 CAResponseInfo_t responseInfo = { 0 };
783 responseInfo.result = CA_CONTENT;
784 responseInfo.info = respondData;
787 res = CASendNotification(endpoint, &responseInfo);
788 if (CA_STATUS_OK != res)
790 printf("Send notification error, error code: %d\n", res);
794 printf("Send notification success\n");
798 CADestroyToken(token);
799 // destroy remote endpoint
800 CADestroyEndpoint(endpoint);
802 printf("\n=============================================\n");
805 void select_network()
807 printf("\n=============================================\n");
808 printf("\tselect network\n");
810 printf("GATT : 1\n");
811 printf("RFCOMM : 2\n");
814 char buf[MAX_BUF_LEN] = { 0 };
815 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
820 int number = buf[0] - '0';
822 if (number < 0 || number > 3)
824 printf("Invalid network type\n");
828 CAResult_t res = CASelectNetwork(1 << number);
829 if (CA_STATUS_OK != res)
831 printf("Select network error\n");
832 g_selected_nw_type = 1 << number;
836 printf("Select network success\n");
838 printf("=============================================\n");
841 void unselect_network()
843 printf("\n=============================================\n");
844 printf("\tunselect enabled network\n");
846 printf("GATT : 1\n");
847 printf("RFCOMM : 2\n");
850 char buf[MAX_BUF_LEN] = { 0 };
851 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
856 int number = buf[0] - '0';
858 if (number < 0 || number > 3)
860 printf("Invalid network type\n");
864 CAResult_t res = CAUnSelectNetwork(1 << number);
865 if (CA_STATUS_OK != res)
867 printf("Unselect network error\n");
871 printf("Unselect network success\n");
874 printf("=============================================\n");
879 printf("\n=============================================\n");
880 printf("\t\tMenu\n");
881 printf("\ts : start server\n");
882 printf("\tc : start client\n");
883 printf("\tr : send request\n");
884 printf("\tt : send request to all\n");
885 printf("\tb : send notification\n");
886 printf("\tn : select network\n");
887 printf("\tx : unselect network\n");
888 printf("\tg : get network information\n");
889 printf("\th : handle request response\n");
890 printf("\tz : run static server\n");
891 printf("\tw : send secure request\n");
892 printf("\tq : quit\n");
893 printf("=============================================\n");
896 char buf[MAX_BUF_LEN] = { 0 };
897 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
899 printf("Failed to get input data\n");
905 void handle_request_response()
907 printf("Handle_request_response\n");
909 CAResult_t res = CAHandleRequestResponse();
910 if (CA_STATUS_OK != res)
912 printf("Handle request error, error code: %d\n", res);
916 printf("Handle request success\n");
920 void get_network_info()
922 CAEndpoint_t *tempInfo = NULL;
923 uint32_t tempSize = 0;
925 CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
926 if (CA_STATUS_OK != res || NULL == tempInfo || 0 >= tempSize)
928 printf("Network not connected\n");
933 printf("################## Network Information #######################\n");
934 printf("Network info total size is %d\n\n", tempSize);
937 for (index = 0; index < tempSize; index++)
939 printf("Type: %d\n", tempInfo[index].adapter);
940 if (CA_ADAPTER_IP == tempInfo[index].adapter)
942 printf("Address: %s\n", tempInfo[index].addr);
943 printf("Port: %d\n", tempInfo[index].port);
947 printf("Address: %s\n", tempInfo[index].addr);
950 printf("Secured: %s\n\n", (tempInfo[index].flags & CA_SECURE) ? "true" : "false");
952 if (tempInfo[index].flags & CA_SECURE)
954 g_local_secure_port = tempInfo[index].port;
955 printf("Secured: in global %d\n\n", g_local_secure_port);
960 printf("##############################################################");
963 void request_handler(const CAEndpoint_t *object, const CARequestInfo_t *requestInfo)
965 if (NULL == object || NULL == requestInfo)
967 printf("Input parameter is NULL\n");
971 if ((NULL != g_last_request_token) && (NULL != requestInfo->info.token)
972 && (strncmp(g_last_request_token, requestInfo->info.token,
973 requestInfo->info.tokenLength) == 0))
975 printf("Token is same. received request of it's own. skip.. \n");
979 printf("##########received request from remote device #############\n");
980 if (CA_ADAPTER_IP == object->adapter)
982 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
983 object->port, object->flags & CA_SECURE);
987 printf("Remote Address: %s \n", object->addr);
989 printf("Data: %s\n", requestInfo->info.payload);
990 printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
992 if (requestInfo->info.options)
994 uint32_t len = requestInfo->info.numOptions;
996 for (i = 0; i < len; i++)
998 printf("Option %d\n", i + 1);
999 printf("ID : %d\n", requestInfo->info.options[i].optionID);
1000 printf("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
1001 requestInfo->info.options[i].optionData);
1004 printf("############################################################\n");
1006 //Check if this has secure communication information
1007 if (requestInfo->info.payload &&
1008 (CA_ADAPTER_IP == object->adapter))
1010 int securePort = get_secure_information(requestInfo->info.payload);
1011 if (0 < securePort) //Set the remote endpoint secure details and send response
1013 printf("This is secure resource...\n");
1015 CAEndpoint_t *endpoint = NULL;
1016 if (CA_STATUS_OK != CACreateEndpoint(0, object->adapter, object->addr,
1017 object->port, &endpoint))
1019 printf("Failed to create duplicate of remote endpoint!\n");
1022 endpoint->flags = CA_SECURE;
1027 printf("Send response with URI\n");
1028 send_response(object, &requestInfo->info);
1033 void response_handler(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
1035 printf("##########Received response from remote device #############\n");
1036 if (CA_ADAPTER_IP == object->adapter)
1038 printf("Remote Address: %s Port: %d secured:%d\n", object->addr,
1039 object->port, object->flags & CA_SECURE);
1043 printf("Remote Address: %s \n", object->addr);
1046 printf("resource uri : %s\n", responseInfo->info.resourceUri);
1047 printf("response result : %d\n", responseInfo->result);
1048 printf("Data: %s\n", responseInfo->info.payload);
1049 printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
1050 printf("Token: %s\n", responseInfo->info.token);
1051 if (responseInfo->info.options)
1053 uint32_t len = responseInfo->info.numOptions;
1055 for (i = 0; i < len; i++)
1057 printf("Option %d\n", i + 1);
1058 printf("ID : %d\n", responseInfo->info.options[i].optionID);
1059 printf("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
1060 responseInfo->info.options[i].optionData);
1063 printf("############################################################\n");
1066 //Check if this has secure communication information
1067 if (responseInfo->info.payload)
1069 int securePort = get_secure_information(responseInfo->info.payload);
1070 if (0 < securePort) //Set the remote endpoint secure details and send response
1072 printf("This is secure resource...\n");
1077 void error_handler(const CAEndpoint_t *rep, const CAErrorInfo_t* errorInfo)
1079 printf("+++++++++++++++++++++++++++++++++++ErrorInfo+++++++++++++++++++++++++++++++++++\n");
1083 const CAInfo_t *info = &errorInfo->info;
1084 printf("Error Handler, ErrorInfo :\n");
1085 printf("Error Handler result : %d\n", errorInfo->result);
1086 printf("Error Handler token : %s\n", info->token);
1087 printf("Error Handler messageId : %d\n", (uint16_t) info->messageId);
1088 printf("Error Handler type : %d\n", info->type);
1089 printf("Error Handler resourceUri : %s\n", info->resourceUri);
1090 printf("Error Handler payload : %s\n", info->payload);
1092 if(CA_ADAPTER_NOT_ENABLED == errorInfo->result)
1094 printf("CA_ADAPTER_NOT_ENABLED, enable the adapter\n");
1096 else if(CA_SEND_FAILED == errorInfo->result)
1098 printf("CA_SEND_FAILED, unable to send the message, check parameters\n");
1100 else if(CA_MEMORY_ALLOC_FAILED == errorInfo->result)
1102 printf("CA_MEMORY_ALLOC_FAILED, insufficient memory\n");
1104 else if(CA_SOCKET_OPERATION_FAILED == errorInfo->result)
1106 printf("CA_SOCKET_OPERATION_FAILED, socket operation failed\n");
1108 else if(CA_STATUS_FAILED == errorInfo->result)
1110 printf("CA_STATUS_FAILED, message could not be delivered, internal error\n");
1113 printf("++++++++++++++++++++++++++++++++End of ErrorInfo++++++++++++++++++++++++++++++++\n");
1118 void send_response(const CAEndpoint_t *endpoint, const CAInfo_t *info)
1120 printf("entering send_response\n");
1122 printf("\n=============================================\n");
1123 printf("\tselect message type\n");
1124 printf("CON : 0\n");
1125 printf("NON : 1\n");
1126 printf("ACK : 2\n");
1127 printf("RESET : 3\n");
1128 printf("select : ");
1130 char buf[MAX_BUF_LEN] = { 0 };
1131 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1136 int messageType = buf[0] - '0';
1137 int responseCode = 0 ;
1138 char responseCodeBuf[MAX_BUF_LEN] = { 0 };
1139 if (CA_MSG_RESET != messageType)
1141 printf("\n=============================================\n");
1142 printf("\tselect response code\n");
1143 printf("EMPTY : 0\n");
1144 printf("CREATED : 201\n");
1145 printf("DELETED : 202\n");
1146 printf("VALID : 203\n");
1147 printf("CHANGED : 204\n");
1148 printf("CONTENT : 205\n");
1149 printf("BAD_REQ : 400\n");
1150 printf("BAD_OPT : 402\n");
1151 printf("NOT_FOUND : 404\n");
1152 printf("INTERNAL_SERVER_ERROR : 500\n");
1153 printf("RETRANSMIT_TIMEOUT : 504\n");
1154 printf("select : ");
1156 if (CA_STATUS_OK != get_input_data(responseCodeBuf, MAX_BUF_LEN))
1160 responseCode = atoi(responseCodeBuf);
1162 CAInfo_t responseData = { 0 };
1163 responseData.type = messageType;
1164 responseData.messageId = (info != NULL) ? info->messageId : 0;
1165 responseData.resourceUri = (info != NULL) ? info->resourceUri : 0;
1167 if(CA_MSG_RESET != messageType)
1169 responseData.token = (info != NULL) ? info->token : NULL;
1170 responseData.tokenLength = (info != NULL) ? info->tokenLength : 0;
1172 if (endpoint->flags & CA_SECURE)
1174 printf("Sending response on secure communication\n");
1176 uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(responseData.resourceUri)
1177 + sizeof(g_local_secure_port);
1178 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1179 if (NULL == responseData.payload)
1181 printf("Memory allocation fail\n");
1184 snprintf((char *) responseData.payload, length, SECURE_INFO_DATA,
1185 (const char *) responseData.resourceUri, g_local_secure_port);
1189 printf("Sending response on non-secure communication\n");
1191 bool useBigPayload = select_payload();
1194 responseData.payload = (CAPayload_t) calloc(BIG_PAYLOAD_SIZE, sizeof(char));
1195 if (NULL == responseData.payload)
1197 printf("Memory allocation fail\n");
1200 populate_binary_payload(responseData.payload, BIG_PAYLOAD_SIZE);
1204 size_t length = sizeof(NORMAL_INFO_DATA) + strlen(responseData.resourceUri);
1205 responseData.payload = (CAPayload_t) calloc(length, sizeof(char));
1206 if (NULL == responseData.payload)
1208 printf("Memory allocation fail\n");
1211 snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA,
1212 (const char *) responseData.resourceUri);
1216 responseData.payloadSize = strlen((char *)responseData.payload)+1;
1217 CAResponseInfo_t responseInfo = { 0 };
1218 responseInfo.result = responseCode;
1219 responseInfo.info = responseData;
1221 // send response (transportType from remoteEndpoint of request Info)
1222 CAResult_t res = CASendResponse(endpoint, &responseInfo);
1223 if (CA_STATUS_OK != res)
1225 printf("Send response error\n");
1229 printf("Send response success\n");
1232 printf("=============================================\n");
1235 int get_secure_information(CAPayload_t payLoad)
1237 printf("Entering get_secure_information\n");
1241 printf("Payload is NULL\n");
1245 char *subString = NULL;
1246 if (NULL == (subString = strstr((const char *) payLoad, "\"sec\":1")))
1248 printf("This is not secure resource\n");
1252 if (NULL == (subString = strstr((const char *) payLoad, "\"port\":")))
1254 printf("This secure resource does not have port information\n");
1258 char *startPos = strstr(subString, ":");
1261 printf("Parsing failed !\n");
1265 char *endPos = strstr(startPos, "}");
1268 printf("Parsing failed !\n");
1272 char portStr[6] = {0};
1273 memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
1275 printf("secured port is: %s\n", portStr);
1276 return atoi(portStr);
1279 void get_resource_uri(char *URI, char *resourceURI, int length)
1281 char *startPos = URI;
1283 if (NULL != (temp = strstr(URI, "://")))
1285 startPos = strchr(temp + 3, '/');
1288 printf("Resource URI is missing\n");
1293 char *endPos = strchr(startPos, '?');
1296 endPos = URI + strlen(URI);
1300 if (endPos - startPos <= length)
1302 memcpy(resourceURI, startPos + 1, endPos - startPos);
1305 printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
1308 CAResult_t get_network_type()
1310 printf("\n=============================================\n");
1311 printf("\tselect network type\n");
1313 printf("GATT : 1\n");
1314 printf("RFCOMM : 2\n");
1315 printf("select : ");
1317 char buf[MAX_BUF_LEN] = { 0 };
1318 if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
1320 return CA_NOT_SUPPORTED ;
1323 int number = buf[0] - '0';
1324 if (0 > number || 2 < number)
1326 printf("\nInvalid Network type");
1327 return CA_NOT_SUPPORTED;
1330 g_selected_nw_type = 1 << number;
1332 return CA_STATUS_OK;
1335 CAResult_t get_input_data(char *buf, int32_t length)
1337 if (!fgets(buf, length, stdin))
1339 printf("fgets error\n");
1340 return CA_STATUS_FAILED;
1344 if ((p = strchr(buf, '\n')) != NULL)
1349 return CA_STATUS_OK;
1353 void parse_coap_uri(const char* uri, addressSet_t* address, CATransportFlags_t *flags)
1357 printf("parameter is null\n");
1363 uint8_t startIndex = 0;
1364 if (strncmp(COAPS_PREFIX, uri, COAPS_PREFIX_LEN) == 0)
1366 printf("uri has '%s' prefix\n", COAPS_PREFIX);
1367 startIndex = COAPS_PREFIX_LEN;
1370 else if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
1372 printf("uri has '%s' prefix\n", COAP_PREFIX);
1373 startIndex = COAP_PREFIX_LEN;
1377 // #2. copy uri for parse
1378 int32_t len = strlen(uri) - startIndex;
1382 printf("uri length is 0!\n");
1386 int res = get_address_set(uri + startIndex, address);
1389 printf("address parse error\n");
1396 int get_address_set(const char *uri, addressSet_t* outAddress)
1398 if (NULL == uri || NULL == outAddress)
1400 printf("parameter is null !\n");
1404 int32_t len = strlen(uri);
1407 printf("uri length is 0!\n");
1413 for (int i = 0; i < len; i++)
1420 // found port number start index
1421 if (isIp && uri[i] == ':')
1424 outAddress->port = atoi(uri + ipLen + 1);
1433 outAddress->ipAddress[i] = uri[i];