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