VS 2013 fixes
[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 #if HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_WINDOWS_H
28 #include <windows.h>
29 #endif
30 #ifdef HAVE_STRING_H
31 #include <string.h>
32 #endif
33 #ifdef HAVE_TIME_H
34 #include <time.h>
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #endif
39
40 #include "ocstack.h"
41 #include "oic_malloc.h"
42 #include "oic_string.h"
43 #include "logger.h"
44 #include "cJSON.h"
45 #include "utlist.h"
46 #include "ocpayload.h"
47
48 #include "securevirtualresourcetypes.h"
49 #include "srmresourcestrings.h" //@note: SRM's internal header
50 #include "doxmresource.h"       //@note: SRM's internal header
51 #include "pstatresource.h"      //@note: SRM's internal header
52 #include "verresource.h"      //@note: SRM's internal header
53
54 #include "pmtypes.h"
55 #include "pmutility.h"
56
57 #include "srmutility.h"
58
59 #define TAG ("PM-UTILITY")
60
61 typedef struct _DiscoveryInfo{
62     OCProvisionDev_t    **ppDevicesList;
63     bool                isOwnedDiscovery;
64 } DiscoveryInfo;
65
66 /*
67  * Function to discover secre port information through unicast
68  *
69  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
70  * @param[in] clientResponse  Response information(It will contain payload)
71  *
72  * @return OC_STACK_OK on success otherwise error.
73  */
74 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
75                                          const OCClientResponse *clientResponse);
76
77 /*
78  * Function to discover security version information through unicast
79  *
80  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
81  * @param[in] clientResponse  Response information(It will contain payload)
82  *
83  * @return OC_STACK_OK on success otherwise error.
84  */
85 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
86                                               const OCClientResponse *clientResponse);
87
88 /**
89  * Callback handler for PMDeviceDiscovery API.
90  *
91  * @param[in] ctx             User context
92  * @param[in] handle          Handler for response
93  * @param[in] clientResponse  Response information (It will contain payload)
94  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
95  *         OC_STACK_DELETE_TRANSACTION to delete it.
96  */
97 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
98                                 OCClientResponse *clientResponse);
99
100 /**
101  * Callback handler for getting secure port information using /oic/res discovery.
102  *
103  * @param[in] ctx             user context
104  * @param[in] handle          Handle for response
105  * @param[in] clientResponse  Response information(It will contain payload)
106  *
107  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
108  *         OC_STACK_DELETE_TRANSACTION to delete it.
109  */
110 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
111                                  OCClientResponse *clientResponse);
112
113 /**
114  * Callback handler for security version discovery.
115  *
116  * @param[in] ctx             User context
117  * @param[in] handle          Handler for response
118  * @param[in] clientResponse  Response information (It will contain payload)
119  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
120  *         OC_STACK_DELETE_TRANSACTION to delete it.
121  */
122 static OCStackApplicationResult SecVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
123                                 OCClientResponse *clientResponse);
124
125 /**
126  * Function to search node in linked list that matches given IP and port.
127  *
128  * @param[in] pList         List of OCProvisionDev_t.
129  * @param[in] addr          address of target device.
130  * @param[in] port          port of remote server.
131  *
132  * @return pointer of OCProvisionDev_t if exist, otherwise NULL
133  */
134 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
135 {
136     if(NULL == addr || NULL == *ppDevicesList)
137     {
138         OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
139         return NULL;
140     }
141
142     OCProvisionDev_t *ptr = NULL;
143     LL_FOREACH(*ppDevicesList, ptr)
144     {
145         if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
146         {
147             return ptr;
148         }
149     }
150
151     return NULL;
152 }
153
154
155 /**
156  * Add device information to list.
157  *
158  * @param[in] pList         List of OCProvisionDev_t.
159  * @param[in] addr          address of target device.
160  * @param[in] port          port of remote server.
161  * @param[in] adapter       adapter type of endpoint.
162  * @param[in] doxm          pointer to doxm instance.
163  * @param[in] connType  connectivity type of endpoint
164  *
165  * @return OC_STACK_OK for success and errorcode otherwise.
166  */
167 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port,
168                         OCTransportAdapter adapter, OCConnectivityType connType, OicSecDoxm_t *doxm)
169 {
170     if (NULL == addr)
171     {
172         return OC_STACK_INVALID_PARAM;
173     }
174
175     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
176     if(!ptr)
177     {
178         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
179         if (NULL == ptr)
180         {
181             OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
182             return OC_STACK_NO_MEMORY;
183         }
184
185         OICStrcpy(ptr->endpoint.addr, MAX_ADDR_STR_SIZE, addr);
186         ptr->endpoint.port = port;
187         ptr->doxm = doxm;
188         ptr->securePort = DEFAULT_SECURE_PORT;
189         ptr->endpoint.adapter = adapter;
190         ptr->next = NULL;
191         ptr->connType = connType;
192         ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
193         OICStrcpy(ptr->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION); // version initialization
194
195         LL_PREPEND(*ppDevicesList, ptr);
196     }
197
198     return OC_STACK_OK;
199 }
200
201 /**
202  * Function to set secure port information from the given list of devices.
203  *
204  * @param[in] pList         List of OCProvisionDev_t.
205  * @param[in] addr          address of target device.
206  * @param[in] port          port of remote server.
207  * @param[in] secureport    secure port information.
208  *
209  * @return OC_STACK_OK for success and errorcode otherwise.
210  */
211 OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
212                                        uint16_t port, uint16_t securePort)
213 {
214     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
215
216     if(!ptr)
217     {
218         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
219         return OC_STACK_ERROR;
220     }
221
222     ptr->securePort = securePort;
223
224     return OC_STACK_OK;
225 }
226
227 /**
228  * Function to set security version information from the given list of devices.
229  *
230  * @param[in] pList         List of OCProvisionDev_t.
231  * @param[in] addr          address of target device.
232  * @param[in] port          port of remote server.
233  * @param[in] secVer    security version information.
234  *
235  * @return OC_STACK_OK for success and errorcode otherwise.
236  */
237 OCStackResult UpdateSecVersionOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
238                                        uint16_t port, const char* secVer)
239 {
240     if (NULL == secVer)
241     {
242         return OC_STACK_INVALID_PARAM;
243     }
244
245     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
246
247     if(!ptr)
248     {
249         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
250         return OC_STACK_ERROR;
251     }
252
253     OICStrcpy(ptr->secVer, MAX_VERSION_LEN, secVer);
254
255     return OC_STACK_OK;
256 }
257
258 /**
259  * This function deletes list of provision target devices
260  *
261  * @param[in] pDevicesList         List of OCProvisionDev_t.
262  */
263 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
264 {
265     if(pDevicesList)
266     {
267         OCProvisionDev_t *del = NULL, *tmp = NULL;
268         LL_FOREACH_SAFE(pDevicesList, del, tmp)
269         {
270             LL_DELETE(pDevicesList, del);
271
272             DeleteDoxmBinData(del->doxm);
273             DeletePstatBinData(del->pstat);
274             OICFree(del);
275         }
276     }
277 }
278
279 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
280 {
281     OIC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
282
283     if (!src)
284     {
285         OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
286         return NULL;
287     }
288
289     // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
290     OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
291     VERIFY_NON_NULL(TAG, newDev, ERROR);
292
293     memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
294
295     if (src->pstat)
296     {
297         newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
298         VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
299
300         memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
301         // We have to assign NULL for not necessary information to prevent memory corruption.
302         newDev->pstat->sm = NULL;
303     }
304
305     if (src->doxm)
306     {
307         newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
308         VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
309
310         memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
311         // We have to assign NULL for not necessary information to prevent memory corruption.
312         newDev->doxm->oxmType = NULL;
313         newDev->doxm->oxm = NULL;
314     }
315
316     if (0 == strlen(src->secVer))
317     {
318         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION);
319     }
320     else
321     {
322         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, src->secVer);
323     }
324
325     newDev->securePort = src->securePort;
326     newDev->devStatus = src->devStatus;
327     newDev->connType = src->connType;
328     newDev->next = NULL;
329
330     OIC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
331
332     return newDev;
333
334 exit:
335     OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
336     if (newDev)
337     {
338         OICFree(newDev->pstat);
339         OICFree(newDev->doxm);
340         OICFree(newDev);
341     }
342     return NULL;
343 }
344
345 /**
346  * Timeout implementation for secure discovery. When performing secure discovery,
347  * we should wait a certain period of time for getting response of each devices.
348  *
349  * @param[in]  waittime  Timeout in seconds.
350  * @param[in]  waitForStackResponse if true timeout function will call OCProcess while waiting.
351  * @return OC_STACK_OK on success otherwise error.
352  */
353 OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
354 {
355     OCStackResult res = OC_STACK_OK;
356 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
357     FILETIME startTime = {0};
358     FILETIME currTime = {0};
359     int clock_res = 1;
360
361     GetSystemTimeAsFileTime(&startTime);
362 #elif defined(HAVE_CLOCK_GETTIME)
363     struct timespec startTime = {.tv_sec=0, .tv_nsec=0};
364     struct timespec currTime  = {.tv_sec=0, .tv_nsec=0};
365
366 # if defined(_POSIX_MONOTONIC_CLOCK)
367     int clock_res = clock_gettime(CLOCK_MONOTONIC, &startTime);
368 # else
369     int clock_res = clock_gettime(CLOCK_REALTIME, &startTime);
370 # endif // defined(_POSIX_MONOTONIC_CLOCK)
371
372 #else
373     ERROR Need PMTimeout implementation
374     return OC_STACK_ERROR;
375 #endif
376
377     if (0 != clock_res)
378     {
379         return OC_STACK_ERROR;
380     }
381     while (OC_STACK_OK == res)
382     {
383 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
384         GetSystemTimeAsFileTime(&currTime);
385 #elif defined(HAVE_CLOCK_GETTIME)
386
387 # if defined(_POSIX_MONOTONIC_CLOCK)
388         clock_res = clock_gettime(CLOCK_MONOTONIC, &currTime);
389 # else
390         clock_res = clock_gettime(CLOCK_REALTIME, &currTime);
391 # endif
392         if (0 != clock_res)
393         {
394             return OC_STACK_TIMEOUT;
395         }
396 #else
397         ERROR Need PMTimeout implementation
398 #endif
399
400 #if defined(HAVE_GETSYSTEMTIMEASFILETIME)
401 #define HNS_TO_S(VAL)  ((VAL)/(10*1000*1000))
402         ULARGE_INTEGER currTimeInt;
403         ULARGE_INTEGER startTimeInt;
404
405         currTimeInt.LowPart  = currTime.dwLowDateTime;
406         currTimeInt.HighPart = currTime.dwHighDateTime;
407
408         startTimeInt.LowPart  = startTime.dwLowDateTime;
409         startTimeInt.HighPart = startTime.dwHighDateTime;
410
411         long elapsed = (long)HNS_TO_S(currTimeInt.QuadPart - startTimeInt.QuadPart);
412 #elif defined(HAVE_CLOCK_GETTIME)
413         long elapsed = (currTime.tv_sec - startTime.tv_sec);
414 #else
415         ERROR Need PMTimeout implementation
416 #endif
417         if (elapsed > waittime)
418         {
419             return OC_STACK_OK;
420         }
421         if (waitForStackResponse)
422         {
423             res = OCProcess();
424         }
425     }
426     return res;
427 }
428
429 /**
430  * Extract secure port information from payload of discovery response.
431  *
432  * @param[in] jsonStr response payload of /oic/res discovery.
433  *
434  * @return Secure port
435  */
436 uint16_t GetSecurePortFromJSON(char* jsonStr)
437 {
438     // TODO: Modify error handling
439     if (NULL == jsonStr)
440     {
441         return 0;
442     }
443     cJSON *jsonProp = NULL;
444     cJSON *jsonP = NULL;
445     cJSON *jsonPort = NULL;
446
447     cJSON *jsonRoot = cJSON_Parse(jsonStr);
448     if(!jsonRoot)
449     {
450         // TODO: Add error log & return default secure port
451         return 0;
452     }
453
454     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
455     if(!jsonProp)
456     {
457         // TODO: Add error log & return default secure port
458         return 0;
459     }
460
461     jsonP = cJSON_GetObjectItem(jsonProp, "p");
462     if(!jsonP)
463     {
464         // TODO: Add error log & return default secure port
465         return 0;
466     }
467
468     jsonPort = cJSON_GetObjectItem(jsonP, "port");
469     if(!jsonPort)
470     {
471         // TODO: Add error log & return default secure port
472         return 0;
473     }
474
475     return (uint16_t)jsonPort->valueint;
476 }
477
478 bool PMGenerateQuery(bool isSecure,
479                      const char* address, uint16_t port,
480                      OCConnectivityType connType,
481                      char* buffer, size_t bufferSize, const char* uri)
482 {
483     if(!address || !buffer || !uri)
484     {
485         OIC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
486         return false;
487     }
488
489     int snRet = 0;
490     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
491
492     switch(connType & CT_MASK_ADAPTER)
493     {
494         case CT_ADAPTER_IP:
495             switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
496             {
497                 case CT_IP_USE_V4:
498                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
499                                          prefix, address, port, uri);
500                     break;
501                 case CT_IP_USE_V6:
502                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
503                                          prefix, address, port, uri);
504                     break;
505                 default:
506                     OIC_LOG(ERROR, TAG, "Unknown address format.");
507                     return false;
508             }
509             // snprintf return value check
510             if (snRet < 0)
511             {
512                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
513                 return false;
514             }
515             else if ((size_t)snRet >= bufferSize)
516             {
517                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
518                 return false;
519             }
520
521             break;
522         // TODO: We need to verify tinyDTLS in below cases
523         case CT_ADAPTER_GATT_BTLE:
524         case CT_ADAPTER_RFCOMM_BTEDR:
525             OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
526             return false;
527             break;
528         default:
529             OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
530             return false;
531     }
532
533     return true;
534 }
535
536 static OCStackApplicationResult SecurityVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
537                                 OCClientResponse *clientResponse)
538 {
539     if (ctx == NULL)
540     {
541         OIC_LOG(ERROR, TAG, "Lost List of device information");
542         return OC_STACK_KEEP_TRANSACTION;
543     }
544     (void)UNUSED;
545     if (clientResponse)
546     {
547         if  (NULL == clientResponse->payload)
548         {
549             OIC_LOG(INFO, TAG, "Skiping Null payload");
550             return OC_STACK_KEEP_TRANSACTION;
551         }
552         if (OC_STACK_OK != clientResponse->result)
553         {
554             OIC_LOG(INFO, TAG, "Error in response");
555             return OC_STACK_KEEP_TRANSACTION;
556         }
557         else
558         {
559             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
560             {
561                 OIC_LOG(INFO, TAG, "Unknown payload type");
562                 return OC_STACK_KEEP_TRANSACTION;
563             }
564
565             OicSecVer_t *ptrVer = NULL;
566             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
567             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
568
569             OCStackResult res = CBORPayloadToVer(payload, size, &ptrVer);
570             if ((NULL == ptrVer) && (OC_STACK_OK != res))
571             {
572                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
573                 return OC_STACK_KEEP_TRANSACTION;
574             }
575             else
576             {
577                 OIC_LOG(DEBUG, TAG, "Successfully converted ver cbor to bin.");
578
579                 //If this is owend device discovery we have to filter out the responses.
580                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
581                 res = UpdateSecVersionOfDevice(pDInfo->ppDevicesList, clientResponse->devAddr.addr,
582                                                          clientResponse->devAddr.port, ptrVer->secv);
583                 if (OC_STACK_OK != res)
584                 {
585                     OIC_LOG(ERROR, TAG, "Error while getting security version.");
586                     DeleteVerBinData(ptrVer);
587                     return OC_STACK_KEEP_TRANSACTION;
588                 }
589
590                 OIC_LOG(INFO, TAG, "= Discovered security version =");
591                 OIC_LOG_V(DEBUG, TAG, "IP %s", clientResponse->devAddr.addr);
592                 OIC_LOG_V(DEBUG, TAG, "PORT %d", clientResponse->devAddr.port);
593                 OIC_LOG_V(DEBUG, TAG, "VERSION %s", ptrVer->secv);
594
595                 OIC_LOG(INFO, TAG, "Exiting SecVersionDiscoveryHandler.");
596                 DeleteVerBinData(ptrVer);
597             }
598         }
599     }
600     else
601     {
602         OIC_LOG(INFO, TAG, "Skiping Null response");
603         return OC_STACK_KEEP_TRANSACTION;
604     }
605
606     return  OC_STACK_DELETE_TRANSACTION;
607 }
608
609 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
610                                  OCClientResponse *clientResponse)
611 {
612     if (ctx == NULL)
613     {
614         OIC_LOG(ERROR, TAG, "Lost List of device information");
615         return OC_STACK_DELETE_TRANSACTION;
616     }
617     (void)UNUSED;
618     if (clientResponse)
619     {
620         if  (NULL == clientResponse->payload)
621         {
622             OIC_LOG(INFO, TAG, "Skiping Null payload");
623         }
624         else
625         {
626             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
627             {
628                 OIC_LOG(INFO, TAG, "Wrong payload type");
629                 return OC_STACK_DELETE_TRANSACTION;
630             }
631
632             uint16_t securePort = 0;
633             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
634
635             if (resPayload && resPayload->secure)
636             {
637                 securePort = resPayload->port;
638             }
639             else
640             {
641                 OIC_LOG(INFO, TAG, "Can not find secure port information.");
642                 return OC_STACK_DELETE_TRANSACTION;
643             }
644
645             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
646             OCStackResult res = UpdateSecurePortOfDevice(pDInfo->ppDevicesList,
647                                                          clientResponse->devAddr.addr,
648                                                          clientResponse->devAddr.port, securePort);
649             if (OC_STACK_OK != res)
650             {
651                 OIC_LOG(ERROR, TAG, "Error while getting secure port.");
652                 return OC_STACK_DELETE_TRANSACTION;
653             }
654
655             res = SecurityVersionDiscovery(pDInfo, clientResponse);
656             if(OC_STACK_OK != res)
657             {
658                 OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
659                 return OC_STACK_DELETE_TRANSACTION;
660             }
661
662             OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
663         }
664
665         return  OC_STACK_DELETE_TRANSACTION;
666     }
667     else
668     {
669         OIC_LOG(INFO, TAG, "Skiping Null response");
670     }
671
672     return  OC_STACK_DELETE_TRANSACTION;
673 }
674
675 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
676                                 OCClientResponse *clientResponse)
677 {
678     if (ctx == NULL)
679     {
680         OIC_LOG(ERROR, TAG, "Lost List of device information");
681         return OC_STACK_KEEP_TRANSACTION;
682     }
683     (void)UNUSED;
684     if (clientResponse)
685     {
686         if  (NULL == clientResponse->payload)
687         {
688             OIC_LOG(INFO, TAG, "Skiping Null payload");
689             return OC_STACK_KEEP_TRANSACTION;
690         }
691         if (OC_STACK_OK != clientResponse->result)
692         {
693             OIC_LOG(INFO, TAG, "Error in response");
694             return OC_STACK_KEEP_TRANSACTION;
695         }
696         else
697         {
698             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
699             {
700                 OIC_LOG(INFO, TAG, "Unknown payload type");
701                 return OC_STACK_KEEP_TRANSACTION;
702             }
703
704             OicSecDoxm_t *ptrDoxm = NULL;
705             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
706             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
707
708             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
709             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
710             {
711                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
712                 return OC_STACK_KEEP_TRANSACTION;
713             }
714             else
715             {
716                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
717
718                 //If this is owend device discovery we have to filter out the responses.
719                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
720                 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
721
722                 // Get my device ID from doxm resource
723                 OicUuid_t myId;
724                 memset(&myId, 0, sizeof(myId));
725                 OCStackResult res = GetDoxmDevOwnerId(&myId);
726                 if(OC_STACK_OK != res)
727                 {
728                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
729                     DeleteDoxmBinData(ptrDoxm);
730                     return OC_STACK_KEEP_TRANSACTION;
731                 }
732
733                 // If this is owned discovery response but owner is not me then discard it.
734                 if( (pDInfo->isOwnedDiscovery) &&
735                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
736                 {
737                     OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
738                     DeleteDoxmBinData(ptrDoxm);
739                     return OC_STACK_KEEP_TRANSACTION;
740                 }
741
742                 res = AddDevice(ppDevicesList, clientResponse->devAddr.addr,
743                         clientResponse->devAddr.port,
744                         clientResponse->devAddr.adapter,
745                         clientResponse->connType, ptrDoxm);
746                 if (OC_STACK_OK != res)
747                 {
748                     OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
749                     DeleteDoxmBinData(ptrDoxm);
750                     return OC_STACK_KEEP_TRANSACTION;
751                 }
752
753                 res = SecurePortDiscovery(pDInfo, clientResponse);
754                 if(OC_STACK_OK != res)
755                 {
756                     OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
757                     DeleteDoxmBinData(ptrDoxm);
758                     return OC_STACK_KEEP_TRANSACTION;
759                 }
760
761                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
762             }
763
764             return  OC_STACK_KEEP_TRANSACTION;
765         }
766     }
767     else
768     {
769         OIC_LOG(INFO, TAG, "Skiping Null response");
770         return OC_STACK_KEEP_TRANSACTION;
771     }
772
773     return  OC_STACK_DELETE_TRANSACTION;
774 }
775
776 /**
777  * Discover owned/unowned devices in the same IP subnet. .
778  *
779  * @param[in] waittime      Timeout in seconds.
780  * @param[in] isOwned       bool flag for owned / unowned discovery
781  * @param[in] ppDevicesList        List of OCProvisionDev_t.
782  *
783  * @return OC_STACK_OK on success otherwise error.
784  */
785 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
786 {
787     OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
788
789     if (NULL != *ppDevicesList)
790     {
791         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
792         return OC_STACK_INVALID_PARAM;
793     }
794
795     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
796     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
797
798     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
799     if(NULL == pDInfo)
800     {
801         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
802         return OC_STACK_NO_MEMORY;
803     }
804
805     pDInfo->ppDevicesList = ppDevicesList;
806     pDInfo->isOwnedDiscovery = isOwned;
807
808     OCCallbackData cbData;
809     cbData.cb = &DeviceDiscoveryHandler;
810     cbData.context = (void *)pDInfo;
811     cbData.cd = NULL;
812     OCStackResult res = OC_STACK_ERROR;
813
814     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
815                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
816
817     OCDoHandle handle = NULL;
818     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
819                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
820     if (res != OC_STACK_OK)
821     {
822         OIC_LOG(ERROR, TAG, "OCStack resource error");
823         OICFree(pDInfo);
824         return res;
825     }
826
827     //Waiting for each response.
828     res = PMTimeout(waittime, true);
829     if(OC_STACK_OK != res)
830     {
831         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
832         OICFree(pDInfo);
833         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
834         if(OC_STACK_OK !=  resCancel)
835         {
836             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
837         }
838         return res;
839     }
840     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
841     if (OC_STACK_OK != res)
842     {
843         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
844         OICFree(pDInfo);
845         return res;
846     }
847     OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
848     OICFree(pDInfo);
849     return res;
850 }
851
852 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
853                                          const OCClientResponse *clientResponse)
854 {
855     OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
856
857     if(NULL == discoveryInfo || NULL == clientResponse)
858     {
859         return OC_STACK_INVALID_PARAM;
860     }
861
862     char rsrc_uri[MAX_URI_LENGTH+1] = {0};
863     int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",
864               OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DOXM);
865     if(wr_len <= 0 || (size_t)wr_len >= sizeof(rsrc_uri))
866     {
867         OIC_LOG(ERROR, TAG, "rsrc_uri_string_print failed");
868         return OC_STACK_ERROR;
869     }
870     //Try to the unicast discovery to getting secure port
871     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
872     if(!PMGenerateQuery(false,
873                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
874                         clientResponse->connType,
875                         query, sizeof(query), rsrc_uri))
876     {
877         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
878         return OC_STACK_ERROR;
879     }
880     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
881
882     OCCallbackData cbData;
883     cbData.cb = &SecurePortDiscoveryHandler;
884     cbData.context = (void*)discoveryInfo;
885     cbData.cd = NULL;
886     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
887             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
888     if(OC_STACK_OK != ret)
889     {
890         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
891         return ret;
892     }
893     else
894     {
895         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
896     }
897
898     OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
899
900     return ret;
901 }
902
903 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
904                                               const OCClientResponse *clientResponse)
905 {
906     OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
907
908     if(NULL == discoveryInfo || NULL == clientResponse)
909     {
910         return OC_STACK_INVALID_PARAM;
911     }
912
913     //Try to the unicast discovery to getting security version
914     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
915     if(!PMGenerateQuery(false,
916                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
917                         clientResponse->connType,
918                         query, sizeof(query), OIC_RSRC_VER_URI))
919     {
920         OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
921         return OC_STACK_ERROR;
922     }
923     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
924
925     OCCallbackData cbData;
926     cbData.cb = &SecurityVersionDiscoveryHandler;
927     cbData.context = (void*)discoveryInfo;
928     cbData.cd = NULL;
929     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
930             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
931     if(OC_STACK_OK != ret)
932     {
933         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
934         return ret;
935     }
936     else
937     {
938         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
939     }
940
941     OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
942
943     return ret;
944 }
945
946 /**
947  * Function to print OCProvisionDev_t for debug purpose.
948  *
949  * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
950  *
951  */
952 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
953 {
954     if (pDev)
955     {
956         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
957         OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
958         OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
959         OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
960         OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
961     }
962     else
963     {
964         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
965     }
966 }
967
968 bool PMDeleteFromUUIDList(OCUuidList_t *pUuidList, OicUuid_t *targetId)
969 {
970     if(pUuidList == NULL || targetId == NULL)
971     {
972         return false;
973     }
974     OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
975     LL_FOREACH_SAFE(pUuidList, tmp1, tmp2)
976     {
977         if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
978         {
979             LL_DELETE(pUuidList, tmp1);
980             OICFree(tmp1);
981             return true;
982         }
983     }
984     return false;
985 }