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;
121 ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
123 LL_PREPEND(*ppDevicesList, ptr);
130 * Function to set secure port information from the given list of devices.
132 * @param[in] pList List of OCProvisionDev_t.
133 * @param[in] addr address of target device.
134 * @param[in] port port of remote server.
135 * @param[in] secureport secure port information.
137 * @return OC_STACK_OK for success and errorcode otherwise.
139 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
140 uint16_t port, uint16_t securePort)
142 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
146 OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
147 return OC_STACK_ERROR;
150 ptr->securePort = securePort;
156 * This function deletes list of provision target devices
158 * @param[in] pDevicesList List of OCProvisionDev_t.
160 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
164 OCProvisionDev_t *del = NULL, *tmp = NULL;
165 LL_FOREACH_SAFE(pDevicesList, del, tmp)
167 LL_DELETE(pDevicesList, del);
169 DeleteDoxmBinData(del->doxm);
170 DeletePstatBinData(del->pstat);
176 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
178 OC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
182 OC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
186 // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
187 OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
188 VERIFY_NON_NULL(TAG, newDev, ERROR);
190 memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
194 newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
195 VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
197 memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
198 // We have to assign NULL for not necessary information to prevent memory corruption.
199 newDev->pstat->sm = NULL;
204 newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
205 VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
207 memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
208 // We have to assign NULL for not necessary information to prevent memory corruption.
209 newDev->doxm->oxmType = NULL;
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)
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_KEEP_TRANSACTION;
408 if (NULL == clientResponse->payload)
410 OC_LOG(INFO, TAG, "Skiping Null payload");
414 if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
416 OC_LOG(INFO, TAG, "Wrong payload type");
417 return OC_STACK_KEEP_TRANSACTION;
420 uint16_t securePort = 0;
421 OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
423 if (resPayload && resPayload->secure)
425 securePort = resPayload->port;
429 OC_LOG(INFO, TAG, "Can not find secure port information.");
430 return OC_STACK_KEEP_TRANSACTION;
433 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
434 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
436 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
437 clientResponse->devAddr.port, securePort);
438 if (OC_STACK_OK != res)
440 OC_LOG(ERROR, TAG, "Error while getting secure port.");
441 return OC_STACK_KEEP_TRANSACTION;
443 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
446 return OC_STACK_KEEP_TRANSACTION;
450 OC_LOG(INFO, TAG, "Skiping Null response");
452 return OC_STACK_DELETE_TRANSACTION;
456 * Callback handler for PMDeviceDiscovery API.
458 * @param[in] ctx User context
459 * @param[in] handle Handler for response
460 * @param[in] clientResponse Response information (It will contain payload)
461 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
462 * OC_STACK_DELETE_TRANSACTION to delete it.
464 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
465 OCClientResponse *clientResponse)
469 OC_LOG(ERROR, TAG, "Lost List of device information");
470 return OC_STACK_KEEP_TRANSACTION;
475 if (NULL == clientResponse->payload)
477 OC_LOG(INFO, TAG, "Skiping Null payload");
478 return OC_STACK_KEEP_TRANSACTION;
480 if (OC_STACK_OK != clientResponse->result)
482 OC_LOG(INFO, TAG, "Error in response");
483 return OC_STACK_KEEP_TRANSACTION;
487 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
489 OC_LOG(INFO, TAG, "Unknown payload type");
490 return OC_STACK_KEEP_TRANSACTION;
492 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
493 ((OCSecurityPayload*)clientResponse->payload)->securityData);
496 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
497 return OC_STACK_KEEP_TRANSACTION;
501 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
503 //If this is owend device discovery we have to filter out the responses.
504 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
505 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
507 // Get my device ID from doxm resource
509 memset(&myId, 0, sizeof(myId));
510 OCStackResult res = GetDoxmDevOwnerId(&myId);
511 if(OC_STACK_OK != res)
513 OC_LOG(ERROR, TAG, "Error while getting my device ID.");
514 DeleteDoxmBinData(ptrDoxm);
515 return OC_STACK_KEEP_TRANSACTION;
518 // If this is owned discovery response but owner is not me then discard it.
519 if( (pDInfo->isOwnedDiscovery) &&
520 (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
522 OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
523 DeleteDoxmBinData(ptrDoxm);
524 return OC_STACK_KEEP_TRANSACTION;
527 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
528 clientResponse->devAddr.port,
529 clientResponse->devAddr.adapter,
530 clientResponse->connType, ptrDoxm);
531 if (OC_STACK_OK != res)
533 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
534 DeleteDoxmBinData(ptrDoxm);
535 return OC_STACK_KEEP_TRANSACTION;
538 //Try to the unicast discovery to getting secure port
539 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
540 if(!PMGenerateQuery(false,
541 clientResponse->devAddr.addr, clientResponse->devAddr.port,
542 clientResponse->connType,
543 query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
545 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
546 return OC_STACK_KEEP_TRANSACTION;
548 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
550 OCCallbackData cbData;
551 cbData.cb = &SecurePortDiscoveryHandler;
552 cbData.context = ctx;
554 OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
555 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
556 // TODO: Should we use the default secure port in case of error?
557 if(OC_STACK_OK != ret)
559 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
560 return OC_STACK_KEEP_TRANSACTION;
564 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
566 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
569 return OC_STACK_KEEP_TRANSACTION;
574 OC_LOG(INFO, TAG, "Skiping Null response");
575 return OC_STACK_KEEP_TRANSACTION;
578 return OC_STACK_DELETE_TRANSACTION;
582 * Discover owned/unowned devices in the same IP subnet. .
584 * @param[in] waittime Timeout in seconds.
585 * @param[in] isOwned bool flag for owned / unowned discovery
586 * @param[in] ppDevicesList List of OCProvisionDev_t.
588 * @return OC_STACK_OK on success otherwise error.
590 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
592 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
594 if (NULL != *ppDevicesList)
596 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
597 return OC_STACK_INVALID_PARAM;
600 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
601 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
603 DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
606 OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
607 return OC_STACK_NO_MEMORY;
610 pDInfo->ppDevicesList = ppDevicesList;
611 pDInfo->isOwnedDiscovery = isOwned;
613 OCCallbackData cbData;
614 cbData.cb = &DeviceDiscoveryHandler;
615 cbData.context = (void *)pDInfo;
617 OCStackResult res = OC_STACK_ERROR;
619 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
620 DOXM_OWNED_FALSE_MULTICAST_QUERY;
622 res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
623 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
624 if (res != OC_STACK_OK)
626 OC_LOG(ERROR, TAG, "OCStack resource error");
630 //Waiting for each response.
631 res = PMTimeout(waittime, true);
632 if(OC_STACK_OK != res)
634 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
638 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
646 * Function to print OCProvisionDev_t for debug purpose.
648 * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OC_LOG_XX
651 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
655 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
656 OC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
657 OC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
658 OC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
659 OC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
663 OC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
667 bool PMDeleteFromUUIDList(OCUuidList_t *pUuidList, OicUuid_t *targetId)
669 if(pUuidList == NULL || targetId == NULL)
673 OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
674 LL_FOREACH_SAFE(pUuidList, tmp1, tmp2)
676 if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
678 LL_DELETE(pUuidList, tmp1);