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