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 #define TAG ("PM-UTILITY")
47 typedef struct _DiscoveryInfo{
48 OCProvisionDev_t **ppDevicesList;
49 bool isOwnedDiscovery;
53 * Function to search node in linked list that matches given IP and port.
55 * @param[in] pList List of OCProvisionDev_t.
56 * @param[in] addr address of target device.
57 * @param[in] port port of remote server.
59 * @return pointer of OCProvisionDev_t if exist, otherwise NULL
61 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
63 if(NULL == addr || NULL == *ppDevicesList)
65 OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
69 OCProvisionDev_t *ptr = NULL;
70 LL_FOREACH(*ppDevicesList, ptr)
72 if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
83 * Add device information to list.
85 * @param[in] pList List of OCProvisionDev_t.
86 * @param[in] addr address of target device.
87 * @param[in] port port of remote server.
88 * @param[in] adapter adapter type of endpoint.
89 * @param[in] doxm pointer to doxm instance.
90 * @param[in] connType connectivity type of endpoint
92 * @return OC_STACK_OK for success and errorcode otherwise.
94 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
95 OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
99 return OC_STACK_INVALID_PARAM;
102 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
105 ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
108 OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
109 return OC_STACK_NO_MEMORY;
112 OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
113 ptr->endpoint.port = port;
115 ptr->securePort = DEFAULT_SECURE_PORT;
116 ptr->endpoint.adapter = adapter;
118 ptr->connType = connType;
120 LL_PREPEND(*ppDevicesList, ptr);
127 * Function to set secure port information from the given list of devices.
129 * @param[in] pList List of OCProvisionDev_t.
130 * @param[in] addr address of target device.
131 * @param[in] port port of remote server.
132 * @param[in] secureport secure port information.
134 * @return OC_STACK_OK for success and errorcode otherwise.
136 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
137 uint16_t port, uint16_t securePort)
139 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
143 OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
144 return OC_STACK_ERROR;
147 ptr->securePort = securePort;
153 * This function deletes list of provision target devices
155 * @param[in] pDevicesList List of OCProvisionDev_t.
157 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
161 OCProvisionDev_t *del = NULL, *tmp = NULL;
162 LL_FOREACH_SAFE(pDevicesList, del, tmp)
164 LL_DELETE(pDevicesList, del);
166 DeleteDoxmBinData(del->doxm);
167 DeletePstatBinData(del->pstat);
174 * Timeout implementation for secure discovery. When performing secure discovery,
175 * we should wait a certain period of time for getting response of each devices.
177 * @param[in] waittime Timeout in seconds.
178 * @return OC_STACK_OK on success otherwise error.
180 OCStackResult PMTimeout(unsigned short waittime)
182 struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
183 struct timespec currTime = {.tv_sec=0, .tv_nsec=0};
185 OCStackResult res = OC_STACK_OK;
186 #ifdef _POSIX_MONOTONIC_CLOCK
187 int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
189 int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
193 return OC_STACK_ERROR;
195 while (OC_STACK_OK == res)
197 #ifdef _POSIX_MONOTONIC_CLOCK
198 clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
200 clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
204 return OC_STACK_TIMEOUT;
206 long elapsed = (currTime.tv_sec - startTime.tv_sec);
207 if (elapsed > waittime)
218 * Extract secure port information from payload of discovery response.
220 * @param[in] jsonStr response payload of /oic/res discovery.
222 * @return Secure port
224 uint16_t GetSecurePortFromJSON(char* jsonStr)
226 // TODO: Modify error handling
231 cJSON *jsonProp = NULL;
233 cJSON *jsonPort = NULL;
235 cJSON *jsonRoot = cJSON_Parse(jsonStr);
238 // TODO: Add error log & return default secure port
242 jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
245 // TODO: Add error log & return default secure port
249 jsonP = cJSON_GetObjectItem(jsonProp, "p");
252 // TODO: Add error log & return default secure port
256 jsonPort = cJSON_GetObjectItem(jsonP, "port");
259 // TODO: Add error log & return default secure port
263 return (uint16_t)jsonPort->valueint;
266 bool PMGenerateQuery(bool isSecure,
267 const char* address, const uint16_t port,
268 const OCConnectivityType connType,
269 char* buffer, size_t bufferSize, const char* uri)
271 if(!address || !buffer || !uri)
273 OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
278 char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
280 switch(connType & CT_MASK_ADAPTER)
283 switch(connType & CT_MASK_FLAGS)
286 snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
287 prefix, address, port, uri);
290 snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
291 prefix, address, port, uri);
294 OC_LOG(ERROR, TAG, "Unknown address format.");
297 if(snRet >= bufferSize)
299 OC_LOG(ERROR, TAG, "PMGenerateQuery : URI is too long");
303 // TODO: We need to verify tinyDTLS in below cases
304 case CT_ADAPTER_GATT_BTLE:
305 case CT_ADAPTER_RFCOMM_BTEDR:
306 OC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
310 OC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
318 * Callback handler for getting secure port information using /oic/res discovery.
320 * @param[in] ctx user context
321 * @param[in] handle Handle for response
322 * @param[in] clientResponse Response information(It will contain payload)
324 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
325 * OC_STACK_DELETE_TRANSACTION to delete it.
327 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
328 OCClientResponse *clientResponse)
332 OC_LOG(ERROR, TAG, "Lost List of device information");
333 return OC_STACK_KEEP_TRANSACTION;
338 if (NULL == clientResponse->payload)
340 OC_LOG(INFO, TAG, "Skiping Null payload");
344 if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
346 OC_LOG(INFO, TAG, "Wrong payload type");
347 return OC_STACK_KEEP_TRANSACTION;
350 uint16_t securePort = 0;
351 OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
353 if (resPayload && resPayload->secure)
355 securePort = resPayload->port;
359 OC_LOG(INFO, TAG, "Can not find secure port information.");
360 return OC_STACK_KEEP_TRANSACTION;
363 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
364 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
366 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
367 clientResponse->devAddr.port, securePort);
368 if (OC_STACK_OK != res)
370 OC_LOG(ERROR, TAG, "Error while getting secure port.");
371 return OC_STACK_KEEP_TRANSACTION;
373 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
376 return OC_STACK_KEEP_TRANSACTION;
380 OC_LOG(INFO, TAG, "Skiping Null response");
382 return OC_STACK_DELETE_TRANSACTION;
386 * Callback handler for PMDeviceDiscovery API.
388 * @param[in] ctx User context
389 * @param[in] handle Handler for response
390 * @param[in] clientResponse Response information (It will contain payload)
391 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
392 * OC_STACK_DELETE_TRANSACTION to delete it.
394 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
395 OCClientResponse *clientResponse)
399 OC_LOG(ERROR, TAG, "Lost List of device information");
400 return OC_STACK_KEEP_TRANSACTION;
405 if (NULL == clientResponse->payload)
407 OC_LOG(INFO, TAG, "Skiping Null payload");
408 return OC_STACK_KEEP_TRANSACTION;
410 if (OC_STACK_OK != clientResponse->result)
412 OC_LOG(INFO, TAG, "Error in response");
413 return OC_STACK_KEEP_TRANSACTION;
417 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
419 OC_LOG(INFO, TAG, "Unknown payload type");
420 return OC_STACK_KEEP_TRANSACTION;
422 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
423 ((OCSecurityPayload*)clientResponse->payload)->securityData);
426 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
427 return OC_STACK_KEEP_TRANSACTION;
431 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
433 //If this is owend device discovery we have to filter out the responses.
434 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
435 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
437 // Get my device ID from doxm resource
439 memset(&myId, 0, sizeof(myId));
440 OCStackResult res = GetDoxmDevOwnerId(&myId);
441 if(OC_STACK_OK != res)
443 OC_LOG(ERROR, TAG, "Error while getting my device ID.");
444 DeleteDoxmBinData(ptrDoxm);
445 return OC_STACK_KEEP_TRANSACTION;
448 // If this is owned discovery response but owner is not me then discard it.
449 if( (pDInfo->isOwnedDiscovery) &&
450 (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
452 OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
453 DeleteDoxmBinData(ptrDoxm);
454 return OC_STACK_KEEP_TRANSACTION;
457 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
458 clientResponse->devAddr.port,
459 clientResponse->devAddr.adapter,
460 clientResponse->connType, ptrDoxm);
461 if (OC_STACK_OK != res)
463 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
464 DeleteDoxmBinData(ptrDoxm);
465 return OC_STACK_KEEP_TRANSACTION;
468 //Try to the unicast discovery to getting secure port
469 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
470 if(!PMGenerateQuery(false,
471 clientResponse->devAddr.addr, clientResponse->devAddr.port,
472 clientResponse->connType,
473 query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
475 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
476 return OC_STACK_KEEP_TRANSACTION;
478 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
480 OCCallbackData cbData;
481 cbData.cb = &SecurePortDiscoveryHandler;
482 cbData.context = ctx;
484 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
485 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
486 // TODO: Should we use the default secure port in case of error?
487 if(OC_STACK_OK != ret)
489 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
490 return OC_STACK_KEEP_TRANSACTION;
494 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
496 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
499 return OC_STACK_KEEP_TRANSACTION;
504 OC_LOG(INFO, TAG, "Skiping Null response");
505 return OC_STACK_KEEP_TRANSACTION;
508 return OC_STACK_DELETE_TRANSACTION;
512 * Discover owned/unowned devices in the same IP subnet. .
514 * @param[in] waittime Timeout in seconds.
515 * @param[in] isOwned bool flag for owned / unowned discovery
516 * @param[in] ppDevicesList List of OCProvisionDev_t.
518 * @return OC_STACK_OK on success otherwise error.
520 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
522 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
524 if (NULL != *ppDevicesList)
526 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
527 return OC_STACK_INVALID_PARAM;
530 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
531 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
533 DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
536 OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
537 return OC_STACK_NO_MEMORY;
540 pDInfo->ppDevicesList = ppDevicesList;
541 pDInfo->isOwnedDiscovery = isOwned;
543 OCCallbackData cbData;
544 cbData.cb = &DeviceDiscoveryHandler;
545 cbData.context = (void *)pDInfo;
547 OCStackResult res = OC_STACK_ERROR;
549 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
550 DOXM_OWNED_FALSE_MULTICAST_QUERY;
552 res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
553 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
554 if (res != OC_STACK_OK)
556 OC_LOG(ERROR, TAG, "OCStack resource error");
560 //Waiting for each response.
561 res = PMTimeout(waittime);
562 if(OC_STACK_OK != res)
564 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
568 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");