Cloud Client
[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 "iotivity_config.h"
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdint.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27
28 #include "ocprovisioningmanager.h"
29 #include "secureresourceprovider.h"
30 #include "logger.h"
31 #include "oic_malloc.h"
32 #include "aclresource.h"
33 #include "pstatresource.h"
34 #include "srmresourcestrings.h"
35 #include "credresource.h"
36 #include "doxmresource.h"
37 #include "pconfresource.h"
38 #include "credentialgenerator.h"
39 #include "cainterface.h"
40 #include "cJSON.h"
41 #include "pmtypes.h"
42 #include "pmutility.h"
43 #include "provisioningdatabasemanager.h"
44 #include "base64.h"
45 #include "utlist.h"
46 #include "ocpayload.h"
47
48 #ifdef __WITH_X509__
49 #include "crlresource.h"
50 #endif // WITH_X509__
51
52 #define TAG "SRPAPI"
53
54 /**
55  * Macro to verify argument is not equal to NULL.
56  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR,OC_STACK_ERROR);
57  */
58 #define VERIFY_NON_NULL(tag, arg, logLevel, retValue) { if (NULL == (arg)) \
59             { OIC_LOG((logLevel), tag, #arg " is NULL"); return retValue; } }
60
61 /**
62  * Macro to verify success of operation.
63  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR, OC_STACK_ERROR);
64  */
65 #define VERIFY_SUCCESS(tag, op, logLevel, retValue) { if (!(op)) \
66             {OIC_LOG((logLevel), tag, #op " failed!!"); return retValue;} }
67
68 /**
69  * Structure to carry credential data to callback.
70  */
71 typedef struct CredentialData CredentialData_t;
72 struct CredentialData
73 {
74     void *ctx;                                  /**< Pointer to user context.**/
75     const OCProvisionDev_t *deviceInfo1;        /**< Pointer to OCProvisionDev_t.**/
76     const OCProvisionDev_t *deviceInfo2;        /**< Pointer to OCProvisionDev_t.**/
77     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
78     OicSecCred_t *credInfoFirst;                /**< Pointer to OicSecCred_t.**/
79     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
80     OCProvisionResult_t *resArr;                /**< Result array.**/
81     int numOfResults;                           /**< Number of results in result array.**/
82 };
83
84 /**
85  * Structure to carry ACL provision API data to callback.
86  */
87 typedef struct ACLData ACLData_t;
88 struct ACLData
89 {
90     void *ctx;                                  /**< Pointer to user context.**/
91     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
92     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
93     OCProvisionResult_t *resArr;                /**< Result array.**/
94     int numOfResults;                           /**< Number of results in result array.**/
95 };
96
97 // Structure to carry get security resource APIs data to callback.
98 typedef struct GetSecData GetSecData_t;
99 struct GetSecData {
100     void *ctx;
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 /**
108  * Structure to carry PCONF provision API data to callback.
109  */
110 typedef struct PconfData PconfData_t;
111 struct PconfData
112 {
113     void *ctx;                                  /**< Pointer to user context.**/
114     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
115     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
116     OCProvisionResult_t *resArr;                /**< Result array.**/
117     int numOfResults;                           /**< Number of results in result array.**/
118 };
119
120 // Enum type index for unlink callback.
121 typedef enum {
122     IDX_FIRST_DEVICE_RES = 0, // index for resulf of the first device
123     IDX_SECOND_DEVICE_RES,    // index for result of the second device
124     IDX_DB_UPDATE_RES         // index for result of updating provisioning database.
125 } IdxUnlinkRes_t;
126
127 // Structure to carry unlink APIs data to callback.
128 typedef struct UnlinkData UnlinkData_t;
129 struct UnlinkData {
130     void *ctx;
131     OCProvisionDev_t* unlinkDev;             /**< Pointer to OCProvisionDev_t to be unlinked.**/
132     OCProvisionResult_t* unlinkRes;          /**< Result array.**/
133     OCProvisionResultCB resultCallback;      /**< Pointer to result callback.**/
134     int numOfResults;                        /**< Number of results in result array.**/
135 };
136
137 //Example of DELETE cred request -> coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
138 const char * SRP_FORM_DELETE_CREDENTIAL = "coaps://[%s]:%d%s?%s=%s";
139 const char * SRP_FORM_DELETE_CREDENTIAL_TCP = "coaps+tcp://[%s]:%d%s?%s=%s";
140
141 // Structure to carry remove APIs data to callback.
142 typedef struct RemoveData RemoveData_t;
143 struct RemoveData {
144     void *ctx;
145     OCProvisionDev_t* revokeTargetDev;      /**< Device which is going to be revoked..**/
146     OCProvisionDev_t* linkedDevList;        /**< A list of devices which have invalid credential.**/
147     OCProvisionResult_t* removeRes;         /**< Result array.**/
148     OCProvisionResultCB resultCallback;     /**< Pointer to result callback.**/
149     size_t numOfResults;                    /**< Number of results in result array.**/
150     size_t sizeOfResArray;
151     bool hasError;
152 };
153
154 /**
155  * Function prototype
156  */
157 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
158         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
159         OCClientResponseHandler responseHandler);
160
161
162 /**
163  * Internal function to update result in result array.
164  */
165 static void registerResultForCredProvisioning(CredentialData_t *credData,
166                                               OCStackResult stackresult, int cause)
167 {
168
169    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
170    if(1 == cause)
171    {
172        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
173               credData->deviceInfo1->doxm->deviceID.id,UUID_LENGTH);
174    }
175    else
176    {
177        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
178               credData->deviceInfo2->doxm->deviceID.id,UUID_LENGTH);
179    }
180    credData->resArr[(credData->numOfResults)].res = stackresult;
181    ++(credData->numOfResults);
182 }
183
184 /**
185  * Callback handler for handling callback of provisioning device 2.
186  *
187  * @param[in] ctx             ctx value passed to callback from calling function.
188  * @param[in] UNUSED          handle to an invocation
189  * @param[in] clientResponse  Response from queries to remote servers.
190  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
191  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
192  */
193 static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNUSED,
194                                                        OCClientResponse *clientResponse)
195 {
196     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
197     CredentialData_t *credData = (CredentialData_t *) ctx;
198     (void)UNUSED;
199
200     OCProvisionResultCB resultCallback = credData->resultCallback;
201     OIC_LOG(INFO, TAG, "provisionCredentialCB2 called");
202     if (clientResponse)
203     {
204         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
205         {
206             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, 2);
207             OCStackResult res =  PDMLinkDevices(&credData->deviceInfo1->doxm->deviceID,
208                     &credData->deviceInfo2->doxm->deviceID);
209             if (OC_STACK_OK != res)
210             {
211                 OIC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
212                 return OC_STACK_DELETE_TRANSACTION;
213             }
214             OIC_LOG(INFO, TAG, "Link created successfully");
215
216             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
217                                                     credData->resArr,
218                                                     false);
219              OICFree(credData->resArr);
220              OICFree(credData);
221              return OC_STACK_DELETE_TRANSACTION;
222         }
223
224     }
225     OIC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
226     registerResultForCredProvisioning(credData, OC_STACK_ERROR, 2);
227     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
228                                             credData->resArr,
229                                             true);
230     OICFree(credData->resArr);
231     OICFree(credData);
232     return OC_STACK_DELETE_TRANSACTION;
233 }
234
235 /**
236  * Callback handler for handling callback of provisioning device 1.
237  *
238  * @param[in] ctx             ctx value passed to callback from calling function.
239  * @param[in] UNUSED          handle to an invocation
240  * @param[in] clientResponse  Response from queries to remote servers.
241  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
242  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
243  */
244 static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNUSED,
245                                                        OCClientResponse *clientResponse)
246 {
247     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
248     (void)UNUSED;
249     CredentialData_t* credData = (CredentialData_t*) ctx;
250     OICFree(credData->credInfoFirst);
251     const OCProvisionDev_t *deviceInfo = credData->deviceInfo2;
252     OicSecCred_t *credInfo = credData->credInfo;
253     const OCProvisionResultCB resultCallback = credData->resultCallback;
254     if (clientResponse)
255     {
256         if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
257         {
258             // send credentials to second device
259             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED,1);
260             OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData,
261                     provisionCredentialCB2);
262             DeleteCredList(credInfo);
263             if (OC_STACK_OK != res)
264             {
265                 registerResultForCredProvisioning(credData, res,2);
266                 ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
267                                                         credData->resArr,
268                                                         true);
269                 OICFree(credData->resArr);
270                 OICFree(credData);
271                 credData = NULL;
272             }
273         }
274         else
275         {
276             registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
277             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
278                                                     credData->resArr,
279                                                     true);
280             OICFree(credData->resArr);
281             OICFree(credData);
282             credData = NULL;
283         }
284     }
285     else
286     {
287         OIC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
288         registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
289        ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
290                                                      credData->resArr,
291                                                      true);
292         DeleteCredList(credInfo);
293         OICFree(credData->resArr);
294         OICFree(credData);
295         credData = NULL;
296     }
297     return OC_STACK_DELETE_TRANSACTION;
298 }
299
300
301
302 /**
303  * Internal function for handling credential generation and sending credential to resource server.
304  *
305  * @param[in] cred Instance of cred resource.
306  * @param[in] deviceInfo information about device to which credential is to be provisioned.
307  * @param[in] responseHandler callbak called by OC stack when request API receives response.
308  * @return  OC_STACK_OK in case of success and other value otherwise.
309  */
310 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
311         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
312         OCClientResponseHandler responseHandler)
313 {
314     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
315     if (!secPayload)
316     {
317         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
318         return OC_STACK_NO_MEMORY;
319     }
320     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
321     int secureFlag = 0;
322     OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
323                                           &secPayload->payloadSize, secureFlag);
324     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
325     {
326         OCPayloadDestroy((OCPayload *)secPayload);
327         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
328         return OC_STACK_NO_MEMORY;
329     }
330
331     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
332     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
333     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
334     if(!PMGenerateQuery(true,
335                         deviceInfo->endpoint.addr,
336                         deviceInfo->securePort,
337                         deviceInfo->connType,
338                         query, sizeof(query), OIC_RSRC_CRED_URI))
339     {
340         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
341         return OC_STACK_ERROR;
342     }
343     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
344
345     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
346     cbData.cb = responseHandler;
347     cbData.context = (void *) credData;
348     cbData.cd = NULL;
349
350     OCDoHandle handle = NULL;
351     OCMethod method = OC_REST_POST;
352     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
353             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
354     OIC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d",ret);
355     if (ret != OC_STACK_OK)
356     {
357         OIC_LOG(ERROR, TAG, "OCStack resource error");
358         return ret;
359     }
360     return OC_STACK_OK;
361 }
362
363 #if defined(__WITH_X509__) || defined(__WITH_TLS__)
364 /**
365  * Structure to carry certificate data to callback.
366  */
367 typedef struct CertificateData CertData_t;
368 struct CertificateData
369 {
370     void *ctx;                                  /**< Pointer to user context.**/
371     const OCProvisionDev_t *deviceInfo;        /**< Pointer to OCProvisionDev_t.**/
372     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
373     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
374     OCProvisionResult_t *resArr;                /**< Result array.**/
375     int numOfResults;                           /**< Number of results in result array.**/
376 };
377
378 /**
379  * Structure to carry CRL provision API data to callback.
380  */
381 typedef struct CRLData CRLData_t;
382 struct CRLData
383 {
384     void *ctx;                                  /**< Pointer to user context.**/
385     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
386     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
387     OCProvisionResult_t *resArr;                /**< Result array.**/
388     int numOfResults;                           /**< Number of results in result array.**/
389 };
390
391 /**
392  * Internal function to update result in result array.
393  */
394 static void registerResultForCertProvisioning(CertData_t *certData,
395                                               OCStackResult stackresult)
396 {
397
398    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
399    memcpy(certData->resArr[(certData->numOfResults)].deviceId.id,
400           certData->deviceInfo->doxm->deviceID.id,UUID_LENGTH);
401    certData->resArr[(certData->numOfResults)].res = stackresult;
402    ++(certData->numOfResults);
403 }
404
405 /**
406  * Internal Function to store results in result array during ACL provisioning.
407  */
408 static void registerResultForCRLProvisioning(CRLData_t *crlData,
409                                              OCStackResult stackresult)
410 {
411    OIC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n",
412                        crlData->numOfResults);
413    memcpy(crlData->resArr[(crlData->numOfResults)].deviceId.id,
414           crlData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
415    crlData->resArr[(crlData->numOfResults)].res = stackresult;
416    ++(crlData->numOfResults);
417 }
418
419
420 /**
421  * Callback handler of SRPProvisionCRL.
422  *
423  * @param[in] ctx             ctx value passed to callback from calling function.
424  * @param[in] UNUSED          handle to an invocation
425  * @param[in] clientResponse  Response from queries to remote servers.
426  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
427  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
428  */
429 static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED,
430                                                   OCClientResponse *clientResponse)
431 {
432     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB.");
433     (void)UNUSED;
434     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
435     CRLData_t *crlData = (CRLData_t*)ctx;
436     OCProvisionResultCB resultCallback = crlData->resultCallback;
437
438     if (clientResponse)
439     {
440         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
441         {
442             registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CHANGED);
443             ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
444                                                     crlData->resArr,
445                                                     false);
446              OICFree(crlData->resArr);
447              OICFree(crlData);
448              return OC_STACK_DELETE_TRANSACTION;
449         }
450     }
451     registerResultForCRLProvisioning(crlData, OC_STACK_ERROR);
452     ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
453                                             crlData->resArr,
454                                             true);
455     OIC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse");
456     OICFree(crlData->resArr);
457     OICFree(crlData);
458     return OC_STACK_DELETE_TRANSACTION;
459 }
460
461 OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
462         OicSecCrl_t *crl, OCProvisionResultCB resultCallback)
463 {
464     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
465     VERIFY_NON_NULL(TAG, crl, ERROR,  OC_STACK_INVALID_PARAM);
466     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
467
468     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
469     if (!secPayload)
470     {
471         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
472         return OC_STACK_NO_MEMORY;
473     }
474
475     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
476     OCStackResult res;
477     res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize, NULL);
478     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
479     {
480         OICFree(secPayload);
481         OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
482         return OC_STACK_NO_MEMORY;
483     }
484     OIC_LOG(DEBUG, TAG, "Created payload for CRL:");
485     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
486
487     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
488     if(!PMGenerateQuery(true,
489                         selectedDeviceInfo->endpoint.addr,
490                         selectedDeviceInfo->securePort,
491                         selectedDeviceInfo->connType,
492                         query, sizeof(query), OIC_RSRC_CRL_URI))
493     {
494         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
495         OCPayloadDestroy((OCPayload *)secPayload);
496         return OC_STACK_ERROR;
497     }
498     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
499
500     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
501     cbData.cb = &SRPProvisionCRLCB;
502     CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t));
503     if (crlData == NULL)
504     {
505         OCPayloadDestroy((OCPayload *)secPayload);
506         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
507         return OC_STACK_NO_MEMORY;
508     }
509
510     crlData->deviceInfo = selectedDeviceInfo;
511     crlData->resultCallback = resultCallback;
512     crlData->numOfResults=0;
513     crlData->ctx = ctx;
514
515     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
516     if (crlData->resArr == NULL)
517     {
518         OCPayloadDestroy((OCPayload *)secPayload);
519         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
520         return OC_STACK_NO_MEMORY;
521     }
522
523     cbData.context = (void *)crlData;
524     cbData.cd = NULL;
525     OCMethod method = OC_REST_POST;
526     OCDoHandle handle = NULL;
527     OIC_LOG(DEBUG, TAG, "Sending CRL info to resource server");
528
529     OCStackResult ret = OCDoResource(&handle, method, query,
530             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
531             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
532
533     if (ret != OC_STACK_OK)
534     {
535         OICFree(crlData->resArr);
536         OICFree(crlData);
537     }
538
539     return ret;
540 }
541
542 /**
543  * Internal function for handling credential generation and sending cretificate credential.
544  *
545  * @param[in] cred Instance of cred resource.
546  * @param[in] deviceInfo information about device to which credential is to be provisioned.
547  * @param[in] responseHandler callbak called by OC stack when request API receives response.
548  * @return  OC_STACK_OK in case of success and other value otherwise.
549  */
550 static OCStackResult provisionCertCred(const OicSecCred_t *cred,
551         const OCProvisionDev_t *deviceInfo, CertData_t *certData,
552         OCClientResponseHandler responseHandler)
553 {
554     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
555     if(!secPayload)
556     {
557         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
558         return OC_STACK_NO_MEMORY;
559     }
560     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
561     int secureFlag = 0;
562     OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
563         &secPayload->payloadSize, secureFlag);
564
565     if ((OC_STACK_OK != res) || (NULL == secPayload->securityData))
566     {
567         OICFree(secPayload);
568         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
569         return OC_STACK_NO_MEMORY;
570     }
571
572     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
573     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
574     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
575     if(!PMGenerateQuery(true,
576                         deviceInfo->endpoint.addr,
577                         deviceInfo->securePort,
578                         deviceInfo->connType,
579                         query, sizeof(query), OIC_RSRC_CRED_URI))
580     {
581         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
582         OCPayloadDestroy((OCPayload *)secPayload);
583         return OC_STACK_ERROR;
584     }
585     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
586
587     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
588     cbData.cb = responseHandler;
589     cbData.context = (void *) certData;
590     cbData.cd = NULL;
591
592     OCDoHandle handle = NULL;
593     OCMethod method = OC_REST_POST;
594     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
595             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
596     OIC_LOG_V(INFO, TAG, "OCDoResource::Certificate provisioning returned : %d",ret);
597     if (ret != OC_STACK_OK)
598     {
599         OIC_LOG(ERROR, TAG, "OCStack resource error");
600     }
601
602     return ret;
603 }
604
605 /**
606  * Callback handler for handling callback of certificate provisioning device.
607  *
608  * @param[in] ctx             ctx value passed to callback from calling function.
609  * @param[in] UNUSED          handle to an invocation
610  * @param[in] clientResponse  Response from queries to remote servers.
611  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
612  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
613  */
614 static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
615                                                        OCClientResponse *clientResponse)
616 {
617     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
618     CertData_t *certData = (CertData_t *) ctx;
619     (void)UNUSED;
620
621     OCProvisionResultCB resultCallback = certData->resultCallback;
622     OIC_LOG(INFO, TAG, "provisionCertCred called");
623     if (clientResponse)
624     {
625         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
626         {
627             registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CHANGED);
628             ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
629                                                     certData->resArr,
630                                                     false);
631              OICFree(certData->resArr);
632              OICFree(certData);
633              return OC_STACK_DELETE_TRANSACTION;
634         }
635
636     }
637     OIC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
638     registerResultForCertProvisioning(certData, OC_STACK_ERROR);
639     ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
640                                             certData->resArr,
641                                             true);
642     OICFree(certData->resArr);
643     OICFree(certData);
644     return OC_STACK_DELETE_TRANSACTION;
645 }
646
647 OCStackResult SRPProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
648         const OCProvisionDev_t *selectedDeviceInfo, OCProvisionResultCB resultCallback)
649 {
650     OIC_LOG(INFO, TAG, "In SRPProvisionTrustCertChain");
651     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
652     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
653     if (SIGNED_ASYMMETRIC_KEY != type || NULL == type)
654     {
655         OIC_LOG(INFO, TAG, "Invalid key type");
656         return OC_STACK_INVALID_PARAM;
657     }
658
659     OicSecCred_t *trustCertChainCred = GetCredResourceDataByCredId(credId);
660     if(NULL == trustCertChainCred)
661     {
662         OIC_LOG(ERROR, TAG, "Can not find matched Trust Cert. Chain.");
663         return OC_STACK_NO_RESOURCE;
664     }
665
666     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
667     if(!secPayload)
668     {
669         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
670         return OC_STACK_NO_MEMORY;
671     }
672     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
673     int secureFlag = 0;
674     if(OC_STACK_OK != CredToCBORPayload(trustCertChainCred, &secPayload->securityData, &secPayload->payloadSize, secureFlag))
675     {
676         OCPayloadDestroy((OCPayload *)secPayload);
677         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
678         return OC_STACK_NO_MEMORY;
679     }
680     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
681     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
682
683     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
684     if(!PMGenerateQuery(true,
685                         selectedDeviceInfo->endpoint.addr,
686                         selectedDeviceInfo->securePort,
687                         selectedDeviceInfo->connType,
688                         query, sizeof(query), OIC_RSRC_CRED_URI))
689     {
690         OIC_LOG(ERROR, TAG, "SRPProvisionTrustCertChain : Failed to generate query");
691         return OC_STACK_ERROR;
692     }
693     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
694
695     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
696     cbData.cb = &provisionCertCB;
697     CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
698     if (NULL == certData)
699     {
700         OICFree(trustCertChainCred);
701         OIC_LOG(ERROR, TAG, "Memory allocation problem");
702         return OC_STACK_NO_MEMORY;
703     }
704     certData->deviceInfo = selectedDeviceInfo;
705     certData->resultCallback = resultCallback;
706     certData->credInfo = trustCertChainCred;
707     certData->numOfResults=0;
708     certData->ctx = ctx;
709
710     int noOfRiCalls = 1;
711     certData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
712     if (certData->resArr == NULL)
713     {
714         DeleteCredList(trustCertChainCred);
715         OICFree(certData);
716         OCPayloadDestroy((OCPayload *)secPayload);
717         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
718         return OC_STACK_NO_MEMORY;
719     }
720     cbData.context = (void *)certData;
721     cbData.cd = NULL;
722     OCMethod method = OC_REST_POST;
723     OCDoHandle handle = NULL;
724     OIC_LOG(DEBUG, TAG, "Sending Cred info to resource server");
725     OCStackResult ret = OCDoResource(&handle, method, query,
726             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
727             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
728     if (ret != OC_STACK_OK)
729     {
730         OICFree(certData->resArr);
731         OICFree(certData);
732     }
733     DeleteCredList(trustCertChainCred);
734
735     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
736     return OC_STACK_OK;
737 }
738
739 OCStackResult SRPSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
740                                             OicEncodingType_t encodingType, uint16_t *credId)
741 {
742     OIC_LOG(DEBUG, TAG, "IN SRPSaveTrustCertChain");
743     VERIFY_NON_NULL(TAG, trustCertChain, ERROR,  OC_STACK_INVALID_PARAM);
744     VERIFY_NON_NULL(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
745
746     OCStackResult res = OC_STACK_ERROR;
747
748     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
749     VERIFY_NON_NULL(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
750
751     memcpy(cred->subject.id, &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
752
753     cred->credUsage= (char *)OICCalloc(1, strlen(TRUST_CA)+1 );
754     VERIFY_NON_NULL(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
755     OICStrcpy(cred->credUsage, strlen(TRUST_CA) + 1, TRUST_CA) ;
756
757     cred->credType = SIGNED_ASYMMETRIC_KEY;
758
759     cred->optionalData.data = (uint8_t *)OICCalloc(1, chainSize);
760     VERIFY_NON_NULL(TAG, cred->optionalData.data, ERROR, OC_STACK_NO_MEMORY);
761     memcpy(cred->optionalData.data, trustCertChain, chainSize);
762     cred->optionalData.len = chainSize;
763     cred->optionalData.encoding = encodingType;
764
765     res = AddCredential(cred);
766     if(res != OC_STACK_OK)
767     {
768         DeleteCredList(cred);
769         return res;
770     }
771     *credId = cred->credId;
772
773     OIC_LOG(DEBUG, TAG, "OUT SRPSaveTrustCertChain");
774
775     return res;
776 }
777
778
779 OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16_t *credId)
780 {
781     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
782     VERIFY_NON_NULL(TAG, cert, ERROR,  OC_STACK_INVALID_PARAM);
783     VERIFY_NON_NULL(TAG, cert->data, ERROR,  OC_STACK_INVALID_PARAM);
784     VERIFY_NON_NULL(TAG, key, ERROR,  OC_STACK_INVALID_PARAM);
785     VERIFY_NON_NULL(TAG, key->data, ERROR,  OC_STACK_INVALID_PARAM);
786     VERIFY_NON_NULL(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
787
788     OCStackResult res = OC_STACK_ERROR;
789
790     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
791     VERIFY_NON_NULL(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
792
793     OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
794
795     if (OC_STACK_OK != GetDoxmDeviceID(&cred->subject))
796     {
797         OIC_LOG(ERROR, TAG, "Cann't get the device id(GetDoxmDeviceID)");
798     }
799
800     cred->credUsage= (char *)OICCalloc(1, strlen(PRIMARY_CERT)+1 );
801     VERIFY_NON_NULL(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
802     OICStrcpy(cred->credUsage, strlen(PRIMARY_CERT) + 1, PRIMARY_CERT) ;
803
804     cred->credType = SIGNED_ASYMMETRIC_KEY;
805
806     OicSecCert_t *publicData = &cred->publicData;
807     publicData->data = (uint8_t *)OICCalloc(1, cert->len);
808     VERIFY_NON_NULL(TAG, publicData->data, ERROR, OC_STACK_NO_MEMORY);
809     memcpy(publicData->data, cert->data, cert->len);
810     publicData->len = cert->len;
811
812     OicSecKey_t *privateData = &cred->privateData;
813     privateData->data = (uint8_t *)OICCalloc(1, key->len);
814     VERIFY_NON_NULL(TAG, privateData->data, ERROR, OC_STACK_NO_MEMORY);
815     memcpy(privateData->data, key->data, key->len);
816     privateData->len = key->len;
817     privateData->encoding = key->encoding;
818
819     res = AddCredential(cred);
820     if(res != OC_STACK_OK)
821     {
822         DeleteCredList(cred);
823         return res;
824     }
825     *credId = cred->credId;
826
827     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
828
829     return res;
830 }
831 #endif // __WITH_X509__ || __WITH_TLS__
832
833 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
834                                       const OCProvisionDev_t *pDev1,
835                                       const OCProvisionDev_t *pDev2,
836                                       OCProvisionResultCB resultCallback)
837 {
838     VERIFY_NON_NULL(TAG, pDev1, ERROR,  OC_STACK_INVALID_PARAM);
839     if (SYMMETRIC_PAIR_WISE_KEY == type)
840     {
841         VERIFY_NON_NULL(TAG, pDev2, ERROR,  OC_STACK_INVALID_PARAM);
842     }
843     if (!resultCallback)
844     {
845         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
846         return OC_STACK_INVALID_CALLBACK;
847     }
848     if (SYMMETRIC_PAIR_WISE_KEY == type &&
849         0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
850     {
851         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
852         return OC_STACK_INVALID_PARAM;
853     }
854
855     if (SYMMETRIC_PAIR_WISE_KEY == type &&
856        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
857     {
858         OIC_LOG(INFO, TAG, "Invalid key size");
859         return OC_STACK_INVALID_PARAM;
860     }
861
862     OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
863
864     if (SYMMETRIC_PAIR_WISE_KEY == type)
865     {
866         bool linkExisits = true;
867         OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
868
869         if (res != OC_STACK_OK)
870         {
871             OIC_LOG(ERROR, TAG, "Internal error occured");
872             return res;
873         }
874         if (linkExisits)
875         {
876             OIC_LOG(ERROR, TAG, "Link already exists");
877             return OC_STACK_INVALID_PARAM;
878         }
879     }
880
881     OicUuid_t provTooldeviceID =   {{0,}};
882     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
883     {
884         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
885         return OC_STACK_ERROR;
886     }
887     OIC_LOG(INFO, TAG, "retrieved deviceid");
888     switch (type)
889     {
890         case SYMMETRIC_PAIR_WISE_KEY:
891         {
892             const OCProvisionDev_t *firstDevice = pDev1;
893             const OCProvisionDev_t *secondDevice = pDev2;
894
895             OicSecCred_t *firstCred = NULL;
896             OicSecCred_t *secondCred = NULL;
897             OCStackResult res = PMGeneratePairWiseCredentials(type, keySize, &provTooldeviceID,
898                     &firstDevice->doxm->deviceID, &secondDevice->doxm->deviceID,
899                     &firstCred, &secondCred);
900             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
901             OIC_LOG(INFO, TAG, "Credentials generated successfully");
902             CredentialData_t *credData =
903                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
904             if (NULL == credData)
905             {
906                 OICFree(firstCred);
907                 OICFree(secondCred);
908                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
909                 return OC_STACK_NO_MEMORY;
910             }
911             credData->deviceInfo1 = firstDevice;
912             credData->deviceInfo2 = secondDevice;
913             credData->credInfo = secondCred;
914             credData->ctx = ctx;
915             credData->credInfoFirst = firstCred;
916             credData->numOfResults = 0;
917             credData->resultCallback = resultCallback;
918             // first call to provision creds to device1.
919             // second call to provision creds to device2.
920             int noOfRiCalls = 2;
921             credData->resArr =
922                 (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
923             if (NULL == credData->resArr)
924             {
925                 OICFree(firstCred);
926                 OICFree(secondCred);
927                 OICFree(credData);
928                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
929                 return OC_STACK_NO_MEMORY;
930             }
931             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
932             if (OC_STACK_OK != res)
933             {
934                 DeleteCredList(firstCred);
935                 DeleteCredList(secondCred);
936                 OICFree(credData->resArr);
937                 OICFree(credData);
938             }
939             OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
940             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
941             return res;
942         }
943 #ifdef __WITH_X509__
944         case SIGNED_ASYMMETRIC_KEY:
945         {
946             const OCProvisionDev_t *firstDevice = pDev1;
947             OicSecCred_t *cred = NULL;
948             OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID,
949                                                                 &firstDevice->doxm->deviceID,&cred);
950             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
951             OIC_LOG(INFO, TAG, "Certificate credentials generated successfully");
952             CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
953             if (NULL == certData)
954             {
955                 OICFree(cred);
956                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
957                 return OC_STACK_NO_MEMORY;
958             }
959
960             certData->deviceInfo = firstDevice;
961             certData->ctx = ctx;
962             certData->credInfo = cred;
963             certData->numOfResults = 0;
964             certData->resultCallback = resultCallback;
965
966             certData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
967             if (NULL == certData->resArr)
968             {
969                 DeleteCredList(cred);
970                 OICFree(certData);
971                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
972                 return OC_STACK_NO_MEMORY;
973             }
974
975             res = provisionCertCred(cred, firstDevice, certData, &provisionCertCB);
976             if (OC_STACK_OK != res)
977             {
978                 OICFree(certData->resArr);
979                 OICFree(certData);
980             }
981             DeleteCredList(cred);
982             OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
983
984             return res;
985         }
986 #endif
987         default:
988         {
989             OIC_LOG(ERROR, TAG, "Invalid option.");
990             return OC_STACK_INVALID_PARAM;
991         }
992     }
993     return OC_STACK_ERROR;
994 }
995
996 /**
997  * Internal Function to store results in result array during ACL provisioning.
998  */
999 static void registerResultForACLProvisioning(ACLData_t *aclData,
1000                                              OCStackResult stackresult)
1001 {
1002    OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
1003                        aclData->numOfResults);
1004    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
1005           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
1006    aclData->resArr[(aclData->numOfResults)].res = stackresult;
1007    ++(aclData->numOfResults);
1008 }
1009
1010 /**
1011  * Callback handler of SRPProvisionACL.
1012  *
1013  * @param[in] ctx             ctx value passed to callback from calling function.
1014  * @param[in] UNUSED          handle to an invocation
1015  * @param[in] clientResponse  Response from queries to remote servers.
1016  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1017  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1018  */
1019 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
1020                                                   OCClientResponse *clientResponse)
1021 {
1022     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
1023     (void)UNUSED;
1024     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
1025     ACLData_t *aclData = (ACLData_t*)ctx;
1026     OCProvisionResultCB resultCallback = aclData->resultCallback;
1027
1028     if (clientResponse)
1029     {
1030         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1031         {
1032             registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CHANGED);
1033             ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
1034                                                     aclData->resArr,
1035                                                     false);
1036              OICFree(aclData->resArr);
1037              OICFree(aclData);
1038              return OC_STACK_DELETE_TRANSACTION;
1039         }
1040     }
1041     registerResultForACLProvisioning(aclData, OC_STACK_ERROR);
1042     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
1043                                             aclData->resArr,
1044                                             true);
1045     OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
1046     OICFree(aclData->resArr);
1047     OICFree(aclData);
1048     return OC_STACK_DELETE_TRANSACTION;
1049 }
1050
1051 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1052         OicSecAcl_t *acl, OCProvisionResultCB resultCallback)
1053 {
1054     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1055     VERIFY_NON_NULL(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
1056     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1057
1058     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1059     if(!secPayload)
1060     {
1061         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1062         return OC_STACK_NO_MEMORY;
1063     }
1064     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1065     if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData, &secPayload->payloadSize))
1066     {
1067         OCPayloadDestroy((OCPayload *)secPayload);
1068         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
1069         return OC_STACK_NO_MEMORY;
1070     }
1071     OIC_LOG(DEBUG, TAG, "Created payload for ACL:");
1072     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1073
1074     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1075     if(!PMGenerateQuery(true,
1076                         selectedDeviceInfo->endpoint.addr,
1077                         selectedDeviceInfo->securePort,
1078                         selectedDeviceInfo->connType,
1079                         query, sizeof(query), OIC_RSRC_ACL_URI))
1080     {
1081         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
1082         return OC_STACK_ERROR;
1083     }
1084     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1085
1086     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1087     cbData.cb = &SRPProvisionACLCB;
1088     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
1089     if (aclData == NULL)
1090     {
1091         OCPayloadDestroy((OCPayload *)secPayload);
1092         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1093         return OC_STACK_NO_MEMORY;
1094     }
1095     aclData->deviceInfo = selectedDeviceInfo;
1096     aclData->resultCallback = resultCallback;
1097     aclData->numOfResults=0;
1098     aclData->ctx = ctx;
1099     // call to provision ACL to device1.
1100     int noOfRiCalls = 1;
1101     aclData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1102     if (aclData->resArr == NULL)
1103     {
1104         OICFree(aclData);
1105         OCPayloadDestroy((OCPayload *)secPayload);
1106         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1107         return OC_STACK_NO_MEMORY;
1108     }
1109     cbData.context = (void *)aclData;
1110     cbData.cd = NULL;
1111     OCMethod method = OC_REST_POST;
1112     OCDoHandle handle = NULL;
1113     OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
1114     OCStackResult ret = OCDoResource(&handle, method, query,
1115             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1116             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1117     if (ret != OC_STACK_OK)
1118     {
1119         OICFree(aclData->resArr);
1120         OICFree(aclData);
1121     }
1122     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1123     return OC_STACK_OK;
1124 }
1125
1126 /**
1127  * Internal Function to store results in result array during Direct-Pairing provisioning.
1128  */
1129 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
1130                                              OCStackResult stackresult)
1131 {
1132    OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
1133            "pconfData->numOfResults is %d\n", pconfData->numOfResults);
1134    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
1135           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
1136    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
1137    ++(pconfData->numOfResults);
1138 }
1139
1140 /**
1141  * Callback handler of SRPProvisionDirectPairing.
1142  *
1143  * @param[in] ctx             ctx value passed to callback from calling function.
1144  * @param[in] UNUSED          handle to an invocation
1145  * @param[in] clientResponse  Response from queries to remote servers.
1146  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1147  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1148  */
1149 static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
1150                                                   OCClientResponse *clientResponse)
1151 {
1152     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
1153     (void)UNUSED;
1154     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
1155     PconfData_t *pconfData = (PconfData_t*)ctx;
1156     OCProvisionResultCB resultCallback = pconfData->resultCallback;
1157
1158     if (clientResponse)
1159     {
1160         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1161         {
1162             registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK);
1163             ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1164                                                     pconfData->resArr,
1165                                                     false);
1166              OICFree(pconfData->resArr);
1167              OICFree(pconfData);
1168              return OC_STACK_DELETE_TRANSACTION;
1169         }
1170     }
1171     registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
1172     ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1173                                             pconfData->resArr,
1174                                             true);
1175     OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
1176     OICFree(pconfData->resArr);
1177     OICFree(pconfData);
1178     return OC_STACK_DELETE_TRANSACTION;
1179 }
1180
1181 OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1182         OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
1183 {
1184     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1185     VERIFY_NON_NULL(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
1186     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1187
1188     // check direct-pairing capability
1189     if (true != selectedDeviceInfo->doxm->dpc)
1190     {
1191         OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
1192         return OC_STACK_UNAUTHORIZED_REQ;
1193     }
1194
1195     OicUuid_t provTooldeviceID =   {.id={0}};
1196     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
1197     {
1198         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
1199         return OC_STACK_ERROR;
1200     }
1201     memcpy(&pconf->rownerID, &provTooldeviceID, sizeof(OicUuid_t));
1202
1203     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1204     if(!secPayload)
1205     {
1206         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1207         return OC_STACK_NO_MEMORY;
1208     }
1209     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1210
1211     if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData),
1212                 &(secPayload->payloadSize)))
1213     {
1214         OCPayloadDestroy((OCPayload*)secPayload);
1215         OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
1216         return OC_STACK_NO_MEMORY;
1217     }
1218     OIC_LOG(DEBUG, TAG, "Created payload for pconf set");
1219     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1220
1221
1222     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1223     if(!PMGenerateQuery(true,
1224                 selectedDeviceInfo->endpoint.addr,
1225                 selectedDeviceInfo->securePort,
1226                 selectedDeviceInfo->connType,
1227                 query, sizeof(query), OIC_RSRC_PCONF_URI))
1228     {
1229         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
1230         return OC_STACK_ERROR;
1231     }
1232     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1233
1234     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1235     cbData.cb = &SRPProvisionDirectPairingCB;
1236     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
1237     if (NULL == pconfData)
1238     {
1239         OCPayloadDestroy((OCPayload*)secPayload);
1240         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1241         return OC_STACK_NO_MEMORY;
1242     }
1243     pconfData->deviceInfo = selectedDeviceInfo;
1244     pconfData->resultCallback = resultCallback;
1245     pconfData->numOfResults=0;
1246     pconfData->ctx = ctx;
1247     // call to provision PCONF to device1.
1248     int noOfRiCalls = 1;
1249     pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1250     if (NULL == pconfData->resArr)
1251     {
1252         OICFree(pconfData);
1253         OCPayloadDestroy((OCPayload*)secPayload);
1254         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1255         return OC_STACK_NO_MEMORY;
1256     }
1257     cbData.context = (void *)pconfData;
1258     cbData.cd = NULL;
1259     OCMethod method = OC_REST_POST;
1260     OCDoHandle handle = NULL;
1261     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
1262     OCStackResult ret = OCDoResource(&handle, method, query,
1263             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1264             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1265     if (OC_STACK_OK != ret)
1266     {
1267         OICFree(pconfData->resArr);
1268         OICFree(pconfData);
1269     }
1270     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1271     return OC_STACK_OK;
1272 }
1273
1274 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
1275 {
1276     if (unlinkData)
1277     {
1278         OICFree(unlinkData->unlinkDev);
1279         OICFree(unlinkData->unlinkRes);
1280         OICFree(unlinkData);
1281     }
1282 }
1283
1284 static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResult stackresult,
1285                                            IdxUnlinkRes_t idx)
1286 {
1287     if (NULL != unlinkData)
1288     {
1289         OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
1290                             unlinkData->numOfResults);
1291         OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
1292
1293         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
1294
1295         // Set result in the result array according to the position (devNum).
1296         if (idx != IDX_DB_UPDATE_RES)
1297         {
1298             memcpy(pUuid->id, unlinkData->unlinkDev[idx].doxm->deviceID.id, sizeof(pUuid->id));
1299         }
1300         else
1301         {   // When deivce ID is 000... this means it's the result of database update.
1302             memset(pUuid->id, 0, sizeof(pUuid->id));
1303         }
1304         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
1305         ++(unlinkData->numOfResults);
1306         OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
1307     }
1308 }
1309
1310 static OCStackResult SendDeleteCredentialRequest(void* ctx,
1311                                                  OCClientResponseHandler respHandler,
1312                                                  const OCProvisionDev_t* revokedDev,
1313                                                  const OCProvisionDev_t* destDev)
1314 {
1315     OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
1316
1317     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1318     {
1319         return OC_STACK_INVALID_PARAM;
1320     }
1321
1322     char *subID = NULL;
1323     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1324     if(OC_STACK_OK != ret)
1325     {
1326         OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to canonical UUID encoding");
1327         return OC_STACK_ERROR;
1328     }
1329
1330     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1331     int snRet = 0;
1332                     //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
1333     char *srpUri = SRP_FORM_DELETE_CREDENTIAL;
1334 #ifdef __WITH_TLS__
1335     if(CA_ADAPTER_TCP == destDev->endpoint.adapter)
1336     {
1337         srpUri = SRP_FORM_DELETE_CREDENTIAL_TCP;
1338     }
1339 #endif
1340     snRet = snprintf(reqBuf, sizeof(reqBuf), srpUri, destDev->endpoint.addr,
1341                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
1342     OICFree(subID);
1343     if (snRet < 0)
1344     {
1345         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
1346         return OC_STACK_ERROR;
1347     }
1348     else if ((size_t)snRet >= sizeof(reqBuf))
1349     {
1350         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
1351         return OC_STACK_ERROR;
1352     }
1353
1354     OCCallbackData cbData;
1355     memset(&cbData, 0, sizeof(cbData));
1356     cbData.context = ctx;
1357     cbData.cb = respHandler;
1358     cbData.cd = NULL;
1359     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1360
1361     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1362
1363     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1364                                      &destDev->endpoint, NULL,
1365                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1366     if (OC_STACK_OK != ret)
1367     {
1368         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1369     }
1370     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1371
1372     return ret;
1373 }
1374
1375 static OCStackResult SendDeleteACLRequest(void* ctx,
1376                                                  OCClientResponseHandler respHandler,
1377                                                  const OCProvisionDev_t* revokedDev,
1378                                                  const OCProvisionDev_t* destDev)
1379 {
1380     OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest");
1381
1382     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1383     {
1384         return OC_STACK_INVALID_PARAM;
1385     }
1386
1387     char *subID = NULL;
1388     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1389     if(OC_STACK_OK != ret)
1390     {
1391         OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding");
1392         return OC_STACK_ERROR;
1393     }
1394
1395     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1396     int snRet = 0;
1397                     //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID)
1398     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
1399                      destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID);
1400     OICFree(subID);
1401     if (snRet < 0)
1402     {
1403         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d\n", snRet);
1404         return OC_STACK_ERROR;
1405     }
1406     else if ((size_t)snRet >= sizeof(reqBuf))
1407     {
1408         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d\n", snRet);
1409         return OC_STACK_ERROR;
1410     }
1411
1412     OCCallbackData cbData;
1413     memset(&cbData, 0, sizeof(cbData));
1414     cbData.context = ctx;
1415     cbData.cb = respHandler;
1416     cbData.cd = NULL;
1417     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1418
1419     OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server");
1420
1421     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1422                                      &destDev->endpoint, NULL,
1423                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1424     if (OC_STACK_OK != ret)
1425     {
1426         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret);
1427     }
1428     OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest");
1429
1430     return ret;
1431 }
1432
1433 /**
1434  * Callback handler of unlink second device.
1435  *
1436  * @param[in] ctx             ctx value passed to callback from calling function.
1437  * @param[in] handle          handle to an invocation
1438  * @param[in] clientResponse  Response from queries to remote servers.
1439  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1440  *          OC_STACK_KEEP_TRANSACTION to keep it.
1441  */
1442 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1443         OCClientResponse *clientResponse)
1444 {
1445     (void) handle;
1446     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1447     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1448     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1449
1450     if (clientResponse)
1451     {
1452         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1453         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1454
1455         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1456         {
1457             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1458         }
1459         else
1460         {
1461             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1462             unlinkData->resultCallback(unlinkData->ctx,
1463                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1464             goto error;
1465         }
1466     }
1467     else
1468     {
1469         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1470                                        IDX_SECOND_DEVICE_RES);
1471         unlinkData->resultCallback(unlinkData->ctx,
1472                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1473         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1474         goto error;
1475     }
1476
1477     //Update provisioning DB when succes case.
1478     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1479                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1480     {
1481         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1482         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1483         unlinkData->resultCallback(unlinkData->ctx,
1484                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1485         goto error;
1486     }
1487     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1488                                false);
1489
1490 error:
1491     DeleteUnlinkData_t(unlinkData);
1492     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1493     return OC_STACK_DELETE_TRANSACTION;
1494
1495 }
1496
1497 /**
1498  * Callback handler of unlink first device.
1499  *
1500  * @param[in] ctx             ctx value passed to callback from calling function.
1501  * @param[in] handle          handle to an invocation
1502  * @param[in] clientResponse  Response from queries to remote servers.
1503  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1504  *          OC_STACK_KEEP_TRANSACTION to keep it.
1505  */
1506 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1507         OCClientResponse *clientResponse)
1508 {
1509     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1510     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1511     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1512     (void) handle;
1513
1514     if (clientResponse)
1515     {
1516         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1517         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1518
1519         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1520         {
1521             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1522
1523             // Second revocation request to second device.
1524             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1525                                                     &unlinkData->unlinkDev[0],
1526                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1527             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1528             if (OC_STACK_OK != res)
1529             {
1530                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1531                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1532                                                 IDX_SECOND_DEVICE_RES);
1533                  unlinkData->resultCallback(unlinkData->ctx,
1534                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1535                  goto error;
1536             }
1537             else
1538             {
1539                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1540                 return OC_STACK_DELETE_TRANSACTION;
1541             }
1542         }
1543         else
1544         {
1545             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1546
1547             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1548                                             unlinkData->unlinkRes, true);
1549             goto error;
1550         }
1551     }
1552     else
1553     {
1554         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1555         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1556                                        IDX_FIRST_DEVICE_RES );
1557         unlinkData->resultCallback(unlinkData->ctx,
1558                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1559                                    true);
1560         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1561     }
1562
1563 error:
1564     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1565     DeleteUnlinkData_t(unlinkData);
1566     return OC_STACK_DELETE_TRANSACTION;
1567 }
1568
1569 /*
1570 * Function to unlink devices.
1571 * This function will remove the credential & relationship between the two devices.
1572 *
1573 * @param[in] ctx Application context would be returned in result callback
1574 * @param[in] pTargetDev1 first device information to be unlinked.
1575 * @param[in] pTargetDev2 second device information to be unlinked.
1576 * @param[in] resultCallback callback provided by API user, callback will be called when
1577 *            device unlink is finished.
1578  * @return  OC_STACK_OK in case of success and other value otherwise.
1579 */
1580 OCStackResult SRPUnlinkDevices(void* ctx,
1581                                const OCProvisionDev_t* pTargetDev1,
1582                                const OCProvisionDev_t* pTargetDev2,
1583                                OCProvisionResultCB resultCallback)
1584 {
1585     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1586
1587     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
1588     {
1589         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1590         return OC_STACK_INVALID_PARAM;
1591     }
1592     if (!resultCallback)
1593     {
1594         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
1595         return OC_STACK_INVALID_CALLBACK;
1596     }
1597     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
1598     {
1599         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
1600         return OC_STACK_INVALID_PARAM;
1601     }
1602
1603     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1604     PMPrintOCProvisionDev(pTargetDev1);
1605     PMPrintOCProvisionDev(pTargetDev2);
1606
1607     // Mark the link status stale
1608     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1609     if (OC_STACK_OK != res)
1610     {
1611         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1612         return res;
1613     }
1614
1615     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1616     VERIFY_NON_NULL(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1617
1618     //Initialize unlink data
1619     unlinkData->ctx = ctx;
1620     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1621     if (NULL == unlinkData->unlinkDev)
1622     {
1623         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1624         res = OC_STACK_NO_MEMORY;
1625         goto error;
1626     }
1627
1628     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1629     if (NULL == unlinkData->unlinkRes)
1630     {
1631         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1632         res = OC_STACK_NO_MEMORY;
1633         goto error;
1634     }
1635
1636     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1637     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1638
1639     unlinkData->numOfResults = 0;
1640     unlinkData->resultCallback = resultCallback;
1641
1642     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1643                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1644     if (OC_STACK_OK != res)
1645     {
1646         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1647         goto error;
1648     }
1649
1650     return res;
1651
1652 error:
1653     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1654     DeleteUnlinkData_t(unlinkData);
1655     return res;
1656 }
1657
1658 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1659 {
1660     if (pRemoveData)
1661     {
1662         OICFree(pRemoveData->revokeTargetDev);
1663         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1664         OICFree(pRemoveData->removeRes);
1665         OICFree(pRemoveData);
1666     }
1667 }
1668
1669 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1670                                           OCStackResult stackresult, bool hasError)
1671 {
1672     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
1673                          removeData->numOfResults + 1);
1674     if (pLinkedDevId)
1675     {
1676         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1677                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1678     }
1679     else
1680     {
1681         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1682                0, sizeof(pLinkedDevId->id) );
1683     }
1684     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1685     removeData->hasError = hasError;
1686     ++(removeData->numOfResults);
1687
1688     // If we get suffcient result from linked devices, we have to call user callback and do free
1689     if (removeData->sizeOfResArray == removeData->numOfResults)
1690     {
1691         if(!removeData->hasError)
1692         {
1693             // Remove device info from prvisioning database
1694             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1695             {
1696                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1697                 removeData->hasError = true;
1698             }
1699         }
1700         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1701                                    removeData->hasError);
1702         DeleteRemoveData_t(removeData);
1703     }
1704  }
1705
1706 static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1707                                           OCStackResult stackresult, bool hasError)
1708 {
1709     OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %zu\n",
1710                          removeData->numOfResults + 1);
1711     if (pLinkedDevId)
1712     {
1713         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1714                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1715     }
1716     else
1717     {
1718         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1719                0, sizeof(pLinkedDevId->id) );
1720     }
1721     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1722     removeData->hasError = hasError;
1723     ++(removeData->numOfResults);
1724
1725     // If we get suffcient result from linked devices, we have to call user callback and do free
1726     if (removeData->sizeOfResArray == removeData->numOfResults)
1727     {
1728         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1729                                    removeData->hasError);
1730         DeleteRemoveData_t(removeData);
1731     }
1732 }
1733
1734 /**
1735  * Callback handler of unlink first device.
1736  *
1737  * @param[in] ctx             ctx value passed to callback from calling function.
1738  * @param[in] handle          handle to an invocation
1739  * @param[in] clientResponse  Response from queries to remote servers.
1740  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1741  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1742  */
1743 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1744         OCClientResponse *clientResponse)
1745 {
1746     //Update the delete credential into delete device context
1747     //Save the deleted status in delDevCtx
1748     (void)handle;
1749     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1750     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1751     OCStackResult res = OC_STACK_ERROR;
1752
1753     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1754
1755     if (clientResponse)
1756     {
1757         OicUuid_t revDevUuid = {.id={0}};
1758         if(UUID_LENGTH == clientResponse->identity.id_length)
1759         {
1760             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1761             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1762             {
1763                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1764                 if (OC_STACK_OK != res)
1765                 {
1766                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1767                            registerResultForRemoveDevice(removeData, &revDevUuid,
1768                            OC_STACK_INCONSISTENT_DB, true);
1769
1770                     return OC_STACK_DELETE_TRANSACTION;
1771                 }
1772
1773                 registerResultForRemoveDevice(removeData, &revDevUuid,
1774                                               OC_STACK_RESOURCE_DELETED, false);
1775             }
1776             else
1777             {
1778                 registerResultForRemoveDevice(removeData, &revDevUuid,
1779                                               clientResponse->result, true);
1780                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1781             }
1782         }
1783         else
1784         {
1785             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1786                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1787
1788             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1789             {
1790                 /**
1791                   * Since server's credential was deleted,
1792                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1793                   */
1794                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1795                 registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1796             }
1797             else
1798             {
1799                 registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1800             }
1801         }
1802     }
1803     else
1804     {
1805         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1806         OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1807     }
1808
1809
1810     return OC_STACK_DELETE_TRANSACTION;
1811 }
1812
1813 /**
1814  * Callback handler of reset device.
1815  *
1816  * @param[in] ctx             ctx value passed to callback from calling function.
1817  * @param[in] handle          handle to an invocation
1818  * @param[in] clientResponse  Response from queries to remote servers.
1819  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1820  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1821  */
1822 static OCStackApplicationResult SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle,
1823         OCClientResponse *clientResponse)
1824 {
1825     //Update the delete credential into delete device context
1826     //Save the deleted status in delDevCtx
1827     (void)handle;
1828     OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB.");
1829     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1830     OCStackResult res = OC_STACK_ERROR;
1831
1832     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1833     OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev);
1834     OCProvisionResultCB resultCallback = removeData->resultCallback;
1835     if (clientResponse)
1836     {
1837         OicUuid_t revDevUuid = {.id={0}};
1838         if(UUID_LENGTH == clientResponse->identity.id_length)
1839         {
1840             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1841             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1842             {
1843                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1844                 if (OC_STACK_OK != res)
1845                 {
1846                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1847                            registerResultForResetDevice(removeData, &revDevUuid,
1848                            OC_STACK_INCONSISTENT_DB, true);
1849
1850                     return OC_STACK_DELETE_TRANSACTION;
1851                 }
1852
1853                 registerResultForResetDevice(removeData, &revDevUuid,
1854                                               OC_STACK_RESOURCE_DELETED, false);
1855             }
1856             else
1857             {
1858                 registerResultForResetDevice(removeData, &revDevUuid,
1859                                               clientResponse->result, false);
1860                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1861             }
1862         }
1863         else
1864         {
1865             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1866                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1867
1868             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1869             {
1870                 /**
1871                   * Since server's credential was deleted,
1872                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1873                   */
1874                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1875                 registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1876             }
1877             else
1878             {
1879                 registerResultForResetDevice(removeData, NULL, clientResponse->result, true);
1880             }
1881         }
1882     }
1883     else
1884     {
1885         registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true);
1886         OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse");
1887     }
1888
1889     SRPResetDevice(pTargetDev, resultCallback);
1890
1891     return OC_STACK_DELETE_TRANSACTION;
1892 }
1893
1894 /**
1895  * Callback handler of reset device sync-up
1896  *
1897  * @param[in] ctx             ctx value passed to callback from calling function.
1898  * @param[in] handle          handle to an invocation
1899  * @param[in] clientResponse  Response from queries to remote servers.
1900  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1901  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1902  */
1903 static OCStackApplicationResult SRPSyncDeviceACLCB(void *ctx, OCDoHandle handle,
1904         OCClientResponse *clientResponse)
1905 {
1906     return OC_STACK_DELETE_TRANSACTION;
1907 }
1908
1909 /**
1910  * Callback handler of device remote reset.
1911  *
1912  * @param[in] ctx             ctx value passed to callback from calling function.
1913  * @param[in] handle          handle to an invocation
1914  * @param[in] clientResponse  Response from queries to remote servers.
1915  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1916  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1917  */
1918 static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle handle,
1919         OCClientResponse *clientResponse)
1920 {
1921     OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB");
1922     if(OC_STACK_OK == clientResponse->result)
1923     {
1924         OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED");
1925     }
1926
1927     // Delete Cred and ACL related to the target device.
1928     const OicSecCred_t *cred = NULL;
1929     OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx;
1930     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
1931     if (cred == NULL)
1932     {
1933         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device.");
1934         goto error;
1935     }
1936
1937     OCStackResult res = RemoveCredential(&cred->subject);
1938     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1939     {
1940         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential.");
1941         goto error;
1942     }
1943
1944     res = RemoveACE(&cred->subject, NULL);
1945     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1946     {
1947         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL.");
1948         goto error;
1949     }
1950     if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID))
1951     {
1952         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM");
1953     }
1954
1955     //Close the DTLS session of the reset device.
1956     CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr;
1957     CAResult_t caResult = CACloseDtlsSession(endpoint);
1958     if(CA_STATUS_OK != caResult)
1959     {
1960         OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult);
1961     }
1962
1963     /**
1964      * If there is no linked device, PM does not send any request.
1965      * So we should directly invoke the result callback to inform the result of OCResetDevice.
1966      */
1967     if(OC_STACK_NO_RESOURCE == res)
1968     {
1969         res = OC_STACK_OK;
1970     }
1971
1972 error:
1973     OICFree(pTargetDev);
1974     return OC_STACK_DELETE_TRANSACTION;
1975
1976 }
1977
1978 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
1979                                                  OCProvisionDev_t* pOwnedDevList,
1980                                                  OCUuidList_t* pLinkedUuidList,
1981                                                  OCProvisionDev_t** ppLinkedDevList,
1982                                                  size_t *numOfLinkedDev)
1983 {
1984     // pOwnedDevList could be NULL. It means no alived and owned device now.
1985     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
1986         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
1987     {
1988         return OC_STACK_INVALID_PARAM;
1989     }
1990
1991     size_t cnt = 0;
1992     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
1993     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
1994     {
1995         // Mark the link status stale.
1996         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
1997         if (OC_STACK_OK != res)
1998         {
1999             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
2000             return OC_STACK_INCONSISTENT_DB;
2001         }
2002
2003         if (pOwnedDevList)
2004         {
2005             // If this linked device is alive (power-on), add the deivce to the list.
2006             OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2007             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
2008             {
2009                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
2010                 {
2011                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
2012                     if (NULL == targetDev)
2013                     {
2014                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
2015                         return OC_STACK_NO_MEMORY;
2016                     }
2017
2018                     LL_PREPEND(*ppLinkedDevList, targetDev);
2019                     cnt++;
2020                     break;
2021                 }
2022             }
2023         }
2024     }
2025     *numOfLinkedDev = cnt;
2026     return OC_STACK_OK;
2027 }
2028
2029 /*
2030 * Function to device revocation
2031 * This function will remove credential of target device from all devices in subnet.
2032 *
2033 * @param[in] ctx Application context would be returned in result callback
2034 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2035 * @param[in] pTargetDev Device information to be revoked.
2036 * @param[in] resultCallback callback provided by API user, callback will be called when
2037 *            credential revocation is finished.
2038 * @return  OC_STACK_OK in case of success and other value otherwise.
2039 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2040 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2041 */
2042 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2043                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2044 {
2045     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
2046
2047     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2048     {
2049         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
2050         return OC_STACK_INVALID_PARAM;
2051     }
2052     if (!resultCallback)
2053     {
2054         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
2055         return OC_STACK_INVALID_CALLBACK;
2056     }
2057
2058     // Declare variables in here to handle error cases with goto statement.
2059     OCProvisionDev_t* pOwnedDevList = NULL;
2060     OCProvisionDev_t* pLinkedDevList = NULL;
2061     RemoveData_t* removeData = NULL;
2062
2063     //1. Find all devices that has a credential of the revoked device
2064     OCUuidList_t* pLinkedUuidList = NULL;
2065     size_t numOfDevices = 0;
2066     OCStackResult res = OC_STACK_ERROR;
2067     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2068     if (OC_STACK_OK != res)
2069     {
2070         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
2071         return res;
2072     }
2073     // if there is no related device, we can skip further process.
2074     if (0 == numOfDevices)
2075     {
2076         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
2077         res = OC_STACK_CONTINUE;
2078         goto error;
2079     }
2080
2081     //2. Find owned device from the network
2082     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2083     if (OC_STACK_OK != res)
2084     {
2085         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
2086         goto error;
2087     }
2088
2089     //3. Make a list of devices to send DELETE credential request
2090     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2091     size_t numOfLinkedDev = 0;
2092     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2093                                       &pLinkedDevList, &numOfLinkedDev);
2094     if (OC_STACK_OK != res)
2095     {
2096         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
2097         goto error;
2098     }
2099     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2100     {                       // So we don't have to send request message.
2101         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
2102         res = OC_STACK_CONTINUE;
2103         goto error;
2104     }
2105
2106     // 4. Prepare RemoveData Context data.
2107     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2108     if (!removeData)
2109     {
2110         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2111         res = OC_STACK_NO_MEMORY;
2112         goto error;
2113     }
2114
2115     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2116     if (!removeData->revokeTargetDev)
2117     {
2118         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
2119         res = OC_STACK_NO_MEMORY;
2120         goto error;
2121     }
2122
2123     removeData->removeRes =
2124         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2125     if (!removeData->removeRes)
2126     {
2127         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2128         res = OC_STACK_NO_MEMORY;
2129         goto error;
2130     }
2131
2132     removeData->ctx = ctx;
2133     removeData->linkedDevList = pLinkedDevList;
2134     removeData->resultCallback = resultCallback;
2135     removeData->numOfResults = 0;
2136     removeData->sizeOfResArray = numOfLinkedDev;
2137     removeData->hasError = false;
2138
2139     // 5. Send DELETE credential request to linked devices.
2140     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2141     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2142     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2143     {
2144         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2145                                            removeData->revokeTargetDev, curDev);
2146         if (OC_STACK_OK != res)
2147         {
2148             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
2149                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2150         }
2151         else
2152         {
2153             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2154         }
2155     }
2156
2157     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2158     PMDeleteDeviceList(pOwnedDevList);
2159     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
2160
2161     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2162
2163 error:
2164     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2165     PMDeleteDeviceList(pOwnedDevList);
2166     PMDeleteDeviceList(pLinkedDevList);
2167     if (removeData)
2168     {
2169         OICFree(removeData->revokeTargetDev);
2170         OICFree(removeData->removeRes);
2171         OICFree(removeData);
2172     }
2173     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
2174     return res;
2175 }
2176
2177 /*
2178 * Function to device revocation
2179 * This function will remove credential of target device from all devices in subnet.
2180 *
2181 * @param[in] ctx Application context would be returned in result callback
2182 * @param[in] pOwnedDevList List of owned devices
2183 * @param[in] pTargetDev Device information to be revoked.
2184 * @param[in] resultCallback callback provided by API user, callback will be called when
2185 *            credential revocation is finished.
2186 * @return  OC_STACK_OK in case of success and other value otherwise.
2187 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2188 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2189 */
2190 OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList,
2191                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2192 {
2193     OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery");
2194
2195     if (!pOwnedDevList)
2196     {
2197         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Owned Device List is empty");
2198         return OC_STACK_CONTINUE;
2199     }
2200     if (!pTargetDev)
2201     {
2202         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters");
2203         return OC_STACK_INVALID_PARAM;
2204     }
2205     if (!resultCallback)
2206     {
2207         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback");
2208         return OC_STACK_INVALID_CALLBACK;
2209     }
2210
2211     // Declare variables in here to handle error cases with goto statement.
2212     OCProvisionDev_t* pLinkedDevList = NULL;
2213     RemoveData_t* removeData = NULL;
2214
2215     //1. Find all devices that has a credential of the revoked device
2216     OCUuidList_t* pLinkedUuidList = NULL;
2217     size_t numOfDevices = 0;
2218     OCStackResult res = OC_STACK_ERROR;
2219     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2220     if (OC_STACK_OK != res)
2221     {
2222         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information");
2223         return OC_STACK_CONTINUE;
2224     }
2225     // if there is no related device, we can skip further process.
2226     if (0 == numOfDevices)
2227     {
2228         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found.");
2229         return OC_STACK_CONTINUE;
2230     }
2231
2232     //2. Make a list of devices to send DELETE credential request
2233     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2234     size_t numOfLinkedDev = 0;
2235     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2236                                       &pLinkedDevList, &numOfLinkedDev);
2237     if (OC_STACK_OK != res)
2238     {
2239         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed");
2240         goto error;
2241     }
2242     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2243     {                       // So we don't have to send request message.
2244         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found.");
2245         return OC_STACK_CONTINUE;
2246     }
2247
2248     // 3. Prepare RemoveData Context data.
2249     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2250     if (!removeData)
2251     {
2252         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2253         res = OC_STACK_NO_MEMORY;
2254         goto error;
2255     }
2256
2257     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2258     if (!removeData->revokeTargetDev)
2259     {
2260         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed");
2261         res = OC_STACK_NO_MEMORY;
2262         goto error;
2263     }
2264
2265     removeData->removeRes =
2266         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2267     if (!removeData->removeRes)
2268     {
2269         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2270         res = OC_STACK_NO_MEMORY;
2271         goto error;
2272     }
2273
2274     removeData->ctx = ctx;
2275     removeData->linkedDevList = pLinkedDevList;
2276     removeData->resultCallback = resultCallback;
2277     removeData->numOfResults = 0;
2278     removeData->sizeOfResArray = numOfLinkedDev;
2279     removeData->hasError = false;
2280
2281     // 5. Send DELETE credential request to linked devices.
2282     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2283     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2284     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2285     {
2286         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2287                                            removeData->revokeTargetDev, curDev);
2288         if (OC_STACK_OK != res)
2289         {
2290             OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\
2291                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2292         }
2293         else
2294         {
2295             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2296         }
2297     }
2298
2299     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2300     OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery");
2301
2302     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2303
2304 error:
2305     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2306     PMDeleteDeviceList(pLinkedDevList);
2307     if (removeData)
2308     {
2309         OICFree(removeData->revokeTargetDev);
2310         OICFree(removeData->removeRes);
2311         OICFree(removeData);
2312     }
2313     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery");
2314     return res;
2315 }
2316
2317 /*
2318  * Function to sync-up credential and ACL of the target device.
2319  * This function will remove credential and ACL of target device from all devices in subnet.
2320  *
2321  * @param[in] ctx Application context would be returned in result callback
2322  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2323  * @param[in] pTargetDev Device information to be revoked.
2324  * @param[in] resultCallback callback provided by API user, callback will be called when
2325  *            credential revocation is finished.
2326  *            when there is an error, this user callback is called immediately.
2327  * @return OC_STACK_OK in case of success and other value otherwise.
2328  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2329  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2330  */
2331 OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2332                          const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2333 {
2334     OIC_LOG(INFO, TAG, "IN SRPSyncDevice");
2335     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2336     {
2337         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters");
2338         return OC_STACK_INVALID_PARAM;
2339     }
2340     if (!resultCallback)
2341     {
2342         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback");
2343         return OC_STACK_INVALID_CALLBACK;
2344     }
2345
2346     // Declare variables in here to handle error cases with goto statement.
2347     OCProvisionDev_t* pOwnedDevList = NULL;
2348     OCProvisionDev_t* pLinkedDevList = NULL;
2349     RemoveData_t* removeData = NULL;
2350
2351     //1. Find all devices that has a credential of the revoked device
2352     OCUuidList_t* pLinkedUuidList = NULL;
2353     size_t numOfDevices = 0;
2354     OCStackResult res = OC_STACK_ERROR;
2355     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2356     if (OC_STACK_OK != res)
2357     {
2358         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information");
2359         return res;
2360     }
2361     // if there is no related device, we can skip further process.
2362     if (0 == numOfDevices)
2363     {
2364         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found.");
2365         res = OC_STACK_CONTINUE;
2366         goto error;
2367     }
2368
2369     //2. Find owned device from the network
2370     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2371     if (OC_STACK_OK != res)
2372     {
2373         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery");
2374         goto error;
2375     }
2376
2377     //3. Make a list of devices to send DELETE credential request
2378     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2379     size_t numOfLinkedDev = 0;
2380     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2381                                       &pLinkedDevList, &numOfLinkedDev);
2382     if (OC_STACK_OK != res)
2383     {
2384         OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed");
2385         goto error;
2386     }
2387     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2388     {                       // So we don't have to send request message.
2389         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found.");
2390         res = OC_STACK_CONTINUE;
2391         goto error;
2392     }
2393
2394     // 4. Prepare RemoveData Context data.
2395     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2396     if (!removeData)
2397     {
2398         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to memory allocation");
2399         res = OC_STACK_NO_MEMORY;
2400         goto error;
2401     }
2402
2403     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2404     if (!removeData->revokeTargetDev)
2405     {
2406         OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed");
2407         res = OC_STACK_NO_MEMORY;
2408         goto error;
2409     }
2410
2411     removeData->removeRes =
2412         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2413     if (!removeData->removeRes)
2414     {
2415         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2416         res = OC_STACK_NO_MEMORY;
2417         goto error;
2418     }
2419
2420     removeData->ctx = ctx;
2421     removeData->linkedDevList = pLinkedDevList;
2422     removeData->resultCallback = resultCallback;
2423     removeData->numOfResults = 0;
2424     removeData->sizeOfResArray = numOfLinkedDev;
2425     removeData->hasError = false;
2426
2427     // 5. Send DELETE credential request to linked devices.
2428     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2429     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2430     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2431     {
2432         res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB,
2433                                            removeData->revokeTargetDev, curDev);
2434         if (OC_STACK_OK != res)
2435         {
2436             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\
2437                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2438             goto error;
2439         }
2440         res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB,
2441                                            removeData->revokeTargetDev, curDev);
2442         if (OC_STACK_OK != res)
2443         {
2444             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\
2445                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2446             totalRes = OC_STACK_ERROR;
2447         }
2448         else
2449         {
2450             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2451         }
2452     }
2453
2454     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2455     PMDeleteDeviceList(pOwnedDevList);
2456     OIC_LOG(INFO, TAG, "OUT SRPSyncDevice");
2457
2458     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2459
2460 error:
2461     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2462     PMDeleteDeviceList(pOwnedDevList);
2463     PMDeleteDeviceList(pLinkedDevList);
2464     if (removeData)
2465     {
2466         OICFree(removeData->revokeTargetDev);
2467         OICFree(removeData->removeRes);
2468         OICFree(removeData);
2469     }
2470     OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice");
2471     return res;
2472 }
2473
2474 /*
2475  * Function for remote reset
2476  * This function will send pstat PUT message to the target device to initiate remote reset.
2477  *
2478  * @param[in] pTargetDev Device information to be revoked.
2479  * @param[in] resultCallback callback provided by API user, callback will be called when
2480  *            credential revocation is finished.
2481  *            when there is an error, this user callback is called immediately.
2482  * @return OC_STACK_OK in case of success and other value otherwise.
2483  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2484  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2485  */
2486 OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev,
2487         OCProvisionResultCB resultCallback)
2488 {
2489     OIC_LOG(INFO, TAG, "IN SRPResetDevice");
2490     if (!pTargetDev)
2491     {
2492         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters");
2493         return OC_STACK_INVALID_PARAM;
2494     }
2495     if (!resultCallback)
2496     {
2497         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback");
2498         return OC_STACK_INVALID_CALLBACK;
2499     }
2500
2501     OCStackResult res = OC_STACK_ERROR;
2502     OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t));
2503     if (!pstat)
2504     {
2505         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2506         return OC_STACK_NO_MEMORY;
2507     }
2508
2509     pstat->cm = RESET;
2510     pstat->isOp = false;
2511     memcpy(pstat->deviceID.id, pTargetDev->doxm->deviceID.id, sizeof(OicUuid_t));
2512     pstat->tm = TAKE_OWNER;
2513     pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2514     pstat->smLen = 1;
2515     pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
2516     if (NULL == pstat->sm)
2517     {
2518         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2519         OICFree(pstat);
2520         return OC_STACK_NO_MEMORY;
2521     }
2522     pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2523
2524     OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload));
2525     if (!secPayload)
2526     {
2527         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2528         res = OC_STACK_NO_MEMORY;
2529         goto error;
2530     }
2531     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2532
2533     if (OC_STACK_OK != PstatToCBORPayload(pstat, &(secPayload->securityData),
2534                 &(secPayload->payloadSize), true))
2535     {
2536         OCPayloadDestroy((OCPayload *) secPayload);
2537         OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload");
2538         res = OC_STACK_NO_MEMORY;
2539         goto error;
2540     }
2541     OIC_LOG(DEBUG, TAG, "Created payload for pstat set");
2542     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2543
2544     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2545     if (!PMGenerateQuery(true,
2546                 pTargetDev->endpoint.addr,
2547                 pTargetDev->securePort,
2548                 pTargetDev->connType,
2549                 query, sizeof(query), OIC_RSRC_PSTAT_URI))
2550     {
2551         OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query");
2552         OCPayloadDestroy((OCPayload *) secPayload);
2553         res = OC_STACK_ERROR;
2554         goto error;
2555     }
2556     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2557
2558     OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev);
2559     OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
2560     cbData.cb = &SRPResetDeviceCB;
2561     cbData.context = (void *) targetDev;
2562     cbData.cd = NULL;
2563     OCMethod method = OC_REST_POST;
2564     OCDoHandle handle = NULL;
2565     OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server");
2566     res = OCDoResource(&handle, method, query,
2567             &targetDev->endpoint, (OCPayload *)secPayload,
2568             targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\
2569     if (OC_STACK_OK != res)
2570     {
2571         OIC_LOG(ERROR, TAG, "OCStack resource error");
2572     }
2573
2574 error:
2575     OICFree(pstat->sm);
2576     OICFree(pstat);
2577     OIC_LOG(INFO, TAG, "OUT SRPResetDevice");
2578     return res;
2579 }
2580
2581 /**
2582  * Internal Function to store results in result array during GetCredResourceCB.
2583  */
2584 static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
2585                                              OCStackResult stackresult)
2586 {
2587    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
2588            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2589    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2590           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2591    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2592    ++(GetSecData->numOfResults);
2593 }
2594
2595 /**
2596  * Callback handler of SRPGetCredResource.
2597  *
2598  * @param[in] ctx             ctx value passed to callback from calling function.
2599  * @param[in] UNUSED          handle to an invocation
2600  * @param[in] clientResponse  Response from queries to remote servers.
2601  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2602  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2603  */
2604 static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
2605                                                   OCClientResponse *clientResponse)
2606 {
2607     OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
2608     (void)UNUSED;
2609     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2610     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2611     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2612
2613     if (clientResponse)
2614     {
2615         if(OC_STACK_OK == clientResponse->result)
2616         {
2617             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2618             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2619
2620             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2621
2622             registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2623             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2624                                                     GetSecData->resArr,
2625                                                     false);
2626              OICFree(GetSecData->resArr);
2627              OICFree(GetSecData);
2628
2629             return OC_STACK_DELETE_TRANSACTION;
2630         }
2631     }
2632     registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2633     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2634                                             GetSecData->resArr,
2635                                             false);
2636     OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
2637     OICFree(GetSecData->resArr);
2638     OICFree(GetSecData);
2639
2640     return OC_STACK_DELETE_TRANSACTION;
2641 }
2642
2643
2644 OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2645         OCProvisionResultCB resultCallback)
2646 {
2647     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2648     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2649
2650     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2651     if(!PMGenerateQuery(true,
2652                         selectedDeviceInfo->endpoint.addr,
2653                         selectedDeviceInfo->securePort,
2654                         selectedDeviceInfo->connType,
2655                         query, sizeof(query), OIC_RSRC_CRED_URI))
2656     {
2657         OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
2658         return OC_STACK_ERROR;
2659     }
2660     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2661
2662     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2663     cbData.cb = &SRPGetCredResourceCB;
2664     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2665     if (NULL == GetSecData)
2666     {
2667         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2668         return OC_STACK_NO_MEMORY;
2669     }
2670     GetSecData->deviceInfo = selectedDeviceInfo;
2671     GetSecData->resultCallback = resultCallback;
2672     GetSecData->numOfResults=0;
2673     GetSecData->ctx = ctx;
2674
2675     int noOfRiCalls = 1;
2676     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2677     if (NULL == GetSecData->resArr)
2678     {
2679         OICFree(GetSecData);
2680         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2681         return OC_STACK_NO_MEMORY;
2682     }
2683     cbData.context = (void *)GetSecData;
2684     cbData.cd = NULL;
2685     OCMethod method = OC_REST_GET;
2686     OCDoHandle handle = NULL;
2687     OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
2688     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2689             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2690     if (OC_STACK_OK != ret)
2691     {
2692         OIC_LOG(ERROR, TAG, "OCStack resource error");
2693         OICFree(GetSecData->resArr);
2694         OICFree(GetSecData);
2695     }
2696     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2697     OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
2698
2699     return OC_STACK_OK;
2700 }
2701
2702 /**
2703  * Internal Function to store results in result array during GetACLResourceCB.
2704  */
2705 static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
2706                                              OCStackResult stackresult)
2707 {
2708    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
2709            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2710    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2711           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2712    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2713    ++(GetSecData->numOfResults);
2714 }
2715
2716 /**
2717  * Callback handler of SRPGetACLResource.
2718  *
2719  * @param[in] ctx             ctx value passed to callback from calling function.
2720  * @param[in] UNUSED          handle to an invocation
2721  * @param[in] clientResponse  Response from queries to remote servers.
2722  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2723  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2724  */
2725 static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
2726                                                   OCClientResponse *clientResponse)
2727 {
2728     OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
2729     (void)UNUSED;
2730     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2731     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2732     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2733
2734     if (clientResponse)
2735     {
2736         if(OC_STACK_OK == clientResponse->result)
2737         {
2738             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2739             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2740
2741             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2742
2743             registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2744             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2745                                                     GetSecData->resArr,
2746                                                     false);
2747              OICFree(GetSecData->resArr);
2748              OICFree(GetSecData);
2749
2750             return OC_STACK_DELETE_TRANSACTION;
2751         }
2752     }
2753     registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2754     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2755                                             GetSecData->resArr,
2756                                             false);
2757     OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
2758     OICFree(GetSecData->resArr);
2759     OICFree(GetSecData);
2760
2761     return OC_STACK_DELETE_TRANSACTION;
2762 }
2763
2764
2765 OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2766         OCProvisionResultCB resultCallback)
2767 {
2768     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2769     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2770
2771     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2772     if(!PMGenerateQuery(true,
2773                         selectedDeviceInfo->endpoint.addr,
2774                         selectedDeviceInfo->securePort,
2775                         selectedDeviceInfo->connType,
2776                         query, sizeof(query), OIC_RSRC_ACL_URI))
2777     {
2778         OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
2779         return OC_STACK_ERROR;
2780     }
2781     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2782
2783     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2784     cbData.cb = &SRPGetACLResourceCB;
2785     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2786     if (NULL == GetSecData)
2787     {
2788         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2789         return OC_STACK_NO_MEMORY;
2790     }
2791     GetSecData->deviceInfo = selectedDeviceInfo;
2792     GetSecData->resultCallback = resultCallback;
2793     GetSecData->numOfResults=0;
2794     GetSecData->ctx = ctx;
2795
2796     int noOfRiCalls = 1;
2797     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2798     if (NULL == GetSecData->resArr)
2799     {
2800         OICFree(GetSecData);
2801         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2802         return OC_STACK_NO_MEMORY;
2803     }
2804     cbData.context = (void *)GetSecData;
2805     cbData.cd = NULL;
2806     OCMethod method = OC_REST_GET;
2807     OCDoHandle handle = NULL;
2808     OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
2809     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2810             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2811     if (OC_STACK_OK != ret)
2812     {
2813         OIC_LOG(ERROR, TAG, "OCStack resource error");
2814         OICFree(GetSecData->resArr);
2815         OICFree(GetSecData);
2816     }
2817     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2818     OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
2819
2820     return OC_STACK_OK;
2821 }