Fix for all discovered devices to include a secure port
[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 "iotivity_config.h"
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #ifdef HAVE_STRING_H
29 #include <string.h>
30 #endif
31
32 #include "ocstack.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "oic_time.h"
36 #include "logger.h"
37 #include "cJSON.h"
38 #include "utlist.h"
39 #include "ocpayload.h"
40
41 #include "securevirtualresourcetypes.h"
42 #include "srmresourcestrings.h" //@note: SRM's internal header
43 #include "doxmresource.h"       //@note: SRM's internal header
44 #include "pstatresource.h"      //@note: SRM's internal header
45 #include "verresource.h"      //@note: SRM's internal header
46
47 #include "pmtypes.h"
48 #include "pmutility.h"
49
50 #include "srmutility.h"
51
52 #define TAG ("PM-UTILITY")
53
54 typedef struct _DiscoveryInfo{
55     OCProvisionDev_t    **ppDevicesList;
56     OCProvisionDev_t    *pCandidateList;
57     bool                isOwnedDiscovery;
58     bool                isSingleDiscovery;
59     bool                isFound;
60     const OicUuid_t     *targetId;
61 } DiscoveryInfo;
62
63 /*
64  * Function to discover secre port information through unicast
65  *
66  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
67  * @param[in] clientResponse  Response information(It will contain payload)
68  *
69  * @return OC_STACK_OK on success otherwise error.
70  */
71 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
72                                          const OCClientResponse *clientResponse);
73
74 /*
75  * Function to discover security version information through unicast
76  *
77  * @param[in] discoveryInfo The pointer of discovery information to matain result of discovery
78  * @param[in] clientResponse  Response information(It will contain payload)
79  *
80  * @return OC_STACK_OK on success otherwise error.
81  */
82 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
83                                               const OCClientResponse *clientResponse);
84
85 /**
86  * Callback handler for PMDeviceDiscovery API.
87  *
88  * @param[in] ctx             User context
89  * @param[in] handle          Handler for response
90  * @param[in] clientResponse  Response information (It will contain payload)
91  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
92  *         OC_STACK_DELETE_TRANSACTION to delete it.
93  */
94 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
95                                 OCClientResponse *clientResponse);
96
97 /**
98  * Callback handler for getting secure port information using /oic/res discovery.
99  *
100  * @param[in] ctx             user context
101  * @param[in] handle          Handle for response
102  * @param[in] clientResponse  Response information(It will contain payload)
103  *
104  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
105  *         OC_STACK_DELETE_TRANSACTION to delete it.
106  */
107 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
108                                  OCClientResponse *clientResponse);
109
110 /**
111  * Callback handler for security version discovery.
112  *
113  * @param[in] ctx             User context
114  * @param[in] handle          Handler for response
115  * @param[in] clientResponse  Response information (It will contain payload)
116  * @return OC_STACK_KEEP_TRANSACTION to keep transaction and
117  *         OC_STACK_DELETE_TRANSACTION to delete it.
118  */
119 static OCStackApplicationResult SecVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
120                                 OCClientResponse *clientResponse);
121
122 /**
123  * Function to search node in linked list that matches given IP and port.
124  *
125  * @param[in] pList         List of OCProvisionDev_t.
126  * @param[in] addr          address of target device.
127  * @param[in] port          port of remote server.
128  *
129  * @return pointer of OCProvisionDev_t if exist, otherwise NULL
130  */
131 OCProvisionDev_t* GetDevice(OCProvisionDev_t **ppDevicesList, const char* addr, const uint16_t port)
132 {
133     if(NULL == addr || NULL == *ppDevicesList)
134     {
135         OIC_LOG_V(ERROR, TAG, "Invalid Input parameters in [%s]\n", __FUNCTION__);
136         return NULL;
137     }
138
139     OCProvisionDev_t *ptr = NULL;
140     LL_FOREACH(*ppDevicesList, ptr)
141     {
142         if( strcmp(ptr->endpoint.addr, addr) == 0 && port == ptr->endpoint.port)
143         {
144             return ptr;
145         }
146     }
147
148     return NULL;
149 }
150
151
152 /**
153  * Add device information to list.
154  *
155  * @param[in] pList         List of OCProvisionDev_t.
156  * @param[in] endpoint      target device endpoint.
157  * @param[in] connType      connectivity type of endpoint
158  * @param[in] doxm          pointer to doxm instance.
159  *
160  * @return OC_STACK_OK for success and error code otherwise.
161  */
162 OCStackResult AddDevice(OCProvisionDev_t **ppDevicesList, OCDevAddr* endpoint,
163                         OCConnectivityType connType, OicSecDoxm_t *doxm)
164 {
165     if (NULL == endpoint)
166     {
167         return OC_STACK_INVALID_PARAM;
168     }
169
170     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, endpoint->addr, endpoint->port);
171     if(!ptr)
172     {
173         ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
174         if (NULL == ptr)
175         {
176             OIC_LOG(ERROR, TAG, "Error while allocating memory for linkedlist node !!");
177             return OC_STACK_NO_MEMORY;
178         }
179
180         ptr->endpoint = *endpoint;
181         ptr->doxm = doxm;
182         ptr->securePort = DEFAULT_SECURE_PORT;
183         ptr->next = NULL;
184         ptr->connType = connType;
185         ptr->devStatus = DEV_STATUS_ON; //AddDevice is called when discovery(=alive)
186         OICStrcpy(ptr->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION); // version initialization
187         ptr->handle = NULL;
188
189         LL_PREPEND(*ppDevicesList, ptr);
190     }
191
192     return OC_STACK_OK;
193 }
194
195 /**
196  * Move device object between two device lists.
197  *
198  * @param[in] ppDstDevicesList         Destination list of OCProvisionDev_t.
199  * @param[in] ppSrcDevicesList         Source list of OCProvisionDev_t.
200  * @param[in] endpoint      target device endpoint.
201  *
202  * @return OC_STACK_OK for success and error code otherwise.
203  */
204 OCStackResult MoveDeviceList(OCProvisionDev_t **ppDstDevicesList,
205                         OCProvisionDev_t **ppSrcDevicesList, OCDevAddr* endpoint)
206 {
207     if (NULL == ppSrcDevicesList || NULL == endpoint)
208     {
209         return OC_STACK_INVALID_PARAM;
210     }
211
212     OCProvisionDev_t *ptr = GetDevice(ppSrcDevicesList, endpoint->addr, endpoint->port);
213     if(ptr)
214     {
215         LL_DELETE(*ppSrcDevicesList, ptr);
216         LL_PREPEND(*ppDstDevicesList, ptr);
217         OIC_LOG_V(DEBUG, TAG, "MoveDeviceList success : %s(%d)", endpoint->addr, endpoint->port);
218         return OC_STACK_OK;
219     }
220
221     return OC_STACK_ERROR;
222 }
223
224 /**
225  * Function to set secure port information from the given list of devices.
226  *
227  * @param[in] pList         List of OCProvisionDev_t.
228  * @param[in] addr          address of target device.
229  * @param[in] port          port of remote server.
230  * @param[in] secureport    secure port information.
231  *
232  * @return OC_STACK_OK for success and errorcode otherwise.
233  */
234 static OCStackResult UpdateSecurePortOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
235                                        uint16_t port, uint16_t securePort
236 #ifdef __WITH_TLS__
237                                        ,uint16_t tcpPort
238 #endif
239                                        )
240 {
241     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
242
243     if(!ptr)
244     {
245         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
246         return OC_STACK_ERROR;
247     }
248
249     ptr->securePort = securePort;
250
251 #ifdef __WITH_TLS__
252     ptr->tcpPort = tcpPort;
253 #endif
254
255     return OC_STACK_OK;
256 }
257
258 /**
259  * Function to set security version information from the given list of devices.
260  *
261  * @param[in] pList         List of OCProvisionDev_t.
262  * @param[in] addr          address of target device.
263  * @param[in] port          port of remote server.
264  * @param[in] secVer    security version information.
265  *
266  * @return OC_STACK_OK for success and errorcode otherwise.
267  */
268 OCStackResult UpdateSecVersionOfDevice(OCProvisionDev_t **ppDevicesList, const char *addr,
269                                        uint16_t port, const char* secVer)
270 {
271     if (NULL == secVer)
272     {
273         return OC_STACK_INVALID_PARAM;
274     }
275
276     OCProvisionDev_t *ptr = GetDevice(ppDevicesList, addr, port);
277
278     if(!ptr)
279     {
280         OIC_LOG(ERROR, TAG, "Can not find device information in the discovery device list");
281         return OC_STACK_ERROR;
282     }
283
284     OICStrcpy(ptr->secVer, MAX_VERSION_LEN, secVer);
285
286     return OC_STACK_OK;
287 }
288
289 /**
290  * This function deletes list of provision target devices
291  *
292  * @param[in] pDevicesList         List of OCProvisionDev_t.
293  */
294 void PMDeleteDeviceList(OCProvisionDev_t *pDevicesList)
295 {
296     if(pDevicesList)
297     {
298         OCProvisionDev_t *del = NULL, *tmp = NULL;
299         LL_FOREACH_SAFE(pDevicesList, del, tmp)
300         {
301             LL_DELETE(pDevicesList, del);
302
303             DeleteDoxmBinData(del->doxm);
304             DeletePstatBinData(del->pstat);
305             OICFree(del);
306         }
307     }
308 }
309
310 OCProvisionDev_t* PMCloneOCProvisionDev(const OCProvisionDev_t* src)
311 {
312     OIC_LOG(DEBUG, TAG, "IN PMCloneOCProvisionDev");
313
314     if (!src)
315     {
316         OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Invalid parameter");
317         return NULL;
318     }
319
320     // TODO: Consider use VERIFY_NON_NULL instead of if ( null check ) { goto exit; }
321     OCProvisionDev_t* newDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
322     VERIFY_NON_NULL(TAG, newDev, ERROR);
323
324     memcpy(&newDev->endpoint, &src->endpoint, sizeof(OCDevAddr));
325
326     if (src->pstat)
327     {
328         newDev->pstat= (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
329         VERIFY_NON_NULL(TAG, newDev->pstat, ERROR);
330
331         memcpy(newDev->pstat, src->pstat, sizeof(OicSecPstat_t));
332         // We have to assign NULL for not necessary information to prevent memory corruption.
333         newDev->pstat->sm = NULL;
334     }
335
336     if (src->doxm)
337     {
338         newDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
339         VERIFY_NON_NULL(TAG, newDev->doxm, ERROR);
340
341         memcpy(newDev->doxm, src->doxm, sizeof(OicSecDoxm_t));
342         // We have to assign NULL for not necessary information to prevent memory corruption.
343         newDev->doxm->oxmType = NULL;
344         newDev->doxm->oxm = NULL;
345     }
346
347     if (0 == strlen(src->secVer))
348     {
349         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, DEFAULT_SEC_VERSION);
350     }
351     else
352     {
353         OICStrcpy(newDev->secVer, MAX_VERSION_LEN, src->secVer);
354     }
355
356     newDev->securePort = src->securePort;
357     newDev->devStatus = src->devStatus;
358     newDev->connType = src->connType;
359     newDev->next = NULL;
360
361     OIC_LOG(DEBUG, TAG, "OUT PMCloneOCProvisionDev");
362
363     return newDev;
364
365 exit:
366     OIC_LOG(ERROR, TAG, "PMCloneOCProvisionDev : Failed to allocate memory");
367     if (newDev)
368     {
369         OICFree(newDev->pstat);
370         OICFree(newDev->doxm);
371         OICFree(newDev);
372     }
373     return NULL;
374 }
375
376 /**
377  * Timeout implementation for secure discovery. When performing secure discovery,
378  * we should wait a certain period of time for getting response of each devices.
379  *
380  * @param[in]  waittime  Timeout in seconds.
381  * @param[in]  waitForStackResponse if true timeout function will call OCProcess while waiting.
382  * @return OC_STACK_OK on success otherwise error.
383  */
384 OCStackResult PMTimeout(unsigned short waittime, bool waitForStackResponse)
385 {
386     OCStackResult res = OC_STACK_OK;
387
388     uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);
389     while (OC_STACK_OK == res)
390     {
391         uint64_t currTime = OICGetCurrentTime(TIME_IN_MS);
392
393         long elapsed = (long)((currTime - startTime) / MS_PER_SEC);
394         if (elapsed > waittime)
395         {
396             return OC_STACK_OK;
397         }
398         if (waitForStackResponse)
399         {
400             res = OCProcess();
401         }
402     }
403     return res;
404 }
405
406 /**
407  * Extract secure port information from payload of discovery response.
408  *
409  * @param[in] jsonStr response payload of /oic/res discovery.
410  *
411  * @return Secure port
412  */
413 uint16_t GetSecurePortFromJSON(char* jsonStr)
414 {
415     // TODO: Modify error handling
416     if (NULL == jsonStr)
417     {
418         return 0;
419     }
420     cJSON *jsonProp = NULL;
421     cJSON *jsonP = NULL;
422     cJSON *jsonPort = NULL;
423
424     cJSON *jsonRoot = cJSON_Parse(jsonStr);
425     if(!jsonRoot)
426     {
427         // TODO: Add error log & return default secure port
428         return 0;
429     }
430
431     jsonProp = cJSON_GetObjectItem(jsonRoot, "prop");
432     if(!jsonProp)
433     {
434         // TODO: Add error log & return default secure port
435         return 0;
436     }
437
438     jsonP = cJSON_GetObjectItem(jsonProp, "p");
439     if(!jsonP)
440     {
441         // TODO: Add error log & return default secure port
442         return 0;
443     }
444
445     jsonPort = cJSON_GetObjectItem(jsonP, "port");
446     if(!jsonPort)
447     {
448         // TODO: Add error log & return default secure port
449         return 0;
450     }
451
452     return (uint16_t)jsonPort->valueint;
453 }
454
455 bool PMGenerateQuery(bool isSecure,
456                      const char* address, uint16_t port,
457                      OCConnectivityType connType,
458                      char* buffer, size_t bufferSize, const char* uri)
459 {
460     if(!address || !buffer || !uri)
461     {
462         OIC_LOG(ERROR, TAG, "PMGenerateQuery : Invalid parameters.");
463         return false;
464     }
465
466     int snRet = 0;
467     char* prefix = (isSecure == true) ? COAPS_PREFIX : COAP_PREFIX;
468
469     switch(connType & CT_MASK_ADAPTER)
470     {
471         case CT_ADAPTER_TCP:
472             prefix = (isSecure == true) ? COAPS_TCP_PREFIX : COAP_TCP_PREFIX;
473         case CT_ADAPTER_IP:
474             switch(connType & CT_MASK_FLAGS & ~CT_FLAG_SECURE)
475             {
476                 case CT_IP_USE_V4:
477                         snRet = snprintf(buffer, bufferSize, "%s%s:%d%s",
478                                          prefix, address, port, uri);
479                     break;
480                 case CT_IP_USE_V6:
481                         snRet = snprintf(buffer, bufferSize, "%s[%s]:%d%s",
482                                          prefix, address, port, uri);
483                     break;
484                 default:
485                     OIC_LOG(ERROR, TAG, "Unknown address format.");
486                     return false;
487             }
488             // snprintf return value check
489             if (snRet < 0)
490             {
491                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Error (snprintf) %d\n", snRet);
492                 return false;
493             }
494             else if ((size_t)snRet >= bufferSize)
495             {
496                 OIC_LOG_V(ERROR, TAG, "PMGenerateQuery : Truncated (snprintf) %d\n", snRet);
497                 return false;
498             }
499
500             break;
501         // TODO: We need to verify tinyDTLS in below cases
502         case CT_ADAPTER_GATT_BTLE:
503         case CT_ADAPTER_RFCOMM_BTEDR:
504             OIC_LOG(ERROR, TAG, "Not supported connectivity adapter.");
505             return false;
506             break;
507         default:
508             OIC_LOG(ERROR, TAG, "Unknown connectivity adapter.");
509             return false;
510     }
511
512     return true;
513 }
514
515 static OCStackApplicationResult SecurityVersionDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
516                                 OCClientResponse *clientResponse)
517 {
518     if (ctx == NULL)
519     {
520         OIC_LOG(ERROR, TAG, "Lost List of device information");
521         return OC_STACK_KEEP_TRANSACTION;
522     }
523     (void)UNUSED;
524     if (clientResponse)
525     {
526         if  (NULL == clientResponse->payload)
527         {
528             OIC_LOG(INFO, TAG, "Skiping Null payload");
529             return OC_STACK_KEEP_TRANSACTION;
530         }
531         if (OC_STACK_OK != clientResponse->result)
532         {
533             OIC_LOG(INFO, TAG, "Error in response");
534             return OC_STACK_KEEP_TRANSACTION;
535         }
536         else
537         {
538             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
539             {
540                 OIC_LOG(INFO, TAG, "Unknown payload type");
541                 return OC_STACK_KEEP_TRANSACTION;
542             }
543
544             OicSecVer_t *ptrVer = NULL;
545             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
546             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
547
548             OCStackResult res = CBORPayloadToVer(payload, size, &ptrVer);
549             if ((NULL == ptrVer) && (OC_STACK_OK != res))
550             {
551                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
552                 return OC_STACK_KEEP_TRANSACTION;
553             }
554             else
555             {
556                 OIC_LOG(DEBUG, TAG, "Successfully converted ver cbor to bin.");
557
558                 //If this is owend device discovery we have to filter out the responses.
559                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
560                 res = UpdateSecVersionOfDevice(pDInfo->ppDevicesList, clientResponse->devAddr.addr,
561                                                          clientResponse->devAddr.port, ptrVer->secv);
562                 if (OC_STACK_OK != res)
563                 {
564                     OIC_LOG(ERROR, TAG, "Error while getting security version.");
565                     DeleteVerBinData(ptrVer);
566                     return OC_STACK_KEEP_TRANSACTION;
567                 }
568
569                 OIC_LOG(INFO, TAG, "= Discovered security version =");
570                 OIC_LOG_V(DEBUG, TAG, "IP %s", clientResponse->devAddr.addr);
571                 OIC_LOG_V(DEBUG, TAG, "PORT %d", clientResponse->devAddr.port);
572                 OIC_LOG_V(DEBUG, TAG, "VERSION %s", ptrVer->secv);
573
574                 OIC_LOG(INFO, TAG, "Exiting SecVersionDiscoveryHandler.");
575                 DeleteVerBinData(ptrVer);
576             }
577         }
578     }
579     else
580     {
581         OIC_LOG(INFO, TAG, "Skiping Null response");
582         return OC_STACK_KEEP_TRANSACTION;
583     }
584
585     return  OC_STACK_DELETE_TRANSACTION;
586 }
587
588 static OCStackApplicationResult SecurePortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
589                                  OCClientResponse *clientResponse)
590 {
591     if (ctx == NULL)
592     {
593         OIC_LOG(ERROR, TAG, "Lost List of device information");
594         return OC_STACK_DELETE_TRANSACTION;
595     }
596     (void)UNUSED;
597     if (clientResponse)
598     {
599         if  (NULL == clientResponse->payload)
600         {
601             OIC_LOG(INFO, TAG, "Skiping Null payload");
602         }
603         else
604         {
605             if (PAYLOAD_TYPE_DISCOVERY != clientResponse->payload->type)
606             {
607                 OIC_LOG(INFO, TAG, "Wrong payload type");
608                 return OC_STACK_DELETE_TRANSACTION;
609             }
610
611             uint16_t securePort = 0;
612             OCResourcePayload* resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
613
614             // Use seure port of doxm for OTM and Provision.
615             while (resPayload)
616             {
617                 if (0 == strncmp(resPayload->uri, OIC_RSRC_DOXM_URI, strlen(OIC_RSRC_DOXM_URI)))
618                 {
619                     OIC_LOG_V(INFO,TAG,"resPaylod->uri:%s",resPayload->uri);
620                     OIC_LOG(INFO, TAG, "Found doxm resource.");
621                     break;
622                 }
623                 else
624                 {
625                     resPayload = resPayload->next;
626                 }
627             }
628             if (NULL == resPayload)
629             {
630                 OIC_LOG(ERROR, TAG, "Can not find doxm resource.");
631                 return OC_STACK_DELETE_TRANSACTION;
632             }
633             if (resPayload && resPayload->secure)
634             {
635                 securePort = resPayload->port;
636             }
637             else
638             {
639                 OIC_LOG(INFO, TAG, "Can not find secure port information.");
640                 return OC_STACK_DELETE_TRANSACTION;
641             }
642 #ifdef __WITH_TLS__
643             OIC_LOG_V(DEBUG, TAG, "%s: TCP port from discovery = %d", __func__, resPayload->tcpPort);
644 #endif
645             DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
646             OCProvisionDev_t *ptr = GetDevice(&pDInfo->pCandidateList,
647                                                          clientResponse->devAddr.addr,
648                                                          clientResponse->devAddr.port);
649             if(!ptr)
650             {
651                 OIC_LOG(ERROR, TAG, "Can not find device information in the discovery candidate device list");
652                 return OC_STACK_DELETE_TRANSACTION;
653             }
654
655             OCStackResult res = UpdateSecurePortOfDevice(&pDInfo->pCandidateList,
656                                                          clientResponse->devAddr.addr,
657                                                          clientResponse->devAddr.port,
658                                                          securePort
659 #ifdef __WITH_TLS__
660                                                          ,resPayload->tcpPort
661 #endif
662                                                          );
663             if (OC_STACK_OK != res)
664             {
665                 OIC_LOG(ERROR, TAG, "Error while getting secure port.");
666                 return OC_STACK_DELETE_TRANSACTION;
667             }
668
669             res = MoveDeviceList(pDInfo->ppDevicesList, &pDInfo->pCandidateList, &clientResponse->devAddr);
670             if(OC_STACK_OK != res)
671             {
672                 OIC_LOG(ERROR, TAG, "Error while move the discovered device to list.");
673                 return OC_STACK_DELETE_TRANSACTION;
674             }
675
676             if(pDInfo->isSingleDiscovery)
677             {
678                 pDInfo->isFound = true;
679             }
680
681 /*
682  * Since security version discovery does not used anymore, disable security version discovery.
683  * Need to discussion to removing all version discovery related codes.
684  */
685 #if 0
686             res = SecurityVersionDiscovery(pDInfo, clientResponse);
687             if(OC_STACK_OK != res)
688             {
689                 OIC_LOG(ERROR, TAG, "Failed to SecurityVersionDiscovery");
690                 return OC_STACK_DELETE_TRANSACTION;
691             }
692 #endif
693
694             OIC_LOG(INFO, TAG, "Exiting SecurePortDiscoveryHandler.");
695         }
696
697         return  OC_STACK_DELETE_TRANSACTION;
698     }
699     else
700     {
701         OIC_LOG(INFO, TAG, "Skiping Null response");
702     }
703
704     return  OC_STACK_DELETE_TRANSACTION;
705 }
706
707 static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
708                                 OCClientResponse *clientResponse)
709 {
710     if (ctx == NULL)
711     {
712         OIC_LOG(ERROR, TAG, "Lost List of device information");
713         return OC_STACK_KEEP_TRANSACTION;
714     }
715     (void)UNUSED;
716     if (clientResponse)
717     {
718         if  (NULL == clientResponse->payload)
719         {
720             OIC_LOG(INFO, TAG, "Skiping Null payload");
721             return OC_STACK_KEEP_TRANSACTION;
722         }
723         if (OC_STACK_OK != clientResponse->result)
724         {
725             OIC_LOG(INFO, TAG, "Error in response");
726             return OC_STACK_KEEP_TRANSACTION;
727         }
728         else
729         {
730             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
731             {
732                 OIC_LOG(INFO, TAG, "Unknown payload type");
733                 return OC_STACK_KEEP_TRANSACTION;
734             }
735
736             OicSecDoxm_t *ptrDoxm = NULL;
737             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
738             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
739
740             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
741             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
742             {
743                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
744                 return OC_STACK_KEEP_TRANSACTION;
745             }
746             else
747             {
748                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
749
750                 //If this is owend device discovery we have to filter out the responses.
751                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
752                 OCProvisionDev_t **ppDevicesList = &pDInfo->pCandidateList;
753
754                 // Get my device ID from doxm resource
755                 OicUuid_t myId;
756                 memset(&myId, 0, sizeof(myId));
757                 OCStackResult res = GetDoxmDevOwnerId(&myId);
758                 if(OC_STACK_OK != res)
759                 {
760                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
761                     DeleteDoxmBinData(ptrDoxm);
762                     return OC_STACK_KEEP_TRANSACTION;
763                 }
764
765                 // If this is owned discovery response but owner is not me then discard it.
766                 if( (pDInfo->isOwnedDiscovery) &&
767                     (0 != memcmp(&ptrDoxm->owner.id, &myId.id, sizeof(myId.id))) )
768                 {
769                     OIC_LOG(DEBUG, TAG, "Discovered device is not owend by me");
770                     DeleteDoxmBinData(ptrDoxm);
771                     return OC_STACK_KEEP_TRANSACTION;
772                 }
773
774                 res = GetDoxmDeviceID(&myId);
775                 if(OC_STACK_OK != res)
776                 {
777                     OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
778                     DeleteDoxmBinData(ptrDoxm);
779                     return OC_STACK_KEEP_TRANSACTION;
780                 }
781                 //if targetId and discovered deviceID are different, discard it
782                 if ((pDInfo->isSingleDiscovery) &&
783                     (0 != memcmp(&ptrDoxm->deviceID.id, &pDInfo->targetId->id, sizeof(pDInfo->targetId->id))) )
784                 {
785                     OIC_LOG(DEBUG, TAG, "Discovered device is not target device");
786                     DeleteDoxmBinData(ptrDoxm);
787                     return OC_STACK_KEEP_TRANSACTION;
788                 }
789                 //if this is owned discovery and this is PT's reply, discard it
790                 if (((pDInfo->isSingleDiscovery) || (pDInfo->isOwnedDiscovery)) &&
791                         (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
792                 {
793                     OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
794                     DeleteDoxmBinData(ptrDoxm);
795                     return OC_STACK_KEEP_TRANSACTION;
796                 }
797
798                 res = AddDevice(ppDevicesList, &clientResponse->devAddr,
799                         clientResponse->connType, ptrDoxm);
800                 if (OC_STACK_OK != res)
801                 {
802                     OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
803                     DeleteDoxmBinData(ptrDoxm);
804                     return OC_STACK_KEEP_TRANSACTION;
805                 }
806
807                 res = SecurePortDiscovery(pDInfo, clientResponse);
808                 if(OC_STACK_OK != res)
809                 {
810                     OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
811                     DeleteDoxmBinData(ptrDoxm);
812                     return OC_STACK_KEEP_TRANSACTION;
813                 }
814
815                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
816             }
817
818             return  OC_STACK_KEEP_TRANSACTION;
819         }
820     }
821     else
822     {
823         OIC_LOG(INFO, TAG, "Skiping Null response");
824         return OC_STACK_KEEP_TRANSACTION;
825     }
826
827     return  OC_STACK_DELETE_TRANSACTION;
828 }
829
830 static void DeviceDiscoveryDeleteHandler(void *ctx)
831 {
832     OIC_LOG(DEBUG, TAG, "IN DeviceDiscoveryDeleteHandler");
833     if (NULL == ctx)
834     {
835         OIC_LOG(WARNING, TAG, "Not found context in DeviceDiscoveryDeleteHandler");
836         return;
837     }
838
839     DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
840     if (NULL != pDInfo->pCandidateList)
841     {
842         OCProvisionDev_t *pDev = NULL;
843         LL_FOREACH(pDInfo->pCandidateList, pDev)
844         {
845             OIC_LOG_V(DEBUG, TAG, "OCCancel - %s : %d",
846                             pDev->endpoint.addr, pDev->endpoint.port);
847             OCCancel(pDev->handle,OC_HIGH_QOS,NULL,0);
848         }
849         PMDeleteDeviceList(pDInfo->pCandidateList);
850     }
851     OIC_LOG(DEBUG, TAG, "OUT DeviceDiscoveryDeleteHandler");
852 }
853
854 /**
855  * Discover owned/unowned device in the specified endpoint/deviceID.
856  * It will return the found device even though timeout is not exceeded.
857  *
858  * @param[in] waittime           Timeout in seconds
859  * @param[in] deviceID           deviceID of target device.
860  * @param[out] ppFoundDevice     OCProvisionDev_t of found device
861  *
862  * @return OC_STACK_OK on success otherwise error.\n
863  *         OC_STACK_INVALID_PARAM when deviceID is NULL or ppFoundDevice is not initailized.
864  */
865 OCStackResult PMSingleDeviceDiscovery(unsigned short waittime, const OicUuid_t* deviceID,
866                                  OCProvisionDev_t **ppFoundDevice)
867 {
868     OIC_LOG(DEBUG, TAG, "IN PMSingleDeviceDiscovery");
869
870     if (NULL != *ppFoundDevice)
871     {
872         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
873         return OC_STACK_INVALID_PARAM;
874     }
875
876     if (NULL == deviceID)
877     {
878         OIC_LOG(ERROR, TAG, "Invalid device ID");
879         return OC_STACK_INVALID_PARAM;
880     }
881
882
883     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
884     if(NULL == pDInfo)
885     {
886         OIC_LOG(ERROR, TAG, "PMSingleDeviceDiscovery : Memory allocation failed.");
887         return OC_STACK_NO_MEMORY;
888     }
889
890     pDInfo->ppDevicesList = ppFoundDevice;
891     pDInfo->pCandidateList = NULL;
892     pDInfo->isOwnedDiscovery = false;
893     pDInfo->isSingleDiscovery = true;
894     pDInfo->isFound = false;
895     pDInfo->targetId = deviceID;
896
897     OCCallbackData cbData;
898     cbData.cb = &DeviceDiscoveryHandler;
899     cbData.context = (void *)pDInfo;
900     cbData.cd = &DeviceDiscoveryDeleteHandler;
901
902     OCStackResult res = OC_STACK_ERROR;
903
904     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH + 1] = { '\0' };
905     snprintf(query, MAX_URI_LENGTH + MAX_QUERY_LENGTH + 1, "/oic/sec/doxm");
906
907     OCDoHandle handle = NULL;
908     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
909                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
910     if (res != OC_STACK_OK)
911     {
912         OIC_LOG(ERROR, TAG, "OCStack resource error");
913         OICFree(pDInfo);
914         return res;
915     }
916
917     //Waiting for each response.
918     res = OC_STACK_OK;
919     uint64_t startTime = OICGetCurrentTime(TIME_IN_MS);
920     while (OC_STACK_OK == res && !pDInfo->isFound)
921     {
922         uint64_t currTime = OICGetCurrentTime(TIME_IN_MS);
923
924         long elapsed = (long)((currTime - startTime) / MS_PER_SEC);
925         if (elapsed > waittime)
926         {
927             break;
928         }
929         res = OCProcess();
930     }
931
932     if(OC_STACK_OK != res)
933     {
934         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
935         OICFree(pDInfo);
936         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
937         if(OC_STACK_OK !=  resCancel)
938         {
939             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
940         }
941         return res;
942     }
943
944     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
945     if (OC_STACK_OK != res)
946     {
947         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
948         OICFree(pDInfo);
949         return res;
950     }
951     OIC_LOG(DEBUG, TAG, "OUT PMSingleDeviceDiscovery");
952     OICFree(pDInfo);
953     return res;
954 }
955
956
957 /**
958  * Discover owned/unowned devices in the same IP subnet. .
959  *
960  * @param[in] waittime      Timeout in seconds.
961  * @param[in] isOwned       bool flag for owned / unowned discovery
962  * @param[in] ppDevicesList        List of OCProvisionDev_t.
963  *
964  * @return OC_STACK_OK on success otherwise error.
965  */
966 OCStackResult PMDeviceDiscovery(unsigned short waittime, bool isOwned, OCProvisionDev_t **ppDevicesList)
967 {
968     OIC_LOG(DEBUG, TAG, "IN PMDeviceDiscovery");
969
970     if (NULL != *ppDevicesList)
971     {
972         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
973         return OC_STACK_INVALID_PARAM;
974     }
975
976     const char DOXM_OWNED_FALSE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=FALSE";
977     const char DOXM_OWNED_TRUE_MULTICAST_QUERY[] = "/oic/sec/doxm?Owned=TRUE";
978
979     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
980     if(NULL == pDInfo)
981     {
982         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
983         return OC_STACK_NO_MEMORY;
984     }
985
986     pDInfo->ppDevicesList = ppDevicesList;
987     pDInfo->pCandidateList = NULL;
988     pDInfo->isOwnedDiscovery = isOwned;
989     pDInfo->isSingleDiscovery = false;
990     pDInfo->targetId = NULL;
991
992     OCCallbackData cbData;
993     cbData.cb = &DeviceDiscoveryHandler;
994     cbData.context = (void *)pDInfo;
995     cbData.cd = &DeviceDiscoveryDeleteHandler;
996     OCStackResult res = OC_STACK_ERROR;
997
998     const char* query = isOwned ? DOXM_OWNED_TRUE_MULTICAST_QUERY :
999                                   DOXM_OWNED_FALSE_MULTICAST_QUERY;
1000
1001     OCDoHandle handle = NULL;
1002     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
1003                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
1004     if (res != OC_STACK_OK)
1005     {
1006         OIC_LOG(ERROR, TAG, "OCStack resource error");
1007         OICFree(pDInfo);
1008         return res;
1009     }
1010
1011     //Waiting for each response.
1012     res = PMTimeout(waittime, true);
1013     if(OC_STACK_OK != res)
1014     {
1015         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
1016         OICFree(pDInfo);
1017         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
1018         if(OC_STACK_OK !=  resCancel)
1019         {
1020             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
1021         }
1022         return res;
1023     }
1024     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
1025     if (OC_STACK_OK != res)
1026     {
1027         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
1028         OICFree(pDInfo);
1029         return res;
1030     }
1031     OIC_LOG(DEBUG, TAG, "OUT PMDeviceDiscovery");
1032     OICFree(pDInfo);
1033     return res;
1034 }
1035
1036 #ifdef _ENABLE_MULTIPLE_OWNER_
1037 static OCStackApplicationResult MOTDeviceDiscoveryHandler(void *ctx, OCDoHandle UNUSED,
1038                                 OCClientResponse *clientResponse)
1039 {
1040     if (ctx == NULL)
1041     {
1042         OIC_LOG(ERROR, TAG, "Lost List of device information");
1043         return OC_STACK_KEEP_TRANSACTION;
1044     }
1045     (void)UNUSED;
1046     if (clientResponse)
1047     {
1048         if  (NULL == clientResponse->payload)
1049         {
1050             OIC_LOG(INFO, TAG, "Skipping Null payload");
1051             return OC_STACK_KEEP_TRANSACTION;
1052         }
1053         if (OC_STACK_OK != clientResponse->result)
1054         {
1055             OIC_LOG(INFO, TAG, "Error in response");
1056             return OC_STACK_KEEP_TRANSACTION;
1057         }
1058         else
1059         {
1060             if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
1061             {
1062                 OIC_LOG(INFO, TAG, "Unknown payload type");
1063                 return OC_STACK_KEEP_TRANSACTION;
1064             }
1065
1066             OicSecDoxm_t *ptrDoxm = NULL;
1067             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
1068             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
1069
1070             OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
1071             if ((NULL == ptrDoxm) || (OC_STACK_OK != res))
1072             {
1073                 OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
1074                 return OC_STACK_KEEP_TRANSACTION;
1075             }
1076             else
1077             {
1078                 OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
1079
1080                 //If this is owend device discovery we have to filter out the responses.
1081                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
1082                 OCProvisionDev_t **ppDevicesList = pDInfo->ppDevicesList;
1083
1084                 // Get my device ID from doxm resource
1085                 OicUuid_t myId;
1086                 memset(&myId, 0, sizeof(myId));
1087                 OCStackResult res = GetDoxmDevOwnerId(&myId);
1088                 if(OC_STACK_OK != res)
1089                 {
1090                     OIC_LOG(ERROR, TAG, "Error while getting my device ID.");
1091                     DeleteDoxmBinData(ptrDoxm);
1092                     return OC_STACK_KEEP_TRANSACTION;
1093                 }
1094
1095                 res = GetDoxmDeviceID(&myId);
1096                 if(OC_STACK_OK != res)
1097                 {
1098                     OIC_LOG(ERROR, TAG, "Error while getting my UUID.");
1099                     DeleteDoxmBinData(ptrDoxm);
1100                     return OC_STACK_KEEP_TRANSACTION;
1101                 }
1102                 //if this is owned discovery and this is PT's reply, discard it
1103                 if((pDInfo->isOwnedDiscovery) &&
1104                         (0 == memcmp(&ptrDoxm->deviceID.id, &myId.id, sizeof(myId.id))) )
1105                 {
1106                     OIC_LOG(DEBUG, TAG, "discarding provision tool's reply");
1107                     DeleteDoxmBinData(ptrDoxm);
1108                     return OC_STACK_KEEP_TRANSACTION;
1109                 }
1110
1111                 if(pDInfo->isOwnedDiscovery)
1112                 {
1113                     OicSecSubOwner_t* subOwner = NULL;
1114                     LL_FOREACH(ptrDoxm->subOwners, subOwner)
1115                     {
1116                         if(memcmp(myId.id, subOwner->uuid.id, sizeof(myId.id)) == 0)
1117                         {
1118                             break;
1119                         }
1120                     }
1121
1122                     if(subOwner)
1123                     {
1124                         res = AddDevice(ppDevicesList, &clientResponse->devAddr,
1125                                 clientResponse->connType, ptrDoxm);
1126                         if (OC_STACK_OK != res)
1127                         {
1128                             OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
1129                             DeleteDoxmBinData(ptrDoxm);
1130                             return OC_STACK_KEEP_TRANSACTION;
1131                         }
1132
1133                         res = SecurePortDiscovery(pDInfo, clientResponse);
1134                         if(OC_STACK_OK != res)
1135                         {
1136                             OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
1137                             DeleteDoxmBinData(ptrDoxm);
1138                             return OC_STACK_KEEP_TRANSACTION;
1139                         }
1140                     }
1141                     else
1142                     {
1143                         OIC_LOG(ERROR, TAG, "discarding device's reply, because not a SubOwner.");
1144                         DeleteDoxmBinData(ptrDoxm);
1145                         return OC_STACK_KEEP_TRANSACTION;
1146                     }
1147                 }
1148                 else
1149                 {
1150                     if(ptrDoxm->mom && OIC_MULTIPLE_OWNER_DISABLE != ptrDoxm->mom->mode)
1151                     {
1152                         res = AddDevice(ppDevicesList, &clientResponse->devAddr,
1153                                 clientResponse->connType, ptrDoxm);
1154                         if (OC_STACK_OK != res)
1155                         {
1156                             OIC_LOG(ERROR, TAG, "Error while adding data to linkedlist.");
1157                             DeleteDoxmBinData(ptrDoxm);
1158                             return OC_STACK_KEEP_TRANSACTION;
1159                         }
1160
1161                         res = SecurePortDiscovery(pDInfo, clientResponse);
1162                         if(OC_STACK_OK != res)
1163                         {
1164                             OIC_LOG(ERROR, TAG, "Failed to SecurePortDiscovery");
1165                             DeleteDoxmBinData(ptrDoxm);
1166                             return OC_STACK_KEEP_TRANSACTION;
1167                         }
1168                     }
1169                     else
1170                     {
1171                         OIC_LOG(ERROR, TAG, "discarding mom disabled device's reply");
1172                         DeleteDoxmBinData(ptrDoxm);
1173                         return OC_STACK_KEEP_TRANSACTION;
1174                     }
1175                 }
1176
1177                 OIC_LOG(INFO, TAG, "Exiting ProvisionDiscoveryHandler.");
1178             }
1179
1180             return  OC_STACK_KEEP_TRANSACTION;
1181         }
1182     }
1183     else
1184     {
1185         OIC_LOG(INFO, TAG, "Skiping Null response");
1186         return OC_STACK_KEEP_TRANSACTION;
1187     }
1188
1189     return  OC_STACK_DELETE_TRANSACTION;
1190 }
1191
1192
1193 /**
1194  * Discover multiple OTM enabled devices in the same IP subnet.
1195  *
1196  * @param[in] waittime      Timeout in seconds.
1197  * @param[in] ppDevicesList        List of OCProvisionDev_t.
1198  *
1199  * @return OC_STACK_OK on success otherwise error.
1200  */
1201 OCStackResult PMMultipleOwnerDeviceDiscovery(unsigned short waittime, bool isMultipleOwned, OCProvisionDev_t **ppDevicesList)
1202 {
1203     OIC_LOG(DEBUG, TAG, "IN PMMultipleOwnerEnabledDeviceDiscovery");
1204
1205     if (NULL != *ppDevicesList)
1206     {
1207         OIC_LOG(ERROR, TAG, "List is not null can cause memory leak");
1208         return OC_STACK_INVALID_PARAM;
1209     }
1210
1211     const char *DOXM_MOM_ENABLE_MULTICAST_QUERY = "/oic/sec/doxm?mom!=0&owned=TRUE";
1212     const char *DOXM_MULTIPLE_OWNED_MULTICAST_QUERY = "/oic/sec/doxm?owned=TRUE";
1213
1214     DiscoveryInfo *pDInfo = OICCalloc(1, sizeof(DiscoveryInfo));
1215     if(NULL == pDInfo)
1216     {
1217         OIC_LOG(ERROR, TAG, "PMDeviceDiscovery : Memory allocation failed.");
1218         return OC_STACK_NO_MEMORY;
1219     }
1220
1221     pDInfo->ppDevicesList = ppDevicesList;
1222     pDInfo->isOwnedDiscovery = isMultipleOwned;
1223
1224     OCCallbackData cbData;
1225     cbData.cb = &MOTDeviceDiscoveryHandler;
1226     cbData.context = (void *)pDInfo;
1227     cbData.cd = NULL;
1228     OCStackResult res = OC_STACK_ERROR;
1229
1230     const char* query = isMultipleOwned ? DOXM_MULTIPLE_OWNED_MULTICAST_QUERY :
1231                                           DOXM_MOM_ENABLE_MULTICAST_QUERY;
1232
1233     OCDoHandle handle = NULL;
1234     res = OCDoResource(&handle, OC_REST_DISCOVER, query, 0, 0,
1235                                      CT_DEFAULT, OC_HIGH_QOS, &cbData, NULL, 0);
1236     if (res != OC_STACK_OK)
1237     {
1238         OIC_LOG(ERROR, TAG, "OCStack resource error");
1239         OICFree(pDInfo);
1240         return res;
1241     }
1242
1243     //Waiting for each response.
1244     res = PMTimeout(waittime, true);
1245     if(OC_STACK_OK != res)
1246     {
1247         OIC_LOG(ERROR, TAG, "Failed to wait response for secure discovery.");
1248         OICFree(pDInfo);
1249         OCStackResult resCancel = OCCancel(handle, OC_HIGH_QOS, NULL, 0);
1250         if(OC_STACK_OK !=  resCancel)
1251         {
1252             OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
1253         }
1254         return res;
1255     }
1256     res = OCCancel(handle,OC_HIGH_QOS,NULL,0);
1257     if (OC_STACK_OK != res)
1258     {
1259         OIC_LOG(ERROR, TAG, "Failed to remove registered callback");
1260         OICFree(pDInfo);
1261         return res;
1262     }
1263     OIC_LOG(DEBUG, TAG, "OUT PMMultipleOwnerEnabledDeviceDiscovery");
1264     OICFree(pDInfo);
1265     return res;
1266 }
1267
1268 #endif //_ENABLE_MULTIPLE_OWNER_
1269
1270 static OCStackResult SecurePortDiscovery(DiscoveryInfo* discoveryInfo,
1271                                          const OCClientResponse *clientResponse)
1272 {
1273     OIC_LOG(DEBUG, TAG, "IN SecurePortDiscovery");
1274
1275     if(NULL == discoveryInfo || NULL == clientResponse)
1276     {
1277         return OC_STACK_INVALID_PARAM;
1278     }
1279
1280     OCProvisionDev_t *pDev = GetDevice(&discoveryInfo->pCandidateList,
1281                         clientResponse->devAddr.addr, clientResponse->devAddr.port);
1282     if(NULL == pDev)
1283     {
1284         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to get device");
1285         return OC_STACK_ERROR;
1286     }
1287
1288     //Try to the unicast discovery to getting secure port
1289     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
1290     if(!PMGenerateQuery(false,
1291                         pDev->endpoint.addr, pDev->endpoint.port,
1292                         pDev->connType,
1293                         query, sizeof(query), OC_RSRVD_WELL_KNOWN_URI))
1294     {
1295         OIC_LOG(ERROR, TAG, "SecurePortDiscovery : Failed to generate query");
1296         return OC_STACK_ERROR;
1297     }
1298     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1299
1300     OCCallbackData cbData;
1301     cbData.cb = &SecurePortDiscoveryHandler;
1302     cbData.context = (void*)discoveryInfo;
1303     cbData.cd = NULL;
1304     OCStackResult ret = OCDoResource(&pDev->handle, OC_REST_DISCOVER, query, 0, 0,
1305             pDev->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1306     if(OC_STACK_OK != ret)
1307     {
1308         OIC_LOG(ERROR, TAG, "Failed to Secure Port Discovery");
1309         return ret;
1310     }
1311     else
1312     {
1313         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
1314     }
1315
1316     OIC_LOG(DEBUG, TAG, "OUT SecurePortDiscovery");
1317
1318     return ret;
1319 }
1320
1321 static OCStackResult SecurityVersionDiscovery(DiscoveryInfo* discoveryInfo,
1322                                               const OCClientResponse *clientResponse)
1323 {
1324     OIC_LOG(DEBUG, TAG, "IN SecurityVersionDiscovery");
1325
1326     if(NULL == discoveryInfo || NULL == clientResponse)
1327     {
1328         return OC_STACK_INVALID_PARAM;
1329     }
1330
1331     //Try to the unicast discovery to getting security version
1332     char query[MAX_URI_LENGTH+MAX_QUERY_LENGTH+1] = {0};
1333     if(!PMGenerateQuery(false,
1334                         clientResponse->devAddr.addr, clientResponse->devAddr.port,
1335                         clientResponse->connType,
1336                         query, sizeof(query), OIC_RSRC_VER_URI))
1337     {
1338         OIC_LOG(ERROR, TAG, "SecurityVersionDiscovery : Failed to generate query");
1339         return OC_STACK_ERROR;
1340     }
1341     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1342
1343     OCCallbackData cbData;
1344     cbData.cb = &SecurityVersionDiscoveryHandler;
1345     cbData.context = (void*)discoveryInfo;
1346     cbData.cd = NULL;
1347     OCStackResult ret = OCDoResource(NULL, OC_REST_DISCOVER, query, 0, 0,
1348             clientResponse->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1349     if(OC_STACK_OK != ret)
1350     {
1351         OIC_LOG(ERROR, TAG, "Failed to Security Version Discovery");
1352         return ret;
1353     }
1354     else
1355     {
1356         OIC_LOG_V(INFO, TAG, "OCDoResource with [%s] Success", query);
1357     }
1358
1359     OIC_LOG(DEBUG, TAG, "OUT SecurityVersionDiscovery");
1360
1361     return ret;
1362 }
1363
1364 /**
1365  * Function to print OCProvisionDev_t for debug purpose.
1366  *
1367  * @param[in] pDev Pointer to OCProvisionDev_t. It's information will be printed by OIC_LOG_XX
1368  *
1369  */
1370 void PMPrintOCProvisionDev(const OCProvisionDev_t* pDev)
1371 {
1372     if (pDev)
1373     {
1374         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t Information +++++");
1375         OIC_LOG_V(DEBUG, TAG, "IP %s", pDev->endpoint.addr);
1376         OIC_LOG_V(DEBUG, TAG, "PORT %d", pDev->endpoint.port);
1377         OIC_LOG_V(DEBUG, TAG, "S-PORT %d", pDev->securePort);
1378         OIC_LOG(DEBUG, TAG, "++++++++++++++++++++++++++++++++++++++++");
1379     }
1380     else
1381     {
1382         OIC_LOG(DEBUG, TAG, "+++++ OCProvisionDev_t is NULL +++++");
1383     }
1384 }
1385
1386 bool PMDeleteFromUUIDList(OCUuidList_t **pUuidList, OicUuid_t *targetId)
1387 {
1388     if(*pUuidList == NULL || targetId == NULL)
1389     {
1390         return false;
1391     }
1392     OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
1393     LL_FOREACH_SAFE(*pUuidList, tmp1, tmp2)
1394     {
1395         if(0 == memcmp(tmp1->dev.id, targetId->id, sizeof(targetId->id)))
1396         {
1397             LL_DELETE(*pUuidList, tmp1);
1398             OICFree(tmp1);
1399             return true;
1400         }
1401     }
1402     return false;
1403 }