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