ACL payload conversion from JSON to CBOR
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / secureresourceprovider.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 #include <stdio.h>
21 #include <string.h>
22 #include <stdint.h>
23 #include <unistd.h>
24
25 #include "ocprovisioningmanager.h"
26 #include "secureresourceprovider.h"
27 #include "logger.h"
28 #include "oic_malloc.h"
29 #include "aclresource.h"
30 #include "pstatresource.h"
31 #include "srmresourcestrings.h"
32 #include "credresource.h"
33 #include "doxmresource.h"
34 #include "pconfresource.h"
35 #include "credentialgenerator.h"
36 #include "cainterface.h"
37 #include "cJSON.h"
38 #include "pmtypes.h"
39 #include "pmutility.h"
40 #include "provisioningdatabasemanager.h"
41 #include "base64.h"
42 #include "utlist.h"
43 #include "ocpayload.h"
44
45 #ifdef __WITH_X509__
46 #include "crlresource.h"
47 #endif // WITH_X509__
48
49 #define TAG "SRPAPI"
50
51 /**
52  * Macro to verify argument is not equal to NULL.
53  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR,OC_STACK_ERROR);
54  */
55 #define VERIFY_NON_NULL(tag, arg, logLevel, retValue) { if (NULL == (arg)) \
56             { OIC_LOG((logLevel), tag, #arg " is NULL"); return retValue; } }
57
58 /**
59  * Macro to verify success of operation.
60  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR, OC_STACK_ERROR);
61  */
62 #define VERIFY_SUCCESS(tag, op, logLevel, retValue) { if (!(op)) \
63             {OIC_LOG((logLevel), tag, #op " failed!!"); return retValue;} }
64
65 /**
66  * Structure to carry credential data to callback.
67  */
68 typedef struct CredentialData CredentialData_t;
69 struct CredentialData
70 {
71     void *ctx;                                  /**< Pointer to user context.**/
72     const OCProvisionDev_t *deviceInfo1;        /**< Pointer to OCProvisionDev_t.**/
73     const OCProvisionDev_t *deviceInfo2;        /**< Pointer to OCProvisionDev_t.**/
74     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
75     OicSecCred_t *credInfoFirst;                /**< Pointer to OicSecCred_t.**/
76     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
77     OCProvisionResult_t *resArr;                /**< Result array.**/
78     int numOfResults;                           /**< Number of results in result array.**/
79 };
80
81 /**
82  * Structure to carry ACL provision API data to callback.
83  */
84 typedef struct ACLData ACLData_t;
85 struct ACLData
86 {
87     void *ctx;                                  /**< Pointer to user context.**/
88     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
89     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
90     OCProvisionResult_t *resArr;                /**< Result array.**/
91     int numOfResults;                           /**< Number of results in result array.**/
92 };
93
94 /**
95  * Structure to carry PCONF provision API data to callback.
96  */
97 typedef struct PconfData PconfData_t;
98 struct PconfData
99 {
100     void *ctx;                                  /**< Pointer to user context.**/
101     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
102     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
103     OCProvisionResult_t *resArr;                /**< Result array.**/
104     int numOfResults;                           /**< Number of results in result array.**/
105 };
106
107 // Enum type index for unlink callback.
108 typedef enum {
109     IDX_FIRST_DEVICE_RES = 0, // index for resulf of the first device
110     IDX_SECOND_DEVICE_RES,    // index for result of the second device
111     IDX_DB_UPDATE_RES         // index for result of updating provisioning database.
112 } IdxUnlinkRes_t;
113
114 // Structure to carry unlink APIs data to callback.
115 typedef struct UnlinkData UnlinkData_t;
116 struct UnlinkData {
117     void *ctx;
118     OCProvisionDev_t* unlinkDev;             /**< Pointer to OCProvisionDev_t to be unlinked.**/
119     OCProvisionResult_t* unlinkRes;          /**< Result array.**/
120     OCProvisionResultCB resultCallback;      /**< Pointer to result callback.**/
121     int numOfResults;                        /**< Number of results in result array.**/
122 };
123
124 //Example of DELETE cred request -> coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
125 const char * SRP_FORM_DELETE_CREDENTIAL = "coaps://[%s]:%d%s?%s=%s";
126
127 // Structure to carry remove APIs data to callback.
128 typedef struct RemoveData RemoveData_t;
129 struct RemoveData {
130     void *ctx;
131     OCProvisionDev_t* revokeTargetDev;      /**< Device which is going to be revoked..**/
132     OCProvisionDev_t* linkedDevList;        /**< A list of devices which have invalid credential.**/
133     OCProvisionResult_t* removeRes;         /**< Result array.**/
134     OCProvisionResultCB resultCallback;     /**< Pointer to result callback.**/
135     size_t numOfResults;                    /**< Number of results in result array.**/
136     size_t sizeOfResArray;
137     bool hasError;
138 };
139
140 /**
141  * Function prototype
142  */
143 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
144         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
145         OCClientResponseHandler responseHandler);
146
147
148 /**
149  * Internal function to update result in result array.
150  */
151 static void registerResultForCredProvisioning(CredentialData_t *credData,
152                                               OCStackResult stackresult, int cause)
153 {
154
155    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
156    if(1 == cause)
157    {
158        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
159               credData->deviceInfo1->doxm->deviceID.id,UUID_LENGTH);
160    }
161    else
162    {
163        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
164               credData->deviceInfo2->doxm->deviceID.id,UUID_LENGTH);
165    }
166    credData->resArr[(credData->numOfResults)].res = stackresult;
167    ++(credData->numOfResults);
168 }
169
170 /**
171  * Callback handler for handling callback of provisioning device 2.
172  *
173  * @param[in] ctx             ctx value passed to callback from calling function.
174  * @param[in] UNUSED          handle to an invocation
175  * @param[in] clientResponse  Response from queries to remote servers.
176  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
177  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
178  */
179 static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNUSED,
180                                                        OCClientResponse *clientResponse)
181 {
182     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
183     CredentialData_t *credData = (CredentialData_t *) ctx;
184     (void)UNUSED;
185
186     OCProvisionResultCB resultCallback = credData->resultCallback;
187     OIC_LOG(INFO, TAG, "provisionCredentialCB2 called");
188     if (clientResponse)
189     {
190         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
191         {
192             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CREATED, 2);
193             OCStackResult res =  PDMLinkDevices(&credData->deviceInfo1->doxm->deviceID,
194                     &credData->deviceInfo2->doxm->deviceID);
195             if (OC_STACK_OK != res)
196             {
197                 OIC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
198                 return OC_STACK_DELETE_TRANSACTION;
199             }
200             OIC_LOG(INFO, TAG, "Link created successfully");
201
202             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
203                                                     credData->resArr,
204                                                     false);
205              OICFree(credData->resArr);
206              OICFree(credData);
207              return OC_STACK_DELETE_TRANSACTION;
208         }
209
210     }
211     OIC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
212     registerResultForCredProvisioning(credData, OC_STACK_ERROR, 2);
213     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
214                                             credData->resArr,
215                                             true);
216     OICFree(credData->resArr);
217     OICFree(credData);
218     return OC_STACK_DELETE_TRANSACTION;
219 }
220
221 /**
222  * Callback handler for handling callback of provisioning device 1.
223  *
224  * @param[in] ctx             ctx value passed to callback from calling function.
225  * @param[in] UNUSED          handle to an invocation
226  * @param[in] clientResponse  Response from queries to remote servers.
227  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
228  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
229  */
230 static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNUSED,
231                                                        OCClientResponse *clientResponse)
232 {
233     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
234     (void)UNUSED;
235     CredentialData_t* credData = (CredentialData_t*) ctx;
236     OICFree(credData->credInfoFirst);
237     const OCProvisionDev_t *deviceInfo = credData->deviceInfo2;
238     OicSecCred_t *credInfo = credData->credInfo;
239     const OCProvisionResultCB resultCallback = credData->resultCallback;
240     if (clientResponse)
241     {
242         if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
243         {
244             // send credentials to second device
245             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CREATED,1);
246             OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData,
247                     provisionCredentialCB2);
248             DeleteCredList(credInfo);
249             if (OC_STACK_OK != res)
250             {
251                 registerResultForCredProvisioning(credData, res,2);
252                 ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
253                                                         credData->resArr,
254                                                         true);
255                 OICFree(credData->resArr);
256                 OICFree(credData);
257                 credData = NULL;
258             }
259         }
260         else
261         {
262             registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
263             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
264                                                     credData->resArr,
265                                                     true);
266             OICFree(credData->resArr);
267             OICFree(credData);
268             credData = NULL;
269         }
270     }
271     else
272     {
273         OIC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
274         registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
275        ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
276                                                      credData->resArr,
277                                                      true);
278         DeleteCredList(credInfo);
279         OICFree(credData->resArr);
280         OICFree(credData);
281         credData = NULL;
282     }
283     return OC_STACK_DELETE_TRANSACTION;
284 }
285
286
287
288 /**
289  * Internal function for handling credential generation and sending credential to resource server.
290  *
291  * @param[in] cred Instance of cred resource.
292  * @param[in] deviceInfo information about device to which credential is to be provisioned.
293  * @param[in] responseHandler callbak called by OC stack when request API receives response.
294  * @return  OC_STACK_OK in case of success and other value otherwise.
295  */
296 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
297         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
298         OCClientResponseHandler responseHandler)
299 {
300     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
301     if(!secPayload)
302     {
303         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
304         return OC_STACK_NO_MEMORY;
305     }
306     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
307     secPayload->securityData = BinToCredJSON(cred);
308     if(NULL == secPayload->securityData)
309     {
310         OICFree(secPayload);
311         OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
312         return OC_STACK_NO_MEMORY;
313     }
314
315     OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
316     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
317     if(!PMGenerateQuery(true,
318                         deviceInfo->endpoint.addr,
319                         deviceInfo->securePort,
320                         deviceInfo->connType,
321                         query, sizeof(query), OIC_RSRC_CRED_URI))
322     {
323         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
324         return OC_STACK_ERROR;
325     }
326     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
327
328     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
329     cbData.cb = responseHandler;
330     cbData.context = (void *) credData;
331     cbData.cd = NULL;
332
333     OCDoHandle handle = NULL;
334     OCMethod method = OC_REST_POST;
335     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
336             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
337     OIC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d",ret);
338     if (ret != OC_STACK_OK)
339     {
340         OIC_LOG(ERROR, TAG, "OCStack resource error");
341         return ret;
342     }
343     return OC_STACK_OK;
344 }
345
346 #ifdef __WITH_X509__
347 /**
348  * Structure to carry certificate data to callback.
349  */
350 typedef struct CertificateData CertData_t;
351 struct CertificateData
352 {
353     void *ctx;                                  /**< Pointer to user context.**/
354     const OCProvisionDev_t *deviceInfo;        /**< Pointer to OCProvisionDev_t.**/
355     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
356     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
357     OCProvisionResult_t *resArr;                /**< Result array.**/
358     int numOfResults;                           /**< Number of results in result array.**/
359 };
360
361 /**
362  * Structure to carry CRL provision API data to callback.
363  */
364 typedef struct CRLData CRLData_t;
365 struct CRLData
366 {
367     void *ctx;                                  /**< Pointer to user context.**/
368     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
369     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
370     OCProvisionResult_t *resArr;                /**< Result array.**/
371     int numOfResults;                           /**< Number of results in result array.**/
372 };
373
374 /**
375  * Internal function to update result in result array.
376  */
377 static void registerResultForCertProvisioning(CertData_t *certData,
378                                               OCStackResult stackresult)
379 {
380
381    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
382    memcpy(certData->resArr[(certData->numOfResults)].deviceId.id,
383           certData->deviceInfo->doxm->deviceID.id,UUID_LENGTH);
384    certData->resArr[(certData->numOfResults)].res = stackresult;
385    ++(certData->numOfResults);
386 }
387
388 /**
389  * Internal Function to store results in result array during ACL provisioning.
390  */
391 static void registerResultForCRLProvisioning(CRLData_t *crlData,
392                                              OCStackResult stackresult)
393 {
394    OIC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n",
395                        crlData->numOfResults);
396    memcpy(crlData->resArr[(crlData->numOfResults)].deviceId.id,
397           crlData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
398    crlData->resArr[(crlData->numOfResults)].res = stackresult;
399    ++(crlData->numOfResults);
400 }
401
402
403 /**
404  * Callback handler of SRPProvisionCRL.
405  *
406  * @param[in] ctx             ctx value passed to callback from calling function.
407  * @param[in] UNUSED          handle to an invocation
408  * @param[in] clientResponse  Response from queries to remote servers.
409  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
410  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
411  */
412 static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED,
413                                                   OCClientResponse *clientResponse)
414 {
415     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB.");
416     (void)UNUSED;
417     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
418     CRLData_t *crlData = (CRLData_t*)ctx;
419     OCProvisionResultCB resultCallback = crlData->resultCallback;
420
421     if (clientResponse)
422     {
423         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
424         {
425             registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CREATED);
426             ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
427                                                     crlData->resArr,
428                                                     false);
429              OICFree(crlData->resArr);
430              OICFree(crlData);
431              return OC_STACK_DELETE_TRANSACTION;
432         }
433     }
434     registerResultForCRLProvisioning(crlData, OC_STACK_ERROR);
435     ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
436                                             crlData->resArr,
437                                             true);
438     OIC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse");
439     OICFree(crlData->resArr);
440     OICFree(crlData);
441     return OC_STACK_DELETE_TRANSACTION;
442 }
443
444 OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
445         OicSecCrl_t *crl, OCProvisionResultCB resultCallback)
446 {
447     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
448     VERIFY_NON_NULL(TAG, crl, ERROR,  OC_STACK_INVALID_PARAM);
449     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
450
451     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
452     if (!secPayload)
453     {
454         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
455         return OC_STACK_NO_MEMORY;
456     }
457
458     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
459     secPayload->securityData = BinToCrlJSON(crl);
460     if (NULL == secPayload->securityData)
461     {
462         OICFree(secPayload);
463         OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
464         return OC_STACK_NO_MEMORY;
465     }
466     OIC_LOG_V(INFO, TAG, "CRL : %s", secPayload->securityData);
467
468     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
469     if(!PMGenerateQuery(true,
470                         selectedDeviceInfo->endpoint.addr,
471                         selectedDeviceInfo->securePort,
472                         selectedDeviceInfo->connType,
473                         query, sizeof(query), OIC_RSRC_CRL_URI))
474     {
475         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
476         OICFree(secPayload->securityData);
477         OICFree(secPayload);
478         return OC_STACK_ERROR;
479     }
480     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
481
482     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
483     cbData.cb = &SRPProvisionCRLCB;
484     CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t));
485     if (crlData == NULL)
486     {
487         OICFree(secPayload->securityData);
488         OICFree(secPayload);
489         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
490         return OC_STACK_NO_MEMORY;
491     }
492
493     crlData->deviceInfo = selectedDeviceInfo;
494     crlData->resultCallback = resultCallback;
495     crlData->numOfResults=0;
496     crlData->ctx = ctx;
497
498     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
499     if (crlData->resArr == NULL)
500     {
501         OICFree(secPayload->securityData);
502         OICFree(secPayload);
503         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
504         return OC_STACK_NO_MEMORY;
505     }
506
507     cbData.context = (void *)crlData;
508     cbData.cd = NULL;
509     OCMethod method = OC_REST_POST;
510     OCDoHandle handle = NULL;
511     OIC_LOG(DEBUG, TAG, "Sending CRL info to resource server");
512
513     OCStackResult ret = OCDoResource(&handle, method, query,
514             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
515             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
516
517     if (ret != OC_STACK_OK)
518     {
519         OICFree(crlData->resArr);
520         OICFree(crlData);
521     }
522
523     return ret;
524 }
525
526 /**
527  * Internal function for handling credential generation and sending cretificate credential.
528  *
529  * @param[in] cred Instance of cred resource.
530  * @param[in] deviceInfo information about device to which credential is to be provisioned.
531  * @param[in] responseHandler callbak called by OC stack when request API receives response.
532  * @return  OC_STACK_OK in case of success and other value otherwise.
533  */
534 static OCStackResult provisionCertCred(const OicSecCred_t *cred,
535         const OCProvisionDev_t *deviceInfo, CertData_t *certData,
536         OCClientResponseHandler responseHandler)
537 {
538     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
539     if(!secPayload)
540     {
541         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
542         return OC_STACK_NO_MEMORY;
543     }
544     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
545     secPayload->securityData = BinToCredJSON(cred);
546
547     if (NULL == secPayload->securityData)
548     {
549         OICFree(secPayload);
550         OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
551         return OC_STACK_NO_MEMORY;
552     }
553
554     OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
555     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
556     if(!PMGenerateQuery(true,
557                         deviceInfo->endpoint.addr,
558                         deviceInfo->securePort,
559                         deviceInfo->connType,
560                         query, sizeof(query), OIC_RSRC_CRED_URI))
561     {
562         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
563         OICFree(secPayload->securityData);
564         OICFree(secPayload);
565         return OC_STACK_ERROR;
566     }
567     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
568
569     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
570     cbData.cb = responseHandler;
571     cbData.context = (void *) certData;
572     cbData.cd = NULL;
573
574     OCDoHandle handle = NULL;
575     OCMethod method = OC_REST_POST;
576     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
577             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
578     OIC_LOG_V(INFO, TAG, "OCDoResource::Certificate provisioning returned : %d",ret);
579     if (ret != OC_STACK_OK)
580     {
581         OIC_LOG(ERROR, TAG, "OCStack resource error");
582     }
583
584     return ret;
585 }
586
587 /**
588  * Callback handler for handling callback of certificate provisioning device.
589  *
590  * @param[in] ctx             ctx value passed to callback from calling function.
591  * @param[in] UNUSED          handle to an invocation
592  * @param[in] clientResponse  Response from queries to remote servers.
593  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
594  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
595  */
596 static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
597                                                        OCClientResponse *clientResponse)
598 {
599     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
600     CertData_t *certData = (CertData_t *) ctx;
601     (void)UNUSED;
602
603     OCProvisionResultCB resultCallback = certData->resultCallback;
604     OIC_LOG(INFO, TAG, "provisionCertCred called");
605     if (clientResponse)
606     {
607         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
608         {
609             registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CREATED);
610             ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
611                                                     certData->resArr,
612                                                     false);
613              OICFree(certData->resArr);
614              OICFree(certData);
615              return OC_STACK_DELETE_TRANSACTION;
616         }
617
618     }
619     OIC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
620     registerResultForCertProvisioning(certData, OC_STACK_ERROR);
621     ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
622                                             certData->resArr,
623                                             true);
624     OICFree(certData->resArr);
625     OICFree(certData);
626     return OC_STACK_DELETE_TRANSACTION;
627 }
628 #endif // __WITH_X509__
629
630 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
631                                       const OCProvisionDev_t *pDev1,
632                                       const OCProvisionDev_t *pDev2,
633                                       OCProvisionResultCB resultCallback)
634 {
635     VERIFY_NON_NULL(TAG, pDev1, ERROR,  OC_STACK_INVALID_PARAM);
636     if (SYMMETRIC_PAIR_WISE_KEY == type)
637     {
638         VERIFY_NON_NULL(TAG, pDev2, ERROR,  OC_STACK_INVALID_PARAM);
639     }
640     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
641
642     if (SYMMETRIC_PAIR_WISE_KEY == type &&
643        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
644     {
645         OIC_LOG(INFO, TAG, "Invalid key size");
646         return OC_STACK_INVALID_PARAM;
647     }
648
649     OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
650
651     if (SYMMETRIC_PAIR_WISE_KEY == type)
652     {
653         bool linkExisits = true;
654         OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
655
656         if (res != OC_STACK_OK)
657         {
658             OIC_LOG(ERROR, TAG, "Internal error occured");
659             return res;
660         }
661         if (linkExisits)
662         {
663             OIC_LOG(ERROR, TAG, "Link already exists");
664             return OC_STACK_INVALID_PARAM;
665         }
666     }
667
668     OicUuid_t provTooldeviceID =   {{0,}};
669     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
670     {
671         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
672         return OC_STACK_ERROR;
673     }
674     OIC_LOG(INFO, TAG, "retrieved deviceid");
675     switch (type)
676     {
677         case SYMMETRIC_PAIR_WISE_KEY:
678         {
679             const OCProvisionDev_t *firstDevice = pDev1;
680             const OCProvisionDev_t *secondDevice = pDev2;
681
682             OicSecCred_t *firstCred = NULL;
683             OicSecCred_t *secondCred = NULL;
684             OCStackResult res = PMGeneratePairWiseCredentials(type, keySize, &provTooldeviceID,
685                     &firstDevice->doxm->deviceID, &secondDevice->doxm->deviceID,
686                     &firstCred, &secondCred);
687             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
688             OIC_LOG(INFO, TAG, "Credentials generated successfully");
689             CredentialData_t *credData =
690                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
691             if (NULL == credData)
692             {
693                 OICFree(firstCred);
694                 OICFree(secondCred);
695                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
696                 return OC_STACK_NO_MEMORY;
697             }
698             credData->deviceInfo1 = firstDevice;
699             credData->deviceInfo2 = secondDevice;
700             credData->credInfo = secondCred;
701             credData->ctx = ctx;
702             credData->credInfoFirst = firstCred;
703             credData->numOfResults = 0;
704             credData->resultCallback = resultCallback;
705             // first call to provision creds to device1.
706             // second call to provision creds to device2.
707             int noOfRiCalls = 2;
708             credData->resArr =
709                 (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
710             if (NULL == credData->resArr)
711             {
712                 OICFree(firstCred);
713                 OICFree(secondCred);
714                 OICFree(credData);
715                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
716                 return OC_STACK_NO_MEMORY;
717             }
718             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
719             if (OC_STACK_OK != res)
720             {
721                 DeleteCredList(firstCred);
722                 DeleteCredList(secondCred);
723                 OICFree(credData->resArr);
724                 OICFree(credData);
725             }
726             OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
727             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
728             return res;
729         }
730 #ifdef __WITH_X509__
731         case SIGNED_ASYMMETRIC_KEY:
732         {
733             const OCProvisionDev_t *firstDevice = pDev1;
734             OicSecCred_t *cred = NULL;
735             OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID,
736                                                                 &firstDevice->doxm->deviceID,&cred);
737             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
738             OIC_LOG(INFO, TAG, "Certificate credentials generated successfully");
739             CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
740             if (NULL == certData)
741             {
742                 OICFree(cred);
743                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
744                 return OC_STACK_NO_MEMORY;
745             }
746
747             certData->deviceInfo = firstDevice;
748             certData->ctx = ctx;
749             certData->credInfo = cred;
750             certData->numOfResults = 0;
751             certData->resultCallback = resultCallback;
752
753             certData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
754             if (NULL == certData->resArr)
755             {
756                 DeleteCredList(cred);
757                 OICFree(certData);
758                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
759                 return OC_STACK_NO_MEMORY;
760             }
761
762             res = provisionCertCred(cred, firstDevice, certData, &provisionCertCB);
763             if (OC_STACK_OK != res)
764             {
765                 OICFree(certData->resArr);
766                 OICFree(certData);
767             }
768             DeleteCredList(cred);
769             OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
770
771             return res;
772         }
773 #endif
774         default:
775         {
776             OIC_LOG(ERROR, TAG, "Invalid option.");
777             return OC_STACK_INVALID_PARAM;
778         }
779     }
780     return OC_STACK_ERROR;
781 }
782
783 /**
784  * Internal Function to store results in result array during ACL provisioning.
785  */
786 static void registerResultForACLProvisioning(ACLData_t *aclData,
787                                              OCStackResult stackresult)
788 {
789    OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
790                        aclData->numOfResults);
791    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
792           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
793    aclData->resArr[(aclData->numOfResults)].res = stackresult;
794    ++(aclData->numOfResults);
795 }
796
797 /**
798  * Callback handler of SRPProvisionACL.
799  *
800  * @param[in] ctx             ctx value passed to callback from calling function.
801  * @param[in] UNUSED          handle to an invocation
802  * @param[in] clientResponse  Response from queries to remote servers.
803  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
804  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
805  */
806 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
807                                                   OCClientResponse *clientResponse)
808 {
809     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
810     (void)UNUSED;
811     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
812     ACLData_t *aclData = (ACLData_t*)ctx;
813     OCProvisionResultCB resultCallback = aclData->resultCallback;
814
815     if (clientResponse)
816     {
817         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
818         {
819             registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CREATED);
820             ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
821                                                     aclData->resArr,
822                                                     false);
823              OICFree(aclData->resArr);
824              OICFree(aclData);
825              return OC_STACK_DELETE_TRANSACTION;
826         }
827     }
828     registerResultForACLProvisioning(aclData, OC_STACK_ERROR);
829     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
830                                             aclData->resArr,
831                                             true);
832     OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
833     OICFree(aclData->resArr);
834     OICFree(aclData);
835     return OC_STACK_DELETE_TRANSACTION;
836 }
837
838 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
839         OicSecAcl_t *acl, OCProvisionResultCB resultCallback)
840 {
841     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
842     VERIFY_NON_NULL(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
843     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
844
845     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
846     if(!secPayload)
847     {
848         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
849         return OC_STACK_NO_MEMORY;
850     }
851     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
852     size_t size = 0;
853     if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData1, &size))
854     {
855         OCPayloadDestroy((OCPayload *)secPayload);
856         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
857         return OC_STACK_NO_MEMORY;
858     }
859     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
860     if(!PMGenerateQuery(true,
861                         selectedDeviceInfo->endpoint.addr,
862                         selectedDeviceInfo->securePort,
863                         selectedDeviceInfo->connType,
864                         query, sizeof(query), OIC_RSRC_ACL_URI))
865     {
866         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
867         return OC_STACK_ERROR;
868     }
869     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
870
871     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
872     cbData.cb = &SRPProvisionACLCB;
873     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
874     if (aclData == NULL)
875     {
876         OCPayloadDestroy((OCPayload *)secPayload);
877         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
878         return OC_STACK_NO_MEMORY;
879     }
880     aclData->deviceInfo = selectedDeviceInfo;
881     aclData->resultCallback = resultCallback;
882     aclData->numOfResults=0;
883     aclData->ctx = ctx;
884     // call to provision ACL to device1.
885     int noOfRiCalls = 1;
886     aclData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
887     if (aclData->resArr == NULL)
888     {
889         OICFree(aclData);
890         OCPayloadDestroy((OCPayload *)secPayload);
891         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
892         return OC_STACK_NO_MEMORY;
893     }
894     cbData.context = (void *)aclData;
895     cbData.cd = NULL;
896     OCMethod method = OC_REST_POST;
897     OCDoHandle handle = NULL;
898     OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
899     OCStackResult ret = OCDoResource(&handle, method, query,
900             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
901             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
902     if (ret != OC_STACK_OK)
903     {
904         OICFree(aclData->resArr);
905         OICFree(aclData);
906     }
907     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
908     return OC_STACK_OK;
909 }
910
911 /**
912  * Internal Function to store results in result array during Direct-Pairing provisioning.
913  */
914 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
915                                              OCStackResult stackresult)
916 {
917    OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning pconfData->numOfResults is %d\n",
918                        pconfData->numOfResults);
919    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
920           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
921    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
922    ++(pconfData->numOfResults);
923 }
924
925 /**
926  * Callback handler of SRPProvisionDirectPairing.
927  *
928  * @param[in] ctx             ctx value passed to callback from calling function.
929  * @param[in] UNUSED          handle to an invocation
930  * @param[in] clientResponse  Response from queries to remote servers.
931  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
932  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
933  */
934 static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
935                                                   OCClientResponse *clientResponse)
936 {
937     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
938     (void)UNUSED;
939     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
940     PconfData_t *pconfData = (PconfData_t*)ctx;
941     OCProvisionResultCB resultCallback = pconfData->resultCallback;
942
943     if (clientResponse)
944     {
945         if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
946         {
947             registerResultForDirectPairingProvisioning(pconfData, OC_STACK_RESOURCE_CREATED);
948             ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
949                                                     pconfData->resArr,
950                                                     false);
951              OICFree(pconfData->resArr);
952              OICFree(pconfData);
953              return OC_STACK_DELETE_TRANSACTION;
954         }
955     }
956     registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
957     ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
958                                             pconfData->resArr,
959                                             true);
960     OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
961     OICFree(pconfData->resArr);
962     OICFree(pconfData);
963     return OC_STACK_DELETE_TRANSACTION;
964 }
965
966 OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
967         OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
968 {
969     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
970     VERIFY_NON_NULL(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
971     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
972
973     // check direct-pairing capability
974     if (true != selectedDeviceInfo->doxm->dpc)
975     {
976         OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
977         return OC_STACK_UNAUTHORIZED_REQ;
978     }
979
980     OicUuid_t provTooldeviceID =   {.id={0}};
981     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
982     {
983         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
984         return OC_STACK_ERROR;
985     }
986     memcpy(&pconf->rowner, &provTooldeviceID, sizeof(OicUuid_t));
987
988     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
989     if(!secPayload)
990     {
991         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
992         return OC_STACK_NO_MEMORY;
993     }
994     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
995     secPayload->securityData = BinToPconfJSON(pconf);
996     if(NULL == secPayload->securityData)
997     {
998         OICFree(secPayload);
999         OIC_LOG(ERROR, TAG, "Failed to BinToPconfJSON");
1000         return OC_STACK_NO_MEMORY;
1001     }
1002     OIC_LOG_V(INFO, TAG, "PCONF : %s", secPayload->securityData);
1003
1004     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1005     if(!PMGenerateQuery(true,
1006                         selectedDeviceInfo->endpoint.addr,
1007                         selectedDeviceInfo->securePort,
1008                         selectedDeviceInfo->connType,
1009                         query, sizeof(query), OIC_RSRC_PCONF_URI))
1010     {
1011         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
1012         return OC_STACK_ERROR;
1013     }
1014     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1015
1016     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1017     cbData.cb = &SRPProvisionDirectPairingCB;
1018     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
1019     if (NULL == pconfData)
1020     {
1021         OICFree(secPayload->securityData);
1022         OICFree(secPayload);
1023         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1024         return OC_STACK_NO_MEMORY;
1025     }
1026     pconfData->deviceInfo = selectedDeviceInfo;
1027     pconfData->resultCallback = resultCallback;
1028     pconfData->numOfResults=0;
1029     pconfData->ctx = ctx;
1030     // call to provision PCONF to device1.
1031     int noOfRiCalls = 1;
1032     pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1033     if (NULL == pconfData->resArr)
1034     {
1035         OICFree(pconfData);
1036         OICFree(secPayload->securityData);
1037         OICFree(secPayload);
1038         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1039         return OC_STACK_NO_MEMORY;
1040     }
1041     cbData.context = (void *)pconfData;
1042     cbData.cd = NULL;
1043     OCMethod method = OC_REST_POST;
1044     OCDoHandle handle = NULL;
1045     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
1046     OCStackResult ret = OCDoResource(&handle, method, query,
1047             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1048             selectedDeviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1049     if (OC_STACK_OK != ret)
1050     {
1051         OICFree(pconfData->resArr);
1052         OICFree(pconfData);
1053     }
1054     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1055     return OC_STACK_OK;
1056 }
1057
1058 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
1059 {
1060     if (unlinkData)
1061     {
1062         OICFree(unlinkData->unlinkDev);
1063         OICFree(unlinkData->unlinkRes);
1064         OICFree(unlinkData);
1065     }
1066 }
1067
1068 static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResult stackresult,
1069                                            IdxUnlinkRes_t idx)
1070 {
1071     if (NULL != unlinkData)
1072     {
1073         OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
1074                             unlinkData->numOfResults);
1075         OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
1076
1077         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
1078
1079         // Set result in the result array according to the position (devNum).
1080         if (idx != IDX_DB_UPDATE_RES)
1081         {
1082             memcpy(pUuid->id, unlinkData->unlinkDev[idx].doxm->deviceID.id, sizeof(pUuid->id));
1083         }
1084         else
1085         {   // When deivce ID is 000... this means it's the result of database update.
1086             memset(pUuid->id, 0, sizeof(pUuid->id));
1087         }
1088         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
1089         ++(unlinkData->numOfResults);
1090         OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
1091     }
1092 }
1093
1094 static OCStackResult SendDeleteCredentialRequest(void* ctx,
1095                                                  OCClientResponseHandler respHandler,
1096                                                  const OCProvisionDev_t* revokedDev,
1097                                                  const OCProvisionDev_t* destDev)
1098 {
1099     OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
1100
1101     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1102     {
1103         return OC_STACK_INVALID_PARAM;
1104     }
1105
1106     char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(revokedDev->doxm->deviceID.id)) + 1] = {};
1107     uint32_t base64Len = 0;
1108     if (B64_OK != b64Encode(revokedDev->doxm->deviceID.id, sizeof(revokedDev->doxm->deviceID.id),
1109                            base64Buff, sizeof(base64Buff), &base64Len))
1110     {
1111         OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to base64 encoding");
1112         return OC_STACK_ERROR;
1113     }
1114
1115     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1116     int snRet = 0;
1117                     //coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
1118     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
1119                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECT_NAME, base64Buff);
1120     if (snRet < 0)
1121     {
1122         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
1123         return OC_STACK_ERROR;
1124     }
1125     else if ((size_t)snRet >= sizeof(reqBuf))
1126     {
1127         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
1128         return OC_STACK_ERROR;
1129     }
1130
1131     OCCallbackData cbData;
1132     memset(&cbData, 0, sizeof(cbData));
1133     cbData.context = ctx;
1134     cbData.cb = respHandler;
1135     cbData.cd = NULL;
1136     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1137
1138     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1139
1140     OCStackResult ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1141                                      &destDev->endpoint, NULL,
1142                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1143     if (OC_STACK_OK != ret)
1144     {
1145         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1146     }
1147     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1148
1149     return ret;
1150 }
1151
1152 /**
1153  * Callback handler of unlink second device.
1154  *
1155  * @param[in] ctx             ctx value passed to callback from calling function.
1156  * @param[in] handle          handle to an invocation
1157  * @param[in] clientResponse  Response from queries to remote servers.
1158  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1159  *          OC_STACK_KEEP_TRANSACTION to keep it.
1160  */
1161 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1162         OCClientResponse *clientResponse)
1163 {
1164     (void) handle;
1165     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1166     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1167     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1168
1169     if (clientResponse)
1170     {
1171         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1172         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1173
1174         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1175         {
1176             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1177         }
1178         else
1179         {
1180             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1181             unlinkData->resultCallback(unlinkData->ctx,
1182                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1183             goto error;
1184         }
1185     }
1186     else
1187     {
1188         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1189                                        IDX_SECOND_DEVICE_RES);
1190         unlinkData->resultCallback(unlinkData->ctx,
1191                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1192         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1193         goto error;
1194     }
1195
1196     //Update provisioning DB when succes case.
1197     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1198                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1199     {
1200         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1201         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1202         unlinkData->resultCallback(unlinkData->ctx,
1203                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1204         goto error;
1205     }
1206     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1207                                false);
1208
1209 error:
1210     DeleteUnlinkData_t(unlinkData);
1211     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1212     return OC_STACK_DELETE_TRANSACTION;
1213
1214 }
1215
1216 /**
1217  * Callback handler of unlink first device.
1218  *
1219  * @param[in] ctx             ctx value passed to callback from calling function.
1220  * @param[in] handle          handle to an invocation
1221  * @param[in] clientResponse  Response from queries to remote servers.
1222  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1223  *          OC_STACK_KEEP_TRANSACTION to keep it.
1224  */
1225 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1226         OCClientResponse *clientResponse)
1227 {
1228     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1229     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1230     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1231     (void) handle;
1232
1233     if (clientResponse)
1234     {
1235         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1236         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1237
1238         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1239         {
1240             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1241
1242             // Second revocation request to second device.
1243             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1244                                                     &unlinkData->unlinkDev[0],
1245                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1246             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1247             if (OC_STACK_OK != res)
1248             {
1249                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1250                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1251                                                 IDX_SECOND_DEVICE_RES);
1252                  unlinkData->resultCallback(unlinkData->ctx,
1253                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1254                  goto error;
1255             }
1256             else
1257             {
1258                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1259                 return OC_STACK_DELETE_TRANSACTION;
1260             }
1261         }
1262         else
1263         {
1264             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1265
1266             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1267                                             unlinkData->unlinkRes, true);
1268             goto error;
1269         }
1270     }
1271     else
1272     {
1273         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1274         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1275                                        IDX_FIRST_DEVICE_RES );
1276         unlinkData->resultCallback(unlinkData->ctx,
1277                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1278                                    true);
1279         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1280     }
1281
1282 error:
1283     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1284     DeleteUnlinkData_t(unlinkData);
1285     return OC_STACK_DELETE_TRANSACTION;
1286 }
1287
1288 /*
1289 * Function to unlink devices.
1290 * This function will remove the credential & relationship between the two devices.
1291 *
1292 * @param[in] ctx Application context would be returned in result callback
1293 * @param[in] pTargetDev1 first device information to be unlinked.
1294 * @param[in] pTargetDev2 second device information to be unlinked.
1295 * @param[in] resultCallback callback provided by API user, callback will be called when
1296 *            device unlink is finished.
1297  * @return  OC_STACK_OK in case of success and other value otherwise.
1298 */
1299 OCStackResult SRPUnlinkDevices(void* ctx,
1300                                const OCProvisionDev_t* pTargetDev1,
1301                                const OCProvisionDev_t* pTargetDev2,
1302                                OCProvisionResultCB resultCallback)
1303 {
1304     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1305
1306     if (!pTargetDev1 || !pTargetDev2 || !resultCallback)
1307     {
1308         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1309         return OC_STACK_INVALID_PARAM;
1310     }
1311     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1312     PMPrintOCProvisionDev(pTargetDev1);
1313     PMPrintOCProvisionDev(pTargetDev2);
1314
1315     // Mark the link status stale
1316     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1317     if (OC_STACK_OK != res)
1318     {
1319         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1320         return res;
1321     }
1322
1323     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1324     VERIFY_NON_NULL(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1325
1326     //Initialize unlink data
1327     unlinkData->ctx = ctx;
1328     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1329     if (NULL == unlinkData->unlinkDev)
1330     {
1331         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1332         res = OC_STACK_NO_MEMORY;
1333         goto error;
1334     }
1335
1336     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1337     if (NULL == unlinkData->unlinkRes)
1338     {
1339         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1340         res = OC_STACK_NO_MEMORY;
1341         goto error;
1342     }
1343
1344     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1345     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1346
1347     unlinkData->numOfResults = 0;
1348     unlinkData->resultCallback = resultCallback;
1349
1350     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1351                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1352     if (OC_STACK_OK != res)
1353     {
1354         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1355         goto error;
1356     }
1357
1358     return res;
1359
1360 error:
1361     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1362     DeleteUnlinkData_t(unlinkData);
1363     return res;
1364 }
1365
1366 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1367 {
1368     if (pRemoveData)
1369     {
1370         OICFree(pRemoveData->revokeTargetDev);
1371         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1372         OICFree(pRemoveData->removeRes);
1373         OICFree(pRemoveData);
1374     }
1375 }
1376
1377 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1378                                           OCStackResult stackresult, bool hasError)
1379 {
1380     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
1381                          removeData->numOfResults + 1);
1382     if (pLinkedDevId)
1383     {
1384         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1385                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1386     }
1387     else
1388     {
1389         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1390                0, sizeof(pLinkedDevId->id) );
1391     }
1392     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1393     removeData->hasError = hasError;
1394     ++(removeData->numOfResults);
1395
1396     // If we get suffcient result from linked devices, we have to call user callback and do free
1397     if (removeData->sizeOfResArray == removeData->numOfResults)
1398     {
1399         if(!removeData->hasError)
1400         {
1401             // Remove device info from prvisioning database
1402             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1403             {
1404                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1405                 removeData->hasError = true;
1406             }
1407         }
1408         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1409                                    removeData->hasError);
1410         DeleteRemoveData_t(removeData);
1411     }
1412  }
1413
1414 /**
1415  * Callback handler of unlink first device.
1416  *
1417  * @param[in] ctx             ctx value passed to callback from calling function.
1418  * @param[in] handle          handle to an invocation
1419  * @param[in] clientResponse  Response from queries to remote servers.
1420  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1421  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1422  */
1423 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1424         OCClientResponse *clientResponse)
1425 {
1426     //Update the delete credential into delete device context
1427     //Save the deleted status in delDevCtx
1428     (void)handle;
1429     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1430     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1431     OCStackResult res = OC_STACK_ERROR;
1432
1433     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1434     if(removeData)
1435     {
1436         if (clientResponse)
1437         {
1438             OicUuid_t revDevUuid = {.id={0}};
1439             if(UUID_LENGTH == clientResponse->identity.id_length)
1440             {
1441                 memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1442                 if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1443                 {
1444                     res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1445                     if (OC_STACK_OK != res)
1446                     {
1447                         OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1448                                registerResultForRemoveDevice(removeData, &revDevUuid,
1449                                OC_STACK_INCONSISTENT_DB, true);
1450
1451                         return OC_STACK_DELETE_TRANSACTION;
1452                     }
1453
1454                     registerResultForRemoveDevice(removeData, &revDevUuid,
1455                                                   OC_STACK_RESOURCE_DELETED, false);
1456                 }
1457                 else
1458                 {
1459                     registerResultForRemoveDevice(removeData, &revDevUuid,
1460                                                   clientResponse->result, true);
1461                     OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1462                 }
1463             }
1464             else
1465             {
1466                 OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1467                          clientResponse->devAddr.addr, clientResponse->devAddr.port);
1468
1469                 if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1470                 {
1471                     /**
1472                       * Since server's credential was deleted,
1473                       * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1474                       */
1475
1476                     OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1477                     registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1478                 }
1479                 else
1480                 {
1481                     registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1482                 }
1483             }
1484         }
1485         else
1486         {
1487             registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1488             OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1489         }
1490     }
1491     else
1492     {
1493         OIC_LOG(WARNING, TAG, "SRPRemoveDevices received null context");
1494     }
1495
1496     return OC_STACK_DELETE_TRANSACTION;
1497 }
1498
1499 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
1500                                                  OCProvisionDev_t* pOwnedDevList,
1501                                                  OCUuidList_t* pLinkedUuidList,
1502                                                  OCProvisionDev_t** ppLinkedDevList,
1503                                                  size_t *numOfLinkedDev)
1504 {
1505     // pOwnedDevList could be NULL. It means no alived and owned device now.
1506     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
1507         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
1508     {
1509         return OC_STACK_INVALID_PARAM;
1510     }
1511
1512     size_t cnt = 0;
1513     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
1514     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
1515     {
1516         // Mark the link status stale.
1517         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
1518         if (OC_STACK_OK != res)
1519         {
1520             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1521             return OC_STACK_INCONSISTENT_DB;
1522         }
1523
1524         if (pOwnedDevList)
1525         {
1526             // If this linked device is alive (power-on), add the deivce to the list.
1527             OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
1528             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
1529             {
1530                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
1531                 {
1532                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
1533                     if (NULL == targetDev)
1534                     {
1535                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
1536                         return OC_STACK_NO_MEMORY;
1537                     }
1538
1539                     LL_PREPEND(*ppLinkedDevList, targetDev);
1540                     cnt++;
1541                     break;
1542                 }
1543             }
1544         }
1545     }
1546     *numOfLinkedDev = cnt;
1547     return OC_STACK_OK;
1548 }
1549
1550 /*
1551 * Function to device revocation
1552 * This function will remove credential of target device from all devices in subnet.
1553 *
1554 * @param[in] ctx Application context would be returned in result callback
1555 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
1556 * @param[in] pTargetDev Device information to be revoked.
1557 * @param[in] resultCallback callback provided by API user, callback will be called when
1558 *            credential revocation is finished.
1559 * @return  OC_STACK_OK in case of success and other value otherwise.
1560 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
1561 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
1562 */
1563 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
1564                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
1565 {
1566     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
1567
1568     if (!pTargetDev || !resultCallback || 0 == waitTimeForOwnedDeviceDiscovery)
1569     {
1570         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
1571         return OC_STACK_INVALID_PARAM;
1572     }
1573
1574     // Declare variables in here to handle error cases with goto statement.
1575     OCProvisionDev_t* pOwnedDevList = NULL;
1576     OCProvisionDev_t* pLinkedDevList = NULL;
1577     RemoveData_t* removeData = NULL;
1578
1579     //1. Find all devices that has a credential of the revoked device
1580     OCUuidList_t* pLinkedUuidList = NULL;
1581     size_t numOfDevices = 0;
1582     OCStackResult res = OC_STACK_ERROR;
1583     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
1584     if (OC_STACK_OK != res)
1585     {
1586         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
1587         return res;
1588     }
1589     // if there is no related device, we can skip further process.
1590     if (0 == numOfDevices)
1591     {
1592         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
1593         res = OC_STACK_CONTINUE;
1594         goto error;
1595     }
1596
1597     //2. Find owned device from the network
1598     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
1599     if (OC_STACK_OK != res)
1600     {
1601         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
1602         goto error;
1603     }
1604
1605     //3. Make a list of devices to send DELETE credential request
1606     //   by comparing owned devices from provisioning database with mutlicast discovery result.
1607     size_t numOfLinkedDev = 0;
1608     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
1609                                       &pLinkedDevList, &numOfLinkedDev);
1610     if (OC_STACK_OK != res)
1611     {
1612         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
1613         goto error;
1614     }
1615     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
1616     {                       // So we don't have to send request message.
1617         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
1618         res = OC_STACK_CONTINUE;
1619         goto error;
1620     }
1621
1622     // 4. Prepare RemoveData Context data.
1623     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
1624     if (!removeData)
1625     {
1626         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
1627         res = OC_STACK_NO_MEMORY;
1628         goto error;
1629     }
1630
1631     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
1632     if (!removeData->revokeTargetDev)
1633     {
1634         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
1635         res = OC_STACK_NO_MEMORY;
1636         goto error;
1637     }
1638
1639     removeData->removeRes =
1640         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
1641     if (!removeData->removeRes)
1642     {
1643         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
1644         res = OC_STACK_NO_MEMORY;
1645         goto error;
1646     }
1647
1648     removeData->ctx = ctx;
1649     removeData->linkedDevList = pLinkedDevList;
1650     removeData->resultCallback = resultCallback;
1651     removeData->numOfResults = 0;
1652     removeData->sizeOfResArray = numOfLinkedDev;
1653     removeData->hasError = false;
1654
1655     // 5. Send DELETE credential request to linked devices.
1656     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
1657     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
1658     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
1659     {
1660         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
1661                                            removeData->revokeTargetDev, curDev);
1662         if (OC_STACK_OK != res)
1663         {
1664             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
1665                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
1666         }
1667         else
1668         {
1669             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
1670         }
1671     }
1672
1673     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
1674     PMDeleteDeviceList(pOwnedDevList);
1675     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
1676
1677     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
1678
1679 error:
1680     PDMDestoryOicUuidLinkList(pLinkedUuidList);
1681     PMDeleteDeviceList(pOwnedDevList);
1682     PMDeleteDeviceList(pLinkedDevList);
1683     if (removeData)
1684     {
1685         OICFree(removeData->revokeTargetDev);
1686         OICFree(removeData->removeRes);
1687         OICFree(removeData);
1688     }
1689     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
1690     return res;
1691 }