1 /* *****************************************************************
3 * Copyright 2015 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 * *****************************************************************/
20 #ifndef _POSIX_C_SOURCE
21 #define _POSIX_C_SOURCE 200112L
30 #include "oic_malloc.h"
31 #include "oic_string.h"
35 #include "ocpayload.h"
36 #include "payload_logging.h"
38 #include "securevirtualresourcetypes.h"
39 #include "srmresourcestrings.h" //@note: SRM's internal header
40 #include "doxmresource.h" //@note: SRM's internal header
41 #include "pstatresource.h" //@note: SRM's internal header
44 #include "pmutility.h"
46 #include "srmutility.h"
48 #define TAG ("PM-UTILITY")
50 typedef struct _DiscoveryInfo{
51 OCProvisionDev_t **ppDevicesList;
52 bool isOwnedDiscovery;
56 * Function to search node in linked list that matches given IP and port.
58 * @param[in] pList List of OCProvisionDev_t.
59 * @param[in] addr address of target device.
60 * @param[in] port port of remote server.
62 * @return pointer of OCProvisionDev_t if exist, otherwise NULL
64 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
66 if(NULL == addr || NULL == *ppDevicesList)
68 OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
72 OCProvisionDev_t *ptr = NULL;
73 LL_FOREACH(*ppDevicesList, ptr)
75 if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
86 * Add device information to list.
88 * @param[in] pList List of OCProvisionDev_t.
89 * @param[in] addr address of target device.
90 * @param[in] port port of remote server.
91 * @param[in] adapter adapter type of endpoint.
92 * @param[in] doxm pointer to doxm instance.
93 * @param[in] connType connectivity type of endpoint
95 * @return OC_STACK_OK for success and errorcode otherwise.
97 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
98 OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
102 return OC_STACK_INVALID_PARAM;
105 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
108 ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
111 OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
112 return OC_STACK_NO_MEMORY;
115 OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
116 ptr->endpoint.port = port;
118 ptr->securePort = DEFAULT_SECURE_PORT;
119 ptr->endpoint.adapter = adapter;
121 ptr->connType = connType;
122 ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
124 LL_PREPEND(*ppDevicesList, ptr);
131 * Function to set secure port information from the given list of devices.
133 * @param[in] pList List of OCProvisionDev_t.
134 * @param[in] addr address of target device.
135 * @param[in] port port of remote server.
136 * @param[in] secureport secure port information.
138 * @return OC_STACK_OK for success and errorcode otherwise.
140 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
141 uint16_t port, uint16_t securePort)
143 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
147 OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
148 return OC_STACK_ERROR;
151 ptr->securePort = securePort;
157 * This function deletes list of provision target devices
159 * @param[in] pDevicesList List of OCProvisionDev_t.
161 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
165 OCProvisionDev_t *del = NULL, *tmp = NULL;
166 LL_FOREACH_SAFE(pDevicesList, del, tmp)
168 LL_DELETE(pDevicesList, del);
170 DeleteDoxmBinData(del->doxm);
171 DeletePstatBinData(del->pstat);
177 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
179 OC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
183 OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
187 // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
188 OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
189 VERIFY_NON_NULL(TAG, newDev, ERROR);
191 memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
195 newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
196 VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
198 memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
199 // We have to assign NULL for not necessary information to prevent memory corruption.
200 newDev->pstat->sm = NULL;
205 newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
206 VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
208 memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
209 // We have to assign NULL for not necessary information to prevent memory corruption.
210 newDev->doxm->oxm = NULL;
213 newDev->securePort = src->securePort;
214 newDev->devStatus = src->devStatus;
215 newDev->connType = src->connType;
218 OC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
223 OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
226 OICFree(newDev->pstat);
227 OICFree(newDev->doxm);
234 * Timeout implementation for secure discovery. When performing secure discovery,
235 * we should wait a certain period of time for getting response of each devices.
237 * @param[in] waittime Timeout in seconds.
238 * @param[in] waitForStackResponse if true timeout function will call OCProcess while waiting.
239 * @return OC_STACK_OK on success otherwise error.
241 OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
243 struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
244 struct timespec currTime = {.tv_sec=0, .tv_nsec=0};
246 OCStackResult res = OC_STACK_OK;
247 #ifdef _POSIX_MONOTONIC_CLOCK
248 int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
250 int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
254 return OC_STACK_ERROR;
256 while (OC_STACK_OK == res)
258 #ifdef _POSIX_MONOTONIC_CLOCK
259 clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
261 clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
265 return OC_STACK_TIMEOUT;
267 long elapsed = (currTime.tv_sec - startTime.tv_sec);
268 if (elapsed > waittime)
272 if (waitForStackResponse)
281 * Extract secure port information from payload of discovery response.
283 * @param[in] jsonStr response payload of /oic/res discovery.
285 * @return Secure port
287 uint16_t GetSecurePortFromJSON(char* jsonStr)
289 // TODO: Modify error handling
294 cJSON *jsonProp = NULL;
296 cJSON *jsonPort = NULL;
298 cJSON *jsonRoot = cJSON_Parse(jsonStr);
301 // TODO: Add error log & return default secure port
305 jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
308 // TODO: Add error log & return default secure port
312 jsonP = cJSON_GetObjectItem(jsonProp, "p");
315 // TODO: Add error log & return default secure port
319 jsonPort = cJSON_GetObjectItem(jsonP, "port");
322 // TODO: Add error log & return default secure port
326 return (uint16_t)jsonPort->valueint;
329 bool PMGenerateQuery(bool isSecure,
330 const char* address, const uint16_t port,
331 const OCConnectivityType connType,
332 char* buffer, size_t bufferSize, const char* uri)
334 if(!address || !buffer || !uri)
336 OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
341 char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
343 switch(connType & CT_MASK_ADAPTER)
346 switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
349 snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
350 prefix, address, port, uri);
353 snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
354 prefix, address, port, uri);
357 OC_LOG(ERROR, TAG, "Unknown address format.");
360 // snprintf return value check
363 OC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
366 else if ((size_t)snRet >= bufferSize)
368 OC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
373 // TODO: We need to verify tinyDTLS in below cases
374 case CT_ADAPTER_GATT_BTLE:
375 case CT_ADAPTER_RFCOMM_BTEDR:
376 OC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
380 OC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
388 * Callback handler for getting secure port information using /oic/res discovery.
390 * @param[in] ctx user context
391 * @param[in] handle Handle for response
392 * @param[in] clientResponse Response information(It will contain payload)
394 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
395 * OC_STACK_DELETE_TRANSACTION to delete it.
397 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
398 OCClientResponse *clientResponse)
402 OC_LOG(ERROR, TAG, "Lost List of device information");
403 return OC_STACK_DELETE_TRANSACTION;
408 if (NULL == clientResponse->payload)
410 OC_LOG(INFO, TAG, "Skiping Null payload");
414 OC_LOG_PAYLOAD(DEBUG, clientResponse->payload);
416 if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
418 OC_LOG(INFO, TAG, "Wrong payload type");
419 return OC_STACK_DELETE_TRANSACTION;
422 uint16_t securePort = 0;
423 OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
425 if (resPayload && resPayload->secure)
427 securePort = resPayload->port;
431 OC_LOG(INFO, TAG, "Can not find secure port information.");
432 return OC_STACK_DELETE_TRANSACTION;
435 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
436 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
438 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
439 clientResponse->devAddr.port, securePort);
440 if (OC_STACK_OK != res)
442 OC_LOG(ERROR, TAG, "Error while getting secure port.");
443 return OC_STACK_DELETE_TRANSACTION;
445 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
448 return OC_STACK_DELETE_TRANSACTION;
452 OC_LOG(INFO, TAG, "Skiping Null response");
454 return OC_STACK_DELETE_TRANSACTION;
458 * Callback handler for PMDeviceDiscovery API.
460 * @param[in] ctx User context
461 * @param[in] handle Handler for response
462 * @param[in] clientResponse Response information (It will contain payload)
463 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
464 * OC_STACK_DELETE_TRANSACTION to delete it.
466 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
467 OCClientResponse *clientResponse)
471 OC_LOG(ERROR, TAG, "Lost List of device information");
472 return OC_STACK_KEEP_TRANSACTION;
477 if (NULL == clientResponse->payload)
479 OC_LOG(INFO, TAG, "Skiping Null payload");
480 return OC_STACK_KEEP_TRANSACTION;
482 if (OC_STACK_OK != clientResponse->result)
484 OC_LOG(INFO, TAG, "Error in response");
485 return OC_STACK_KEEP_TRANSACTION;
489 OC_LOG_PAYLOAD(DEBUG, clientResponse->payload);
491 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
493 OC_LOG(INFO, TAG, "Unknown payload type");
494 return OC_STACK_KEEP_TRANSACTION;
496 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
497 ((OCSecurityPayload*)clientResponse->payload)->securityData, false);
500 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
501 return OC_STACK_KEEP_TRANSACTION;
505 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
507 //If this is owend device discovery we have to filter out the responses.
508 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
509 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
511 // Get my device ID from doxm resource
513 memset(&myId, 0, sizeof(myId));
514 OCStackResult res = GetDoxmDevOwnerId(&myId);
515 if(OC_STACK_OK != res)
517 OC_LOG(ERROR, TAG, "Error while getting my device ID.");
518 DeleteDoxmBinData(ptrDoxm);
519 return OC_STACK_KEEP_TRANSACTION;
522 // If this is owned discovery response but owner is not me then discard it.
523 if( (pDInfo->isOwnedDiscovery) &&
524 (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
526 OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
527 DeleteDoxmBinData(ptrDoxm);
528 return OC_STACK_KEEP_TRANSACTION;
531 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
532 clientResponse->devAddr.port,
533 clientResponse->devAddr.adapter,
534 clientResponse->connType, ptrDoxm);
535 if (OC_STACK_OK != res)
537 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
538 DeleteDoxmBinData(ptrDoxm);
539 return OC_STACK_KEEP_TRANSACTION;
541 char rsrc_uri[MAX_URI_LENGTH+1] = {0};
542 int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
543 OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
544 if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
546 OC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
547 return OC_STACK_ERROR;
549 //Try to the unicast discovery to getting secure port
550 char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
551 if(!PMGenerateQuery(false,
552 clientResponse->devAddr.addr, clientResponse->devAddr.port,
553 clientResponse->connType,
554 query, sizeof(query), rsrc_uri))
556 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
557 return OC_STACK_KEEP_TRANSACTION;
559 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
561 OCCallbackData cbData;
562 cbData.cb = &SecurePortDiscoveryHandler;
563 cbData.context = ctx;
565 OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
566 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
567 // TODO: Should we use the default secure port in case of error?
568 if(OC_STACK_OK != ret)
570 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
571 return OC_STACK_KEEP_TRANSACTION;
575 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
577 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
580 return OC_STACK_KEEP_TRANSACTION;
585 OC_LOG(INFO, TAG, "Skiping Null response");
586 return OC_STACK_KEEP_TRANSACTION;
589 return OC_STACK_DELETE_TRANSACTION;
593 * Discover owned/unowned devices in the same IP subnet. .
595 * @param[in] waittime Timeout in seconds.
596 * @param[in] isOwned bool flag for owned / unowned discovery
597 * @param[in] ppDevicesList List of OCProvisionDev_t.
599 * @return OC_STACK_OK on success otherwise error.
601 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
603 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
605 if (NULL != *ppDevicesList)
607 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
608 return OC_STACK_INVALID_PARAM;
611 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
612 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
614 DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
617 OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
618 return OC_STACK_NO_MEMORY;
621 pDInfo->ppDevicesList = ppDevicesList;
622 pDInfo->isOwnedDiscovery = isOwned;
624 OCCallbackData cbData;
625 cbData.cb = &DeviceDiscoveryHandler;
626 cbData.context = (void *)pDInfo;
628 OCStackResult res = OC_STACK_ERROR;
630 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
631 DOXM_OWNED_FALSE_MULTICAST_QUERY;
633 OCDoHandle handle = NULL;
634 res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
635 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
636 if (res != OC_STACK_OK)
638 OC_LOG(ERROR, TAG, "OCStack resource error");
643 //Waiting for each response.
644 res = PMTimeout(waittime, true);
645 if(OC_STACK_OK != res)
647 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
649 OCStackResult resCancel = OCCancel(handle, OC_LOW_QOS, NULL, 0);
650 if(OC_STACK_OK != resCancel)
652 OC_LOG(ERROR, TAG, "Failed to remove registered callback");
656 res = OCCancel(handle,OC_LOW_QOS,NULL,0);
657 if (OC_STACK_OK != res)
659 OC_LOG(ERROR, TAG, "Failed to remove registered callback");
663 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
669 * Function to print OCProvisionDev_t for debug purpose.
671 * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OC_LOG_XX
674 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
678 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
679 OC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
680 OC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
681 OC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
682 OC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
686 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
690 bool PMDeleteFromUUIDList(OCUuidList_t *pUuidList, OicUuid_t *targetId)
692 if(pUuidList == NULL || targetId == NULL)
696 OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
697 LL_FOREACH_SAFE(pUuidList, tmp1, tmp2)
699 if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
701 LL_DELETE(pUuidList, tmp1);