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;
359 OC_LOG_V(INFO, TAG, "UpdateSecurePortOfDevice with %d", securePort);
361 OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
362 clientResponse->devAddr.port, securePort);
363 if (OC_STACK_OK != res)
365 OC_LOG(ERROR, TAG, "Error while getting secure port.");
366 return OC_STACK_KEEP_TRANSACTION;
368 OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
371 return OC_STACK_KEEP_TRANSACTION;
375 OC_LOG(INFO, TAG, "Skiping Null response");
377 return OC_STACK_DELETE_TRANSACTION;
381 * Callback handler for PMDeviceDiscovery API.
383 * @param[in] ctx User context
384 * @param[in] handle Handler for response
385 * @param[in] clientResponse Response information (It will contain payload)
386 * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
387 * OC_STACK_DELETE_TRANSACTION to delete it.
389 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
390 OCClientResponse *clientResponse)
394 OC_LOG(ERROR, TAG, "Lost List of device information");
395 return OC_STACK_KEEP_TRANSACTION;
400 if (NULL == clientResponse->payload)
402 OC_LOG(INFO, TAG, "Skiping Null payload");
403 return OC_STACK_KEEP_TRANSACTION;
405 if (OC_STACK_OK != clientResponse->result)
407 OC_LOG(INFO, TAG, "Error in response");
408 return OC_STACK_KEEP_TRANSACTION;
412 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
414 OC_LOG(INFO, TAG, "Unknown payload type");
415 return OC_STACK_KEEP_TRANSACTION;
417 OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
418 ((OCSecurityPayload*)clientResponse->payload)->securityData);
421 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
422 return OC_STACK_KEEP_TRANSACTION;
426 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
428 OCProvisionDev_t **ppDevicesList = (OCProvisionDev_t**) ctx;
430 OCStackResult res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
431 clientResponse->devAddr.port,
432 clientResponse->devAddr.adapter,
433 clientResponse->connType, ptrDoxm);
434 if (OC_STACK_OK != res)
436 OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
437 DeleteDoxmBinData(ptrDoxm);
438 return OC_STACK_KEEP_TRANSACTION;
441 //Try to the unicast discovery to getting secure port
442 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0, };
443 if(!PMGenerateQuery(false,
444 clientResponse->devAddr.addr, clientResponse->devAddr.port,
445 clientResponse->connType,
446 query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
448 OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
449 return OC_STACK_ERROR;
451 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
453 OCCallbackData cbData;
454 cbData.cb = &SecurePortDiscoveryHandler;
455 cbData.context = ctx;
457 OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
458 clientResponse->connType, OC_LOW_QOS, &cbData, NULL, 0);
459 // TODO: Should we use the default secure port in case of error?
460 if(OC_STACK_OK != ret)
462 OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
463 return OC_STACK_DELETE_TRANSACTION;
467 OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
469 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
472 return OC_STACK_KEEP_TRANSACTION;
477 OC_LOG(INFO, TAG, "Skiping Null response");
478 return OC_STACK_KEEP_TRANSACTION;
481 return OC_STACK_DELETE_TRANSACTION;
485 * Discover owned/unowned devices in the same IP subnet. .
487 * @param[in] waittime Timeout in seconds.
488 * @param[in] isOwned bool flag for owned / unowned discovery
489 * @param[in] ppDevicesList List of OCProvisionDev_t.
491 * @return OC_STACK_OK on success otherwise error.
493 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
495 OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
497 if (NULL != *ppDevicesList)
499 OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
500 return OC_STACK_INVALID_PARAM;
503 const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
504 const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
506 OCCallbackData cbData;
507 cbData.cb = &DeviceDiscoveryHandler;
508 cbData.context = (void *)ppDevicesList;
510 OCStackResult res = OC_STACK_ERROR;
512 const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
513 DOXM_OWNED_FALSE_MULTICAST_QUERY;
515 res = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
516 CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
517 if (res != OC_STACK_OK)
519 OC_LOG(ERROR, TAG, "OCStack resource error");
523 //Waiting for each response.
524 res = PMTimeout(waittime);
525 if(OC_STACK_OK != res)
527 OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
531 OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");