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