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