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"
37 #include "securevirtualresourcetypes.h"
38 #include "srmresourcestrings.h" //@note: SRM's internal header
39 #include "doxmresource.h" //@note: SRM's internal header
40 #include "pstatresource.h" //@note: SRM's internal header
43 #include "pmutility.h"
45 #include "srmutility.h"
47 #define TAG ("PM-UTILITY")
49 typedef struct _DiscoveryInfo{
50 OCProvisionDev_t **ppDevicesList;
51 bool isOwnedDiscovery;
55 * Function to search node in linked list that matches given IP and port.
57 * @param[in] pList List of OCProvisionDev_t.
58 * @param[in] addr address of target device.
59 * @param[in] port port of remote server.
61 * @return pointer of OCProvisionDev_t if exist, otherwise NULL
63 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
65 if(NULL == addr || NULL == *ppDevicesList)
67 OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
71 OCProvisionDev_t *ptr = NULL;
72 LL_FOREACH(*ppDevicesList, ptr)
74 if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
85 * Add device information to list.
87 * @param[in] pList List of OCProvisionDev_t.
88 * @param[in] addr address of target device.
89 * @param[in] port port of remote server.
90 * @param[in] adapter adapter type of endpoint.
91 * @param[in] doxm pointer to doxm instance.
92 * @param[in] connType connectivity type of endpoint
94 * @return OC_STACK_OK for success and errorcode otherwise.
96 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
97 OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
101 return OC_STACK_INVALID_PARAM;
104 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
107 ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
110 OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
111 return OC_STACK_NO_MEMORY;
114 OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
115 ptr->endpoint.port = port;
117 ptr->securePort = DEFAULT_SECURE_PORT;
118 ptr->endpoint.adapter = adapter;
120 ptr->connType = connType;
122 LL_PREPEND(*ppDevicesList, ptr);
129 * Function to set secure port information from the given list of devices.
131 * @param[in] pList List of OCProvisionDev_t.
132 * @param[in] addr address of target device.
133 * @param[in] port port of remote server.
134 * @param[in] secureport secure port information.
136 * @return OC_STACK_OK for success and errorcode otherwise.
138 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
139 uint16_t port, uint16_t securePort)
141 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
145 OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
146 return OC_STACK_ERROR;
149 ptr->securePort = securePort;
155 * This function deletes list of provision target devices
157 * @param[in] pDevicesList List of OCProvisionDev_t.
159 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
163 OCProvisionDev_t *del = NULL, *tmp = NULL;
164 LL_FOREACH_SAFE(pDevicesList, del, tmp)
166 LL_DELETE(pDevicesList, del);
168 DeleteDoxmBinData(del->doxm);
169 DeletePstatBinData(del->pstat);
175 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
177 OC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
181 OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
185 // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
186 OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
187 VERIFY_NON_NULL(TAG, newDev, ERROR);
189 memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
193 newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
194 VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
196 memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
197 // We have to assign NULL for not necessary information to prevent memory corruption.
198 newDev->pstat->sm = NULL;
203 newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
204 VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
206 memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
207 // We have to assign NULL for not necessary information to prevent memory corruption.
208 newDev->doxm->oxmType = NULL;
209 newDev->doxm->oxm = NULL;
212 newDev->securePort = src->securePort;
213 //TODO: Below comment line should be activated after 2333 change is merged
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)
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 if(snRet >= bufferSize)
362 OC_LOG(ERROR, TAG, "PMGenerateQuery : URI is too long");
366 // TODO: We need to verify tinyDTLS in below cases
367 case CT_ADAPTER_GATT_BTLE:
368 case CT_ADAPTER_RFCOMM_BTEDR:
369 OC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
373 OC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
381 * Callback handler for getting secure port information using /oic/res discovery.
383 * @param[in] ctx user context
384 * @param[in] handle Handle for response
385 * @param[in] clientResponse Response information(It will contain payload)
387 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
388 * OC_STACK_DELETE_TRANSACTION to delete it.
390 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
391 OCClientResponse *clientResponse)
395 OC_LOG(ERROR, TAG, "Lost List of device information");
396 return OC_STACK_KEEP_TRANSACTION;
401 if (NULL == clientResponse->payload)
403 OC_LOG(INFO, TAG, "Skiping Null payload");
407 if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
409 OC_LOG(INFO, TAG, "Wrong payload type");
410 return OC_STACK_KEEP_TRANSACTION;
413 uint16_t securePort = 0;
414 OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
416 if (resPayload && resPayload->secure)
418 securePort = resPayload->port;
422 OC_LOG(INFO, TAG, "Can not find secure port information.");
423 return OC_STACK_KEEP_TRANSACTION;
426 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
427 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
429 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
430 clientResponse->devAddr.port, securePort);
431 if (OC_STACK_OK != res)
433 OC_LOG(ERROR, TAG, "Error while getting secure port.");
434 return OC_STACK_KEEP_TRANSACTION;
436 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
439 return OC_STACK_KEEP_TRANSACTION;
443 OC_LOG(INFO, TAG, "Skiping Null response");
445 return OC_STACK_DELETE_TRANSACTION;
449 * Callback handler for PMDeviceDiscovery API.
451 * @param[in] ctx User context
452 * @param[in] handle Handler for response
453 * @param[in] clientResponse Response information (It will contain payload)
454 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
455 * OC_STACK_DELETE_TRANSACTION to delete it.
457 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
458 OCClientResponse *clientResponse)
462 OC_LOG(ERROR, TAG, "Lost List of device information");
463 return OC_STACK_KEEP_TRANSACTION;
468 if (NULL == clientResponse->payload)
470 OC_LOG(INFO, TAG, "Skiping Null payload");
471 return OC_STACK_KEEP_TRANSACTION;
473 if (OC_STACK_OK != clientResponse->result)
475 OC_LOG(INFO, TAG, "Error in response");
476 return OC_STACK_KEEP_TRANSACTION;
480 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
482 OC_LOG(INFO, TAG, "Unknown payload type");
483 return OC_STACK_KEEP_TRANSACTION;
485 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
486 ((OCSecurityPayload*)clientResponse->payload)->securityData);
489 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
490 return OC_STACK_KEEP_TRANSACTION;
494 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
496 //If this is owend device discovery we have to filter out the responses.
497 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
498 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
500 // Get my device ID from doxm resource
502 memset(&myId, 0, sizeof(myId));
503 OCStackResult res = GetDoxmDevOwnerId(&myId);
504 if(OC_STACK_OK != res)
506 OC_LOG(ERROR, TAG, "Error while getting my device ID.");
507 DeleteDoxmBinData(ptrDoxm);
508 return OC_STACK_KEEP_TRANSACTION;
511 // If this is owned discovery response but owner is not me then discard it.
512 if( (pDInfo->isOwnedDiscovery) &&
513 (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
515 OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
516 DeleteDoxmBinData(ptrDoxm);
517 return OC_STACK_KEEP_TRANSACTION;
520 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
521 clientResponse->devAddr.port,
522 clientResponse->devAddr.adapter,
523 clientResponse->connType, ptrDoxm);
524 if (OC_STACK_OK != res)
526 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
527 DeleteDoxmBinData(ptrDoxm);
528 return OC_STACK_KEEP_TRANSACTION;
531 //Try to the unicast discovery to getting secure port
532 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
533 if(!PMGenerateQuery(false,
534 clientResponse->devAddr.addr, clientResponse->devAddr.port,
535 clientResponse->connType,
536 query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
538 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
539 return OC_STACK_KEEP_TRANSACTION;
541 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
543 OCCallbackData cbData;
544 cbData.cb = &SecurePortDiscoveryHandler;
545 cbData.context = ctx;
547 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
548 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
549 // TODO: Should we use the default secure port in case of error?
550 if(OC_STACK_OK != ret)
552 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
553 return OC_STACK_KEEP_TRANSACTION;
557 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
559 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
562 return OC_STACK_KEEP_TRANSACTION;
567 OC_LOG(INFO, TAG, "Skiping Null response");
568 return OC_STACK_KEEP_TRANSACTION;
571 return OC_STACK_DELETE_TRANSACTION;
575 * Discover owned/unowned devices in the same IP subnet. .
577 * @param[in] waittime Timeout in seconds.
578 * @param[in] isOwned bool flag for owned / unowned discovery
579 * @param[in] ppDevicesList List of OCProvisionDev_t.
581 * @return OC_STACK_OK on success otherwise error.
583 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
585 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
587 if (NULL != *ppDevicesList)
589 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
590 return OC_STACK_INVALID_PARAM;
593 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
594 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
596 DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
599 OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
600 return OC_STACK_NO_MEMORY;
603 pDInfo->ppDevicesList = ppDevicesList;
604 pDInfo->isOwnedDiscovery = isOwned;
606 OCCallbackData cbData;
607 cbData.cb = &DeviceDiscoveryHandler;
608 cbData.context = (void *)pDInfo;
610 OCStackResult res = OC_STACK_ERROR;
612 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
613 DOXM_OWNED_FALSE_MULTICAST_QUERY;
615 res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
616 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
617 if (res != OC_STACK_OK)
619 OC_LOG(ERROR, TAG, "OCStack resource error");
623 //Waiting for each response.
624 res = PMTimeout(waittime, true);
625 if(OC_STACK_OK != res)
627 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
631 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
639 * Function to print OCProvisionDev_t for debug purpose.
641 * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OC_LOG_XX
644 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
648 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
649 OC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
650 OC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
651 OC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
652 OC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
656 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
660 bool PMDeleteFromUUIDList(OCUuidList_t *pUuidList, OicUuid_t *targetId)
662 if(pUuidList == NULL || targetId == NULL)
666 OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
667 LL_FOREACH_SAFE(pUuidList, tmp1, tmp2)
669 if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
671 LL_DELETE(pUuidList, tmp1);