Add filter to Owned Device Discovery.
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / pmutility.c
1 /* *****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
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
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * *****************************************************************/
20 #ifndef _POSIX_C_SOURCE
21 #define _POSIX_C_SOURCE 200112L
22 #endif
23
24 #include <unistd.h>
25 #include <string.h>
26 #include <time.h>
27 #include <sys/time.h>
28
29 #include "ocstack.h"
30 #include "oic_malloc.h"
31 #include "oic_string.h"
32 #include "logger.h"
33 #include "cJSON.h"
34 #include "utlist.h"
35 #include "ocpayload.h"
36
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
41
42 #include "pmtypes.h"
43 #include "pmutility.h"
44
45 #define TAG ("PM-UTILITY")
46
47 typedef struct _DiscoveryInfo{
48     OCProvisionDev_t    **ppDevicesList;
49     bool                isOwnedDiscovery;
50 } DiscoveryInfo;
51
52 /**
53  * Function to search node in linked list that matches given IP and port.
54  *
55  * @param[in] pList         List of OCProvisionDev_t.
56  * @param[in] addr          address of target device.
57  * @param[in] port          port of remote server.
58  *
59  * @return pointer of OCProvisionDev_t if exist, otherwise NULL
60  */
61 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
62 {
63     if(NULL == addr || NULL == *ppDevicesList)
64     {
65         OC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
66         return NULL;
67     }
68
69     OCProvisionDev_t *ptr = NULL;
70     LL_FOREACH(*ppDevicesList, ptr)
71     {
72         if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
73         {
74             return ptr;
75         }
76     }
77
78     return NULL;
79 }
80
81
82 /**
83  * Add device information to list.
84  *
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
91  *
92  * @return OC_STACK_OK for success and errorcode otherwise.
93  */
94 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
95                         OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
96 {
97     if (NULL == addr)
98     {
99         return OC_STACK_INVALID_PARAM;
100     }
101
102     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
103     if(!ptr)
104     {
105         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
106         if (NULL == ptr)
107         {
108             OC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
109             return OC_STACK_NO_MEMORY;
110         }
111
112         OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
113         ptr->endpoint.port = port;
114         ptr->doxm = doxm;
115         ptr->securePort = DEFAULT_SECURE_PORT;
116         ptr->endpoint.adapter = adapter;
117         ptr->next = NULL;
118         ptr->connType = connType;
119
120         LL_PREPEND(*ppDevicesList, ptr);
121     }
122
123     return OC_STACK_OK;
124 }
125
126 /**
127  * Function to set secure port information from the given list of devices.
128  *
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.
133  *
134  * @return OC_STACK_OK for success and errorcode otherwise.
135  */
136 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
137                                        uint16_t port, uint16_t securePort)
138 {
139     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
140
141     if(!ptr)
142     {
143         OC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
144         return OC_STACK_ERROR;
145     }
146
147     ptr->securePort = securePort;
148
149     return OC_STACK_OK;
150 }
151
152 /**
153  * This function deletes list of provision target devices
154  *
155  * @param[in] pDevicesList         List of OCProvisionDev_t.
156  */
157 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
158 {
159     if(pDevicesList)
160     {
161         OCProvisionDev_t *del = NULL, *tmp = NULL;
162         LL_FOREACH_SAFE(pDevicesList, del, tmp)
163         {
164             LL_DELETE(pDevicesList, del);
165
166             DeleteDoxmBinData(del->doxm);
167             DeletePstatBinData(del->pstat);
168             OICFree(del);
169         }
170     }
171 }
172
173 /**
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.
176  *
177  * @param[in]  waittime  Timeout in seconds.
178  * @return OC_STACK_OK on success otherwise error.
179  */
180 OCStackResult PMTimeout(unsigned short waittime)
181 {
182     struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
183     struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
184
185     OCStackResult res = OC_STACK_OK;
186 #ifdef _POSIX_MONOTONIC_CLOCK
187     int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
188 #else
189     int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
190 #endif
191     if (0 != clock_res)
192     {
193         return OC_STACK_ERROR;
194     }
195     while (OC_STACK_OK == res)
196     {
197 #ifdef _POSIX_MONOTONIC_CLOCK
198         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
199 #else
200         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
201 #endif
202         if (0 != clock_res)
203         {
204             return OC_STACK_TIMEOUT;
205         }
206         long elapsed = (currTime.tv_sec - startTime.tv_sec);
207         if (elapsed > waittime)
208         {
209             return OC_STACK_OK;
210         }
211         res = OCProcess();
212     }
213
214     return res;
215 }
216
217 /**
218  * Extract secure port information from payload of discovery response.
219  *
220  * @param[in] jsonStr response payload of /oic/res discovery.
221  *
222  * @return Secure port
223  */
224 uint16_t GetSecurePortFromJSON(char* jsonStr)
225 {
226     // TODO: Modify error handling
227     if (NULL == jsonStr)
228     {
229         return 0;
230     }
231     cJSON *jsonProp = NULL;
232     cJSON *jsonP = NULL;
233     cJSON *jsonPort = NULL;
234
235     cJSON *jsonRoot = cJSON_Parse(jsonStr);
236     if(!jsonRoot)
237     {
238         // TODO: Add error log & return default secure port
239         return 0;
240     }
241
242     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
243     if(!jsonProp)
244     {
245         // TODO: Add error log & return default secure port
246         return 0;
247     }
248
249     jsonP = cJSON_GetObjectItem(jsonProp, "p");
250     if(!jsonP)
251     {
252         // TODO: Add error log & return default secure port
253         return 0;
254     }
255
256     jsonPort = cJSON_GetObjectItem(jsonP, "port");
257     if(!jsonPort)
258     {
259         // TODO: Add error log & return default secure port
260         return 0;
261     }
262
263     return (uint16_t)jsonPort->valueint;
264 }
265
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)
270 {
271     if(!address || !buffer || !uri)
272     {
273         OC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
274         return false;
275     }
276
277     int snRet = 0;
278     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
279
280     switch(connType & CT_MASK_ADAPTER)
281     {
282         case CT_ADAPTER_IP:
283             switch(connType & CT_MASK_FLAGS)
284             {
285                 case CT_IP_USE_V4:
286                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
287                                          prefix, address, port, uri);
288                     break;
289                 case CT_IP_USE_V6:
290                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
291                                          prefix, address, port, uri);
292                     break;
293                 default:
294                     OC_LOG(ERROR, TAG, "Unknown address format.");
295                     return false;
296             }
297             if(snRet >= bufferSize)
298             {
299                 OC_LOG(ERROR, TAG, "PMGenerateQuery : URI is too long");
300                 return false;
301             }
302             break;
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.");
307             return false;
308             break;
309         default:
310             OC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
311             return false;
312     }
313
314     return true;
315 }
316
317 /**
318  * Callback handler for getting secure port information using /oic/res discovery.
319  *
320  * @param[in] ctx             user context
321  * @param[in] handle          Handle for response
322  * @param[in] clientResponse  Response information(It will contain payload)
323  *
324  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
325  *         OC_STACK_DELETE_TRANSACTION to delete it.
326  */
327 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
328                                  OCClientResponse *clientResponse)
329 {
330     if (ctx == NULL)
331     {
332         OC_LOG(ERROR, TAG, "Lost List of device information");
333         return OC_STACK_KEEP_TRANSACTION;
334     }
335     (void)UNUSED;
336     if (clientResponse)
337     {
338         if  (NULL == clientResponse->payload)
339         {
340             OC_LOG(INFO, TAG, "Skiping Null payload");
341         }
342         else
343         {
344             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
345             {
346                 OC_LOG(INFO, TAG, "Wrong payload type");
347                 return OC_STACK_KEEP_TRANSACTION;
348             }
349
350             uint16_t securePort = 0;
351             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
352
353             if (resPayload && resPayload->secure)
354             {
355                 securePort = resPayload->port;
356             }
357             else
358             {
359                 OC_LOG(INFO, TAG, "Can not find secure port information.");
360                 return OC_STACK_KEEP_TRANSACTION;
361             }
362
363             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
364             OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
365
366             OCStackResult res = UpdateSecurePortOfDevice(ppDevicesList, clientResponse->devAddr.addr,
367                                                          clientResponse->devAddr.port, securePort);
368             if (OC_STACK_OK != res)
369             {
370                 OC_LOG(ERROR, TAG, "Error while getting secure port.");
371                 return OC_STACK_KEEP_TRANSACTION;
372             }
373             OC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
374         }
375
376         return  OC_STACK_KEEP_TRANSACTION;
377     }
378     else
379     {
380         OC_LOG(INFO, TAG, "Skiping Null response");
381     }
382     return  OC_STACK_DELETE_TRANSACTION;
383 }
384
385 /**
386  * Callback handler for PMDeviceDiscovery API.
387  *
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.
393  */
394 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
395                                 OCClientResponse *clientResponse)
396 {
397     if (ctx == NULL)
398     {
399         OC_LOG(ERROR, TAG, "Lost List of device information");
400         return OC_STACK_KEEP_TRANSACTION;
401     }
402     (void)UNUSED;
403     if (clientResponse)
404     {
405         if  (NULL == clientResponse->payload)
406         {
407             OC_LOG(INFO, TAG, "Skiping Null payload");
408             return OC_STACK_KEEP_TRANSACTION;
409         }
410         if (OC_STACK_OK != clientResponse->result)
411         {
412             OC_LOG(INFO, TAG, "Error in response");
413             return OC_STACK_KEEP_TRANSACTION;
414         }
415         else
416         {
417             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
418             {
419                 OC_LOG(INFO, TAG, "Unknown payload type");
420                 return OC_STACK_KEEP_TRANSACTION;
421             }
422             OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
423                             ((OCSecurityPayload*)clientResponse->payload)->securityData);
424             if (NULL == ptrDoxm)
425             {
426                 OC_LOG(INFO, TAG, "Ignoring malformed JSON");
427                 return OC_STACK_KEEP_TRANSACTION;
428             }
429             else
430             {
431                 OC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
432
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;
436
437                 // Get my device ID from doxm resource
438                 OicUuid_t myId;
439                 memset(&myId, 0, sizeof(myId));
440                 OCStackResult res = GetDoxmDevOwnerId(&myId);
441                 if(OC_STACK_OK != res)
442                 {
443                     OC_LOG(ERROR, TAG, "Error while getting my device ID.");
444                     DeleteDoxmBinData(ptrDoxm);
445                     return OC_STACK_KEEP_TRANSACTION;
446                 }
447
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))) )
451                 {
452                     OC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
453                     DeleteDoxmBinData(ptrDoxm);
454                     return OC_STACK_KEEP_TRANSACTION;
455                 }
456
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)
462                 {
463                     OC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
464                     DeleteDoxmBinData(ptrDoxm);
465                     return OC_STACK_KEEP_TRANSACTION;
466                 }
467
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))
474                 {
475                     OC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
476                     return OC_STACK_KEEP_TRANSACTION;
477                 }
478                 OC_LOG_V(DEBUG, TAG, "Query=%s", query);
479
480                 OCCallbackData cbData;
481                 cbData.cb = &SecurePortDiscoveryHandler;
482                 cbData.context = ctx;
483                 cbData.cd = NULL;
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)
488                 {
489                     OC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
490                     return OC_STACK_KEEP_TRANSACTION;
491                 }
492                 else
493                 {
494                     OC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
495                 }
496                 OC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
497             }
498
499             return  OC_STACK_KEEP_TRANSACTION;
500         }
501     }
502     else
503     {
504         OC_LOG(INFO, TAG, "Skiping Null response");
505         return OC_STACK_KEEP_TRANSACTION;
506     }
507
508     return  OC_STACK_DELETE_TRANSACTION;
509 }
510
511 /**
512  * Discover owned/unowned devices in the same IP subnet. .
513  *
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.
517  *
518  * @return OC_STACK_OK on success otherwise error.
519  */
520 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
521 {
522     OC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
523
524     if (NULL != *ppDevicesList)
525     {
526         OC_LOG(ERROR, TAG, "List is not null can cause memory leak");
527         return OC_STACK_INVALID_PARAM;
528     }
529
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";
532
533     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
534     if(NULL == pDInfo)
535     {
536         OC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
537         return OC_STACK_NO_MEMORY;
538     }
539
540     pDInfo->ppDevicesList = ppDevicesList;
541     pDInfo->isOwnedDiscovery = isOwned;
542
543     OCCallbackData cbData;
544     cbData.cb = &DeviceDiscoveryHandler;
545     cbData.context = (void *)pDInfo;
546     cbData.cd = NULL;
547     OCStackResult res = OC_STACK_ERROR;
548
549     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
550                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
551
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)
555     {
556         OC_LOG(ERROR, TAG, "OCStack resource error");
557         goto exit;
558     }
559
560     //Waiting for each response.
561     res = PMTimeout(waittime);
562     if(OC_STACK_OK != res)
563     {
564         OC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
565         goto exit;
566     }
567
568     OC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
569
570 exit:
571     OICFree(pDInfo);
572     return res;
573 }