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")
48 * Function to search node in linked list that matches given IP and port.
50 * @param[in] pList List of OCProvisionDev_t.
51 * @param[in] addr address of target device.
52 * @param[in] port port of remote server.
54 * @return pointer of OCProvisionDev_t if exist, otherwise NULL
56 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
58 if(NULL == addr || NULL == *ppDevicesList)
60 OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
64 OCProvisionDev_t *ptr = NULL;
65 LL_FOREACH(*ppDevicesList, ptr)
67 if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
78 * Add device information to list.
80 * @param[in] pList List of OCProvisionDev_t.
81 * @param[in] addr address of target device.
82 * @param[in] port port of remote server.
83 * @param[in] adapter adapter type of endpoint.
84 * @param[in] doxm pointer to doxm instance.
85 * @param[in] connType connectivity type of endpoint
87 * @return OC_STACK_OK for success and errorcode otherwise.
89 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
90 OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
94 return OC_STACK_INVALID_PARAM;
97 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
100 ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
103 OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
104 return OC_STACK_NO_MEMORY;
107 OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
108 ptr->endpoint.port = port;
110 ptr->securePort = DEFAULT_SECURE_PORT;
111 ptr->endpoint.adapter = adapter;
113 ptr->connType = connType;
115 LL_PREPEND(*ppDevicesList, ptr);
122 * Function to set secure port information from the given list of devices.
124 * @param[in] pList List of OCProvisionDev_t.
125 * @param[in] addr address of target device.
126 * @param[in] port port of remote server.
127 * @param[in] secureport secure port information.
129 * @return OC_STACK_OK for success and errorcode otherwise.
131 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr, uint16_t port,
134 OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
138 OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
139 return OC_STACK_ERROR;
142 ptr->securePort = securePort;
148 * This function deletes list of provision target devices
150 * @param[in] pList List of OCProvisionDev_t.
152 void DeleteDeviceList(OCProvisionDev_t **ppDevicesList)
156 OCProvisionDev_t *del = NULL, *tmp = NULL;
157 LL_FOREACH_SAFE(*ppDevicesList, del, tmp)
159 LL_DELETE(*ppDevicesList, del);
161 DeleteDoxmBinData(del->doxm);
162 DeletePstatBinData(del->pstat);
169 * Timeout implementation for secure discovery. When performing secure discovery,
170 * we should wait a certain period of time for getting response of each devices.
172 * @param[in] waittime Timeout in seconds.
173 * @return OC_STACK_OK on success otherwise error.
175 OCStackResult PMTimeout(unsigned short waittime)
177 struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
178 struct timespec currTime = {.tv_sec=0, .tv_nsec=0};
180 OCStackResult res = OC_STACK_OK;
181 #ifdef _POSIX_MONOTONIC_CLOCK
182 int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
184 int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
188 return OC_STACK_ERROR;
190 while (OC_STACK_OK == res)
192 #ifdef _POSIX_MONOTONIC_CLOCK
193 clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
195 clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
199 return OC_STACK_TIMEOUT;
201 long elapsed = (currTime.tv_sec - startTime.tv_sec);
202 if (elapsed > waittime)
213 * Extract secure port information from payload of discovery response.
215 * @param[in] jsonStr response payload of /oic/res discovery.
217 * @return Secure port
219 uint16_t GetSecurePortFromJSON(char* jsonStr)
221 // TODO: Modify error handling
226 cJSON *jsonProp = NULL;
228 cJSON *jsonPort = NULL;
230 cJSON *jsonRoot = cJSON_Parse(jsonStr);
233 // TODO: Add error log & return default secure port
237 jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
240 // TODO: Add error log & return default secure port
244 jsonP = cJSON_GetObjectItem(jsonProp, "p");
247 // TODO: Add error log & return default secure port
251 jsonPort = cJSON_GetObjectItem(jsonP, "port");
254 // TODO: Add error log & return default secure port
258 return (uint16_t)jsonPort->valueint;
261 bool PMGenerateQuery(bool isSecure,
262 const char* address, const uint16_t port,
263 const OCConnectivityType connType,
264 char* buffer, size_t bufferSize, const char* uri)
266 if(!address || !buffer || !uri)
268 OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
273 char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
275 switch(connType & CT_MASK_ADAPTER)
278 switch(connType & CT_MASK_FLAGS)
281 snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
282 prefix, address, port, uri);
285 snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
286 prefix, address, port, uri);
289 OC_LOG(ERROR, ERROR, "Unknown address format.");
292 if(snRet >= bufferSize)
294 OC_LOG(ERROR, INFO, "PMGenerateQuery : URI is too long");
298 // TODO: We need to verify tinyDTLS in below cases
299 case CT_ADAPTER_GATT_BTLE:
300 case CT_ADAPTER_RFCOMM_BTEDR:
301 OC_LOG(ERROR, ERROR, "Not supported connectivity adapter.");
305 OC_LOG(ERROR, ERROR, "Unknown connectivity adapter.");
313 * Callback handler for getting secure port information using /oic/res discovery.
315 * @param[in] ctx user context
316 * @param[in] handle Handle for response
317 * @param[in] clientResponse Response information(It will contain payload)
319 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
320 * OC_STACK_DELETE_TRANSACTION to delete it.
322 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
323 OCClientResponse *clientResponse)
327 OC_LOG(ERROR, TAG, "Lost List of device information");
328 return OC_STACK_KEEP_TRANSACTION;
333 if (NULL == clientResponse->payload)
335 OC_LOG(INFO, TAG, "Skiping Null payload");
339 if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
341 OC_LOG(INFO, TAG, "Wrong payload type");
342 return OC_STACK_KEEP_TRANSACTION;
345 uint16_t securePort = 0;
346 OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
348 if (resPayload && resPayload->secure)
350 securePort = resPayload->port;
354 OC_LOG(INFO, TAG, "Can not find secure port information.");
355 return OC_STACK_KEEP_TRANSACTION;
358 OCProvisionDev_t** ppDevicesList = (OCProvisionDev_t**) ctx;
360 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
361 clientResponse->devAddr.port, securePort);
362 if (OC_STACK_OK != res)
364 OC_LOG(ERROR, TAG, "Error while getting secure port.");
365 return OC_STACK_KEEP_TRANSACTION;
367 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
370 return OC_STACK_KEEP_TRANSACTION;
374 OC_LOG(INFO, TAG, "Skiping Null response");
376 return OC_STACK_DELETE_TRANSACTION;
380 * Callback handler for PMDeviceDiscovery API.
382 * @param[in] ctx User context
383 * @param[in] handle Handler for response
384 * @param[in] clientResponse Response information (It will contain payload)
385 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
386 * OC_STACK_DELETE_TRANSACTION to delete it.
388 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
389 OCClientResponse *clientResponse)
393 OC_LOG(ERROR, TAG, "Lost List of device information");
394 return OC_STACK_KEEP_TRANSACTION;
399 if (NULL == clientResponse->payload)
401 OC_LOG(INFO, TAG, "Skiping Null payload");
402 return OC_STACK_KEEP_TRANSACTION;
404 if (OC_STACK_OK != clientResponse->result)
406 OC_LOG(INFO, TAG, "Error in response");
407 return OC_STACK_KEEP_TRANSACTION;
411 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
413 OC_LOG(INFO, TAG, "Unknown payload type");
414 return OC_STACK_KEEP_TRANSACTION;
416 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
417 ((OCSecurityPayload*)clientResponse->payload)->securityData);
420 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
421 return OC_STACK_KEEP_TRANSACTION;
425 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
427 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
429 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
430 clientResponse->devAddr.port,
431 clientResponse->devAddr.adapter,
432 clientResponse->connType, ptrDoxm);
433 if (OC_STACK_OK != res)
435 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
436 DeleteDoxmBinData(ptrDoxm);
437 return OC_STACK_KEEP_TRANSACTION;
440 //Try to the unicast discovery to getting secure port
441 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
442 if(!PMGenerateQuery(false,
443 clientResponse->devAddr.addr, clientResponse->devAddr.port,
444 clientResponse->connType,
445 query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
447 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
448 return OC_STACK_ERROR;
450 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
452 OCCallbackData cbData;
453 cbData.cb = &SecurePortDiscoveryHandler;
454 cbData.context = ctx;
456 OCStackResult ret = OCDoResource(NULL, OC_REST_GET, query, 0, 0,
457 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
458 // TODO: Should we use the default secure port in case of error?
459 if(OC_STACK_OK != ret)
461 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
462 return OC_STACK_DELETE_TRANSACTION;
466 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
468 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
471 return OC_STACK_KEEP_TRANSACTION;
476 OC_LOG(INFO, TAG, "Skiping Null response");
477 return OC_STACK_KEEP_TRANSACTION;
480 return OC_STACK_DELETE_TRANSACTION;
484 * Discover owned/unowned devices in the same IP subnet. .
486 * @param[in] waittime Timeout in seconds.
487 * @param[in] isOwned bool flag for owned / unowned discovery
488 * @param[in] ppDevicesList List of OCProvisionDev_t.
490 * @return OC_STACK_OK on success otherwise error.
492 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
494 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
496 if (NULL != *ppDevicesList)
498 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
499 return OC_STACK_INVALID_PARAM;
502 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
503 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
505 OCCallbackData cbData;
506 cbData.cb = &DeviceDiscoveryHandler;
507 cbData.context = (void *)ppDevicesList;
509 OCStackResult res = OC_STACK_ERROR;
511 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
512 DOXM_OWNED_FALSE_MULTICAST_QUERY;
514 res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
515 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
516 if (res != OC_STACK_OK)
518 OC_LOG(ERROR, TAG, "OCStack resource error");
522 //Waiting for each response.
523 res = PMTimeout(waittime);
524 if(OC_STACK_OK != res)
526 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
530 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");