Fix the incorrect credential access in SRPProvisionTrustCertChain.
[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         OIC_LOG(ERROR, TAG, "Memory allocation problem");
701         return OC_STACK_NO_MEMORY;
702     }
703     certData->deviceInfo = selectedDeviceInfo;
704     certData->resultCallback = resultCallback;
705     certData->credInfo = NULL; //credInfo not used in the response handler
706     certData->numOfResults=0;
707     certData->ctx = ctx;
708
709     int noOfRiCalls = 1;
710     certData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
711     if (certData->resArr == NULL)
712     {
713         OICFree(certData);
714         OCPayloadDestroy((OCPayload *)secPayload);
715         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
716         return OC_STACK_NO_MEMORY;
717     }
718     cbData.context = (void *)certData;
719     cbData.cd = NULL;
720     OCMethod method = OC_REST_POST;
721     OCDoHandle handle = NULL;
722     OIC_LOG(DEBUG, TAG, "Sending Cred info to resource server");
723     OCStackResult ret = OCDoResource(&handle, method, query,
724             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
725             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
726     if (ret != OC_STACK_OK)
727     {
728         OICFree(certData->resArr);
729         OICFree(certData);
730     }
731
732     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
733     return OC_STACK_OK;
734 }
735
736 OCStackResult SRPSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
737                                             OicEncodingType_t encodingType, uint16_t *credId)
738 {
739     OIC_LOG(DEBUG, TAG, "IN SRPSaveTrustCertChain");
740     VERIFY_NON_NULL(TAG, trustCertChain, ERROR,  OC_STACK_INVALID_PARAM);
741     VERIFY_NON_NULL(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
742
743     OCStackResult res = OC_STACK_ERROR;
744
745     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
746     VERIFY_NON_NULL(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
747
748     memcpy(cred->subject.id, &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
749
750     cred->credUsage= (char *)OICCalloc(1, strlen(TRUST_CA)+1 );
751     VERIFY_NON_NULL(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
752     OICStrcpy(cred->credUsage, strlen(TRUST_CA) + 1, TRUST_CA) ;
753
754     cred->credType = SIGNED_ASYMMETRIC_KEY;
755
756     if (encodingType == OIC_ENCODING_PEM)
757     {
758         cred->optionalData.data = (uint8_t *)OICCalloc(1, chainSize + 1);
759         VERIFY_NON_NULL(TAG, cred->optionalData.data, ERROR, OC_STACK_NO_MEMORY);
760         cred->optionalData.len = chainSize + 1;
761     }
762     else
763     {
764         cred->optionalData.data = (uint8_t *)OICCalloc(1, chainSize);
765         VERIFY_NON_NULL(TAG, cred->optionalData.data, ERROR, OC_STACK_NO_MEMORY);
766         cred->optionalData.len = chainSize;
767     }
768     memcpy(cred->optionalData.data, trustCertChain, chainSize);
769     cred->optionalData.encoding = encodingType;
770
771     res = AddCredential(cred);
772     if(res != OC_STACK_OK)
773     {
774         DeleteCredList(cred);
775         return res;
776     }
777     *credId = cred->credId;
778
779     OIC_LOG(DEBUG, TAG, "OUT SRPSaveTrustCertChain");
780
781     return res;
782 }
783
784
785 OCStackResult SRPSaveOwnCertChain(OicSecCert_t * cert, OicSecKey_t * key, uint16_t *credId)
786 {
787     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
788     VERIFY_NON_NULL(TAG, cert, ERROR,  OC_STACK_INVALID_PARAM);
789     VERIFY_NON_NULL(TAG, cert->data, ERROR,  OC_STACK_INVALID_PARAM);
790     VERIFY_NON_NULL(TAG, key, ERROR,  OC_STACK_INVALID_PARAM);
791     VERIFY_NON_NULL(TAG, key->data, ERROR,  OC_STACK_INVALID_PARAM);
792     VERIFY_NON_NULL(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
793
794     OCStackResult res = OC_STACK_ERROR;
795
796     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
797     VERIFY_NON_NULL(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
798
799     OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
800
801     if (OC_STACK_OK != GetDoxmDeviceID(&cred->subject))
802     {
803         OIC_LOG(ERROR, TAG, "Cann't get the device id(GetDoxmDeviceID)");
804     }
805
806     cred->credUsage= (char *)OICCalloc(1, strlen(PRIMARY_CERT)+1 );
807     VERIFY_NON_NULL(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
808     OICStrcpy(cred->credUsage, strlen(PRIMARY_CERT) + 1, PRIMARY_CERT) ;
809
810     cred->credType = SIGNED_ASYMMETRIC_KEY;
811
812     OicSecCert_t *publicData = &cred->publicData;
813     publicData->data = (uint8_t *)OICCalloc(1, cert->len);
814     VERIFY_NON_NULL(TAG, publicData->data, ERROR, OC_STACK_NO_MEMORY);
815     memcpy(publicData->data, cert->data, cert->len);
816     publicData->len = cert->len;
817
818     OicSecKey_t *privateData = &cred->privateData;
819     privateData->data = (uint8_t *)OICCalloc(1, key->len);
820     VERIFY_NON_NULL(TAG, privateData->data, ERROR, OC_STACK_NO_MEMORY);
821     memcpy(privateData->data, key->data, key->len);
822     privateData->len = key->len;
823     privateData->encoding = key->encoding;
824
825     res = AddCredential(cred);
826     if(res != OC_STACK_OK)
827     {
828         DeleteCredList(cred);
829         return res;
830     }
831     *credId = cred->credId;
832
833     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
834
835     return res;
836 }
837 #endif // __WITH_X509__ || __WITH_TLS__
838
839 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
840                                       const OCProvisionDev_t *pDev1,
841                                       const OCProvisionDev_t *pDev2,
842                                       OCProvisionResultCB resultCallback)
843 {
844     VERIFY_NON_NULL(TAG, pDev1, ERROR,  OC_STACK_INVALID_PARAM);
845     if (SYMMETRIC_PAIR_WISE_KEY == type)
846     {
847         VERIFY_NON_NULL(TAG, pDev2, ERROR,  OC_STACK_INVALID_PARAM);
848     }
849     if (!resultCallback)
850     {
851         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
852         return OC_STACK_INVALID_CALLBACK;
853     }
854     if (SYMMETRIC_PAIR_WISE_KEY == type &&
855         0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
856     {
857         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
858         return OC_STACK_INVALID_PARAM;
859     }
860
861     if (SYMMETRIC_PAIR_WISE_KEY == type &&
862        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
863     {
864         OIC_LOG(INFO, TAG, "Invalid key size");
865         return OC_STACK_INVALID_PARAM;
866     }
867
868     OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
869
870     if (SYMMETRIC_PAIR_WISE_KEY == type)
871     {
872         bool linkExisits = true;
873         OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
874
875         if (res != OC_STACK_OK)
876         {
877             OIC_LOG(ERROR, TAG, "Internal error occured");
878             return res;
879         }
880         if (linkExisits)
881         {
882             OIC_LOG(ERROR, TAG, "Link already exists");
883             return OC_STACK_INVALID_PARAM;
884         }
885     }
886
887     OicUuid_t provTooldeviceID =   {{0,}};
888     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
889     {
890         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
891         return OC_STACK_ERROR;
892     }
893     OIC_LOG(INFO, TAG, "retrieved deviceid");
894     switch (type)
895     {
896         case SYMMETRIC_PAIR_WISE_KEY:
897         {
898             const OCProvisionDev_t *firstDevice = pDev1;
899             const OCProvisionDev_t *secondDevice = pDev2;
900
901             OicSecCred_t *firstCred = NULL;
902             OicSecCred_t *secondCred = NULL;
903             OCStackResult res = PMGeneratePairWiseCredentials(type, keySize, &provTooldeviceID,
904                     &firstDevice->doxm->deviceID, &secondDevice->doxm->deviceID,
905                     &firstCred, &secondCred);
906             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
907             OIC_LOG(INFO, TAG, "Credentials generated successfully");
908             CredentialData_t *credData =
909                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
910             if (NULL == credData)
911             {
912                 OICFree(firstCred);
913                 OICFree(secondCred);
914                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
915                 return OC_STACK_NO_MEMORY;
916             }
917             credData->deviceInfo1 = firstDevice;
918             credData->deviceInfo2 = secondDevice;
919             credData->credInfo = secondCred;
920             credData->ctx = ctx;
921             credData->credInfoFirst = firstCred;
922             credData->numOfResults = 0;
923             credData->resultCallback = resultCallback;
924             // first call to provision creds to device1.
925             // second call to provision creds to device2.
926             int noOfRiCalls = 2;
927             credData->resArr =
928                 (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
929             if (NULL == credData->resArr)
930             {
931                 OICFree(firstCred);
932                 OICFree(secondCred);
933                 OICFree(credData);
934                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
935                 return OC_STACK_NO_MEMORY;
936             }
937             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
938             if (OC_STACK_OK != res)
939             {
940                 DeleteCredList(firstCred);
941                 DeleteCredList(secondCred);
942                 OICFree(credData->resArr);
943                 OICFree(credData);
944             }
945             OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
946             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
947             return res;
948         }
949 #ifdef __WITH_X509__
950         case SIGNED_ASYMMETRIC_KEY:
951         {
952             const OCProvisionDev_t *firstDevice = pDev1;
953             OicSecCred_t *cred = NULL;
954             OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID,
955                                                                 &firstDevice->doxm->deviceID,&cred);
956             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
957             OIC_LOG(INFO, TAG, "Certificate credentials generated successfully");
958             CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
959             if (NULL == certData)
960             {
961                 OICFree(cred);
962                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
963                 return OC_STACK_NO_MEMORY;
964             }
965
966             certData->deviceInfo = firstDevice;
967             certData->ctx = ctx;
968             certData->credInfo = cred;
969             certData->numOfResults = 0;
970             certData->resultCallback = resultCallback;
971
972             certData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
973             if (NULL == certData->resArr)
974             {
975                 DeleteCredList(cred);
976                 OICFree(certData);
977                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
978                 return OC_STACK_NO_MEMORY;
979             }
980
981             res = provisionCertCred(cred, firstDevice, certData, &provisionCertCB);
982             if (OC_STACK_OK != res)
983             {
984                 OICFree(certData->resArr);
985                 OICFree(certData);
986             }
987             DeleteCredList(cred);
988             OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
989
990             return res;
991         }
992 #endif
993         default:
994         {
995             OIC_LOG(ERROR, TAG, "Invalid option.");
996             return OC_STACK_INVALID_PARAM;
997         }
998     }
999     return OC_STACK_ERROR;
1000 }
1001
1002 /**
1003  * Internal Function to store results in result array during ACL provisioning.
1004  */
1005 static void registerResultForACLProvisioning(ACLData_t *aclData,
1006                                              OCStackResult stackresult)
1007 {
1008    OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
1009                        aclData->numOfResults);
1010    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
1011           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
1012    aclData->resArr[(aclData->numOfResults)].res = stackresult;
1013    ++(aclData->numOfResults);
1014 }
1015
1016 /**
1017  * Callback handler of SRPProvisionACL.
1018  *
1019  * @param[in] ctx             ctx value passed to callback from calling function.
1020  * @param[in] UNUSED          handle to an invocation
1021  * @param[in] clientResponse  Response from queries to remote servers.
1022  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1023  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1024  */
1025 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
1026                                                   OCClientResponse *clientResponse)
1027 {
1028     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
1029     (void)UNUSED;
1030     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
1031     ACLData_t *aclData = (ACLData_t*)ctx;
1032     OCProvisionResultCB resultCallback = aclData->resultCallback;
1033
1034     if (clientResponse)
1035     {
1036         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1037         {
1038             registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CHANGED);
1039             ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
1040                                                     aclData->resArr,
1041                                                     false);
1042              OICFree(aclData->resArr);
1043              OICFree(aclData);
1044              return OC_STACK_DELETE_TRANSACTION;
1045         }
1046     }
1047     registerResultForACLProvisioning(aclData, OC_STACK_ERROR);
1048     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
1049                                             aclData->resArr,
1050                                             true);
1051     OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
1052     OICFree(aclData->resArr);
1053     OICFree(aclData);
1054     return OC_STACK_DELETE_TRANSACTION;
1055 }
1056
1057 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1058         OicSecAcl_t *acl, OCProvisionResultCB resultCallback)
1059 {
1060     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1061     VERIFY_NON_NULL(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
1062     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1063
1064     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1065     if(!secPayload)
1066     {
1067         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1068         return OC_STACK_NO_MEMORY;
1069     }
1070     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1071     if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData, &secPayload->payloadSize))
1072     {
1073         OCPayloadDestroy((OCPayload *)secPayload);
1074         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
1075         return OC_STACK_NO_MEMORY;
1076     }
1077     OIC_LOG(DEBUG, TAG, "Created payload for ACL:");
1078     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1079
1080     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1081     if(!PMGenerateQuery(true,
1082                         selectedDeviceInfo->endpoint.addr,
1083                         selectedDeviceInfo->securePort,
1084                         selectedDeviceInfo->connType,
1085                         query, sizeof(query), OIC_RSRC_ACL_URI))
1086     {
1087         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
1088         return OC_STACK_ERROR;
1089     }
1090     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1091
1092     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1093     cbData.cb = &SRPProvisionACLCB;
1094     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
1095     if (aclData == NULL)
1096     {
1097         OCPayloadDestroy((OCPayload *)secPayload);
1098         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1099         return OC_STACK_NO_MEMORY;
1100     }
1101     aclData->deviceInfo = selectedDeviceInfo;
1102     aclData->resultCallback = resultCallback;
1103     aclData->numOfResults=0;
1104     aclData->ctx = ctx;
1105     // call to provision ACL to device1.
1106     int noOfRiCalls = 1;
1107     aclData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1108     if (aclData->resArr == NULL)
1109     {
1110         OICFree(aclData);
1111         OCPayloadDestroy((OCPayload *)secPayload);
1112         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1113         return OC_STACK_NO_MEMORY;
1114     }
1115     cbData.context = (void *)aclData;
1116     cbData.cd = NULL;
1117     OCMethod method = OC_REST_POST;
1118     OCDoHandle handle = NULL;
1119     OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
1120     OCStackResult ret = OCDoResource(&handle, method, query,
1121             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1122             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1123     if (ret != OC_STACK_OK)
1124     {
1125         OICFree(aclData->resArr);
1126         OICFree(aclData);
1127     }
1128     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1129     return OC_STACK_OK;
1130 }
1131
1132 /**
1133  * Internal Function to store results in result array during Direct-Pairing provisioning.
1134  */
1135 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
1136                                              OCStackResult stackresult)
1137 {
1138    OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
1139            "pconfData->numOfResults is %d\n", pconfData->numOfResults);
1140    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
1141           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
1142    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
1143    ++(pconfData->numOfResults);
1144 }
1145
1146 /**
1147  * Callback handler of SRPProvisionDirectPairing.
1148  *
1149  * @param[in] ctx             ctx value passed to callback from calling function.
1150  * @param[in] UNUSED          handle to an invocation
1151  * @param[in] clientResponse  Response from queries to remote servers.
1152  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1153  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1154  */
1155 static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
1156                                                   OCClientResponse *clientResponse)
1157 {
1158     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
1159     (void)UNUSED;
1160     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
1161     PconfData_t *pconfData = (PconfData_t*)ctx;
1162     OCProvisionResultCB resultCallback = pconfData->resultCallback;
1163
1164     if (clientResponse)
1165     {
1166         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1167         {
1168             registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK);
1169             ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1170                                                     pconfData->resArr,
1171                                                     false);
1172              OICFree(pconfData->resArr);
1173              OICFree(pconfData);
1174              return OC_STACK_DELETE_TRANSACTION;
1175         }
1176     }
1177     registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
1178     ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1179                                             pconfData->resArr,
1180                                             true);
1181     OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
1182     OICFree(pconfData->resArr);
1183     OICFree(pconfData);
1184     return OC_STACK_DELETE_TRANSACTION;
1185 }
1186
1187 OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1188         OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
1189 {
1190     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1191     VERIFY_NON_NULL(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
1192     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1193
1194     // check direct-pairing capability
1195     if (true != selectedDeviceInfo->doxm->dpc)
1196     {
1197         OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
1198         return OC_STACK_UNAUTHORIZED_REQ;
1199     }
1200
1201     OicUuid_t provTooldeviceID =   {.id={0}};
1202     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
1203     {
1204         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
1205         return OC_STACK_ERROR;
1206     }
1207     memcpy(&pconf->rownerID, &provTooldeviceID, sizeof(OicUuid_t));
1208
1209     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1210     if(!secPayload)
1211     {
1212         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1213         return OC_STACK_NO_MEMORY;
1214     }
1215     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1216
1217     if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData),
1218                 &(secPayload->payloadSize)))
1219     {
1220         OCPayloadDestroy((OCPayload*)secPayload);
1221         OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
1222         return OC_STACK_NO_MEMORY;
1223     }
1224     OIC_LOG(DEBUG, TAG, "Created payload for pconf set");
1225     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1226
1227
1228     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1229     if(!PMGenerateQuery(true,
1230                 selectedDeviceInfo->endpoint.addr,
1231                 selectedDeviceInfo->securePort,
1232                 selectedDeviceInfo->connType,
1233                 query, sizeof(query), OIC_RSRC_PCONF_URI))
1234     {
1235         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
1236         return OC_STACK_ERROR;
1237     }
1238     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1239
1240     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1241     cbData.cb = &SRPProvisionDirectPairingCB;
1242     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
1243     if (NULL == pconfData)
1244     {
1245         OCPayloadDestroy((OCPayload*)secPayload);
1246         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1247         return OC_STACK_NO_MEMORY;
1248     }
1249     pconfData->deviceInfo = selectedDeviceInfo;
1250     pconfData->resultCallback = resultCallback;
1251     pconfData->numOfResults=0;
1252     pconfData->ctx = ctx;
1253     // call to provision PCONF to device1.
1254     int noOfRiCalls = 1;
1255     pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1256     if (NULL == pconfData->resArr)
1257     {
1258         OICFree(pconfData);
1259         OCPayloadDestroy((OCPayload*)secPayload);
1260         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1261         return OC_STACK_NO_MEMORY;
1262     }
1263     cbData.context = (void *)pconfData;
1264     cbData.cd = NULL;
1265     OCMethod method = OC_REST_POST;
1266     OCDoHandle handle = NULL;
1267     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
1268     OCStackResult ret = OCDoResource(&handle, method, query,
1269             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1270             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1271     if (OC_STACK_OK != ret)
1272     {
1273         OICFree(pconfData->resArr);
1274         OICFree(pconfData);
1275     }
1276     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1277     return OC_STACK_OK;
1278 }
1279
1280 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
1281 {
1282     if (unlinkData)
1283     {
1284         OICFree(unlinkData->unlinkDev);
1285         OICFree(unlinkData->unlinkRes);
1286         OICFree(unlinkData);
1287     }
1288 }
1289
1290 static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResult stackresult,
1291                                            IdxUnlinkRes_t idx)
1292 {
1293     if (NULL != unlinkData)
1294     {
1295         OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
1296                             unlinkData->numOfResults);
1297         OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
1298
1299         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
1300
1301         // Set result in the result array according to the position (devNum).
1302         if (idx != IDX_DB_UPDATE_RES)
1303         {
1304             memcpy(pUuid->id, unlinkData->unlinkDev[idx].doxm->deviceID.id, sizeof(pUuid->id));
1305         }
1306         else
1307         {   // When deivce ID is 000... this means it's the result of database update.
1308             memset(pUuid->id, 0, sizeof(pUuid->id));
1309         }
1310         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
1311         ++(unlinkData->numOfResults);
1312         OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
1313     }
1314 }
1315
1316 static OCStackResult SendDeleteCredentialRequest(void* ctx,
1317                                                  OCClientResponseHandler respHandler,
1318                                                  const OCProvisionDev_t* revokedDev,
1319                                                  const OCProvisionDev_t* destDev)
1320 {
1321     OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
1322
1323     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1324     {
1325         return OC_STACK_INVALID_PARAM;
1326     }
1327
1328     char *subID = NULL;
1329     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1330     if(OC_STACK_OK != ret)
1331     {
1332         OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to canonical UUID encoding");
1333         return OC_STACK_ERROR;
1334     }
1335
1336     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1337     int snRet = 0;
1338                     //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
1339     char *srpUri = SRP_FORM_DELETE_CREDENTIAL;
1340 #ifdef __WITH_TLS__
1341     if(CA_ADAPTER_TCP == destDev->endpoint.adapter)
1342     {
1343         srpUri = SRP_FORM_DELETE_CREDENTIAL_TCP;
1344     }
1345 #endif
1346     snRet = snprintf(reqBuf, sizeof(reqBuf), srpUri, destDev->endpoint.addr,
1347                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
1348     OICFree(subID);
1349     if (snRet < 0)
1350     {
1351         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
1352         return OC_STACK_ERROR;
1353     }
1354     else if ((size_t)snRet >= sizeof(reqBuf))
1355     {
1356         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
1357         return OC_STACK_ERROR;
1358     }
1359
1360     OCCallbackData cbData;
1361     memset(&cbData, 0, sizeof(cbData));
1362     cbData.context = ctx;
1363     cbData.cb = respHandler;
1364     cbData.cd = NULL;
1365     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1366
1367     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1368
1369     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1370                                      &destDev->endpoint, NULL,
1371                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1372     if (OC_STACK_OK != ret)
1373     {
1374         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1375     }
1376     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1377
1378     return ret;
1379 }
1380
1381 static OCStackResult SendDeleteACLRequest(void* ctx,
1382                                                  OCClientResponseHandler respHandler,
1383                                                  const OCProvisionDev_t* revokedDev,
1384                                                  const OCProvisionDev_t* destDev)
1385 {
1386     OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest");
1387
1388     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1389     {
1390         return OC_STACK_INVALID_PARAM;
1391     }
1392
1393     char *subID = NULL;
1394     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1395     if(OC_STACK_OK != ret)
1396     {
1397         OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding");
1398         return OC_STACK_ERROR;
1399     }
1400
1401     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1402     int snRet = 0;
1403                     //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID)
1404     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
1405                      destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID);
1406     OICFree(subID);
1407     if (snRet < 0)
1408     {
1409         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d\n", snRet);
1410         return OC_STACK_ERROR;
1411     }
1412     else if ((size_t)snRet >= sizeof(reqBuf))
1413     {
1414         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d\n", snRet);
1415         return OC_STACK_ERROR;
1416     }
1417
1418     OCCallbackData cbData;
1419     memset(&cbData, 0, sizeof(cbData));
1420     cbData.context = ctx;
1421     cbData.cb = respHandler;
1422     cbData.cd = NULL;
1423     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1424
1425     OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server");
1426
1427     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1428                                      &destDev->endpoint, NULL,
1429                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1430     if (OC_STACK_OK != ret)
1431     {
1432         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret);
1433     }
1434     OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest");
1435
1436     return ret;
1437 }
1438
1439 /**
1440  * Callback handler of unlink second device.
1441  *
1442  * @param[in] ctx             ctx value passed to callback from calling function.
1443  * @param[in] handle          handle to an invocation
1444  * @param[in] clientResponse  Response from queries to remote servers.
1445  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1446  *          OC_STACK_KEEP_TRANSACTION to keep it.
1447  */
1448 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1449         OCClientResponse *clientResponse)
1450 {
1451     (void) handle;
1452     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1453     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1454     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1455
1456     if (clientResponse)
1457     {
1458         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1459         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1460
1461         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1462         {
1463             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1464         }
1465         else
1466         {
1467             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1468             unlinkData->resultCallback(unlinkData->ctx,
1469                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1470             goto error;
1471         }
1472     }
1473     else
1474     {
1475         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1476                                        IDX_SECOND_DEVICE_RES);
1477         unlinkData->resultCallback(unlinkData->ctx,
1478                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1479         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1480         goto error;
1481     }
1482
1483     //Update provisioning DB when succes case.
1484     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1485                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1486     {
1487         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1488         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1489         unlinkData->resultCallback(unlinkData->ctx,
1490                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1491         goto error;
1492     }
1493     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1494                                false);
1495
1496 error:
1497     DeleteUnlinkData_t(unlinkData);
1498     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1499     return OC_STACK_DELETE_TRANSACTION;
1500
1501 }
1502
1503 /**
1504  * Callback handler of unlink first device.
1505  *
1506  * @param[in] ctx             ctx value passed to callback from calling function.
1507  * @param[in] handle          handle to an invocation
1508  * @param[in] clientResponse  Response from queries to remote servers.
1509  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1510  *          OC_STACK_KEEP_TRANSACTION to keep it.
1511  */
1512 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1513         OCClientResponse *clientResponse)
1514 {
1515     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1516     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1517     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1518     (void) handle;
1519
1520     if (clientResponse)
1521     {
1522         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1523         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1524
1525         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1526         {
1527             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1528
1529             // Second revocation request to second device.
1530             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1531                                                     &unlinkData->unlinkDev[0],
1532                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1533             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1534             if (OC_STACK_OK != res)
1535             {
1536                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1537                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1538                                                 IDX_SECOND_DEVICE_RES);
1539                  unlinkData->resultCallback(unlinkData->ctx,
1540                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1541                  goto error;
1542             }
1543             else
1544             {
1545                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1546                 return OC_STACK_DELETE_TRANSACTION;
1547             }
1548         }
1549         else
1550         {
1551             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1552
1553             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1554                                             unlinkData->unlinkRes, true);
1555             goto error;
1556         }
1557     }
1558     else
1559     {
1560         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1561         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1562                                        IDX_FIRST_DEVICE_RES );
1563         unlinkData->resultCallback(unlinkData->ctx,
1564                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1565                                    true);
1566         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1567     }
1568
1569 error:
1570     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1571     DeleteUnlinkData_t(unlinkData);
1572     return OC_STACK_DELETE_TRANSACTION;
1573 }
1574
1575 /*
1576 * Function to unlink devices.
1577 * This function will remove the credential & relationship between the two devices.
1578 *
1579 * @param[in] ctx Application context would be returned in result callback
1580 * @param[in] pTargetDev1 first device information to be unlinked.
1581 * @param[in] pTargetDev2 second device information to be unlinked.
1582 * @param[in] resultCallback callback provided by API user, callback will be called when
1583 *            device unlink is finished.
1584  * @return  OC_STACK_OK in case of success and other value otherwise.
1585 */
1586 OCStackResult SRPUnlinkDevices(void* ctx,
1587                                const OCProvisionDev_t* pTargetDev1,
1588                                const OCProvisionDev_t* pTargetDev2,
1589                                OCProvisionResultCB resultCallback)
1590 {
1591     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1592
1593     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
1594     {
1595         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1596         return OC_STACK_INVALID_PARAM;
1597     }
1598     if (!resultCallback)
1599     {
1600         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
1601         return OC_STACK_INVALID_CALLBACK;
1602     }
1603     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
1604     {
1605         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
1606         return OC_STACK_INVALID_PARAM;
1607     }
1608
1609     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1610     PMPrintOCProvisionDev(pTargetDev1);
1611     PMPrintOCProvisionDev(pTargetDev2);
1612
1613     // Mark the link status stale
1614     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1615     if (OC_STACK_OK != res)
1616     {
1617         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1618         return res;
1619     }
1620
1621     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1622     VERIFY_NON_NULL(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1623
1624     //Initialize unlink data
1625     unlinkData->ctx = ctx;
1626     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1627     if (NULL == unlinkData->unlinkDev)
1628     {
1629         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1630         res = OC_STACK_NO_MEMORY;
1631         goto error;
1632     }
1633
1634     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1635     if (NULL == unlinkData->unlinkRes)
1636     {
1637         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1638         res = OC_STACK_NO_MEMORY;
1639         goto error;
1640     }
1641
1642     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1643     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1644
1645     unlinkData->numOfResults = 0;
1646     unlinkData->resultCallback = resultCallback;
1647
1648     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1649                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1650     if (OC_STACK_OK != res)
1651     {
1652         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1653         goto error;
1654     }
1655
1656     return res;
1657
1658 error:
1659     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1660     DeleteUnlinkData_t(unlinkData);
1661     return res;
1662 }
1663
1664 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1665 {
1666     if (pRemoveData)
1667     {
1668         OICFree(pRemoveData->revokeTargetDev);
1669         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1670         OICFree(pRemoveData->removeRes);
1671         OICFree(pRemoveData);
1672     }
1673 }
1674
1675 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1676                                           OCStackResult stackresult, bool hasError)
1677 {
1678     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
1679                          removeData->numOfResults + 1);
1680     if (pLinkedDevId)
1681     {
1682         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1683                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1684     }
1685     else
1686     {
1687         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1688                0, sizeof(pLinkedDevId->id) );
1689     }
1690     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1691     removeData->hasError = hasError;
1692     ++(removeData->numOfResults);
1693
1694     // If we get suffcient result from linked devices, we have to call user callback and do free
1695     if (removeData->sizeOfResArray == removeData->numOfResults)
1696     {
1697         if(!removeData->hasError)
1698         {
1699             // Remove device info from prvisioning database
1700             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1701             {
1702                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1703                 removeData->hasError = true;
1704             }
1705         }
1706         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1707                                    removeData->hasError);
1708         DeleteRemoveData_t(removeData);
1709     }
1710  }
1711
1712 static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1713                                           OCStackResult stackresult, bool hasError)
1714 {
1715     OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %zu\n",
1716                          removeData->numOfResults + 1);
1717     if (pLinkedDevId)
1718     {
1719         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1720                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1721     }
1722     else
1723     {
1724         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1725                0, sizeof(pLinkedDevId->id) );
1726     }
1727     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1728     removeData->hasError = hasError;
1729     ++(removeData->numOfResults);
1730
1731     // If we get suffcient result from linked devices, we have to call user callback and do free
1732     if (removeData->sizeOfResArray == removeData->numOfResults)
1733     {
1734         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1735                                    removeData->hasError);
1736         DeleteRemoveData_t(removeData);
1737     }
1738 }
1739
1740 /**
1741  * Callback handler of unlink first device.
1742  *
1743  * @param[in] ctx             ctx value passed to callback from calling function.
1744  * @param[in] handle          handle to an invocation
1745  * @param[in] clientResponse  Response from queries to remote servers.
1746  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1747  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1748  */
1749 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1750         OCClientResponse *clientResponse)
1751 {
1752     //Update the delete credential into delete device context
1753     //Save the deleted status in delDevCtx
1754     (void)handle;
1755     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1756     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1757     OCStackResult res = OC_STACK_ERROR;
1758
1759     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1760
1761     if (clientResponse)
1762     {
1763         OicUuid_t revDevUuid = {.id={0}};
1764         if(UUID_LENGTH == clientResponse->identity.id_length)
1765         {
1766             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1767             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1768             {
1769                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1770                 if (OC_STACK_OK != res)
1771                 {
1772                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1773                            registerResultForRemoveDevice(removeData, &revDevUuid,
1774                            OC_STACK_INCONSISTENT_DB, true);
1775
1776                     return OC_STACK_DELETE_TRANSACTION;
1777                 }
1778
1779                 registerResultForRemoveDevice(removeData, &revDevUuid,
1780                                               OC_STACK_RESOURCE_DELETED, false);
1781             }
1782             else
1783             {
1784                 registerResultForRemoveDevice(removeData, &revDevUuid,
1785                                               clientResponse->result, true);
1786                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1787             }
1788         }
1789         else
1790         {
1791             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1792                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1793
1794             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1795             {
1796                 /**
1797                   * Since server's credential was deleted,
1798                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1799                   */
1800                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1801                 registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1802             }
1803             else
1804             {
1805                 registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1806             }
1807         }
1808     }
1809     else
1810     {
1811         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1812         OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1813     }
1814
1815
1816     return OC_STACK_DELETE_TRANSACTION;
1817 }
1818
1819 /**
1820  * Callback handler of reset device.
1821  *
1822  * @param[in] ctx             ctx value passed to callback from calling function.
1823  * @param[in] handle          handle to an invocation
1824  * @param[in] clientResponse  Response from queries to remote servers.
1825  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1826  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1827  */
1828 static OCStackApplicationResult SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle,
1829         OCClientResponse *clientResponse)
1830 {
1831     //Update the delete credential into delete device context
1832     //Save the deleted status in delDevCtx
1833     (void)handle;
1834     OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB.");
1835     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1836     OCStackResult res = OC_STACK_ERROR;
1837
1838     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1839     OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev);
1840     OCProvisionResultCB resultCallback = removeData->resultCallback;
1841     if (clientResponse)
1842     {
1843         OicUuid_t revDevUuid = {.id={0}};
1844         if(UUID_LENGTH == clientResponse->identity.id_length)
1845         {
1846             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1847             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1848             {
1849                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1850                 if (OC_STACK_OK != res)
1851                 {
1852                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1853                            registerResultForResetDevice(removeData, &revDevUuid,
1854                            OC_STACK_INCONSISTENT_DB, true);
1855
1856                     return OC_STACK_DELETE_TRANSACTION;
1857                 }
1858
1859                 registerResultForResetDevice(removeData, &revDevUuid,
1860                                               OC_STACK_RESOURCE_DELETED, false);
1861             }
1862             else
1863             {
1864                 registerResultForResetDevice(removeData, &revDevUuid,
1865                                               clientResponse->result, false);
1866                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1867             }
1868         }
1869         else
1870         {
1871             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1872                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1873
1874             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1875             {
1876                 /**
1877                   * Since server's credential was deleted,
1878                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1879                   */
1880                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1881                 registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1882             }
1883             else
1884             {
1885                 registerResultForResetDevice(removeData, NULL, clientResponse->result, true);
1886             }
1887         }
1888     }
1889     else
1890     {
1891         registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true);
1892         OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse");
1893     }
1894
1895     SRPResetDevice(pTargetDev, resultCallback);
1896
1897     return OC_STACK_DELETE_TRANSACTION;
1898 }
1899
1900 /**
1901  * Callback handler of reset device sync-up
1902  *
1903  * @param[in] ctx             ctx value passed to callback from calling function.
1904  * @param[in] handle          handle to an invocation
1905  * @param[in] clientResponse  Response from queries to remote servers.
1906  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1907  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1908  */
1909 static OCStackApplicationResult SRPSyncDeviceACLCB(void *ctx, OCDoHandle handle,
1910         OCClientResponse *clientResponse)
1911 {
1912     return OC_STACK_DELETE_TRANSACTION;
1913 }
1914
1915 /**
1916  * Callback handler of device remote reset.
1917  *
1918  * @param[in] ctx             ctx value passed to callback from calling function.
1919  * @param[in] handle          handle to an invocation
1920  * @param[in] clientResponse  Response from queries to remote servers.
1921  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1922  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1923  */
1924 static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle handle,
1925         OCClientResponse *clientResponse)
1926 {
1927     OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB");
1928     if(OC_STACK_OK == clientResponse->result)
1929     {
1930         OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED");
1931     }
1932
1933     // Delete Cred and ACL related to the target device.
1934     const OicSecCred_t *cred = NULL;
1935     OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx;
1936     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
1937     if (cred == NULL)
1938     {
1939         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device.");
1940         goto error;
1941     }
1942
1943     OCStackResult res = RemoveCredential(&cred->subject);
1944     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1945     {
1946         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential.");
1947         goto error;
1948     }
1949
1950     res = RemoveACE(&cred->subject, NULL);
1951     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1952     {
1953         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL.");
1954         goto error;
1955     }
1956     if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID))
1957     {
1958         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM");
1959     }
1960
1961     //Close the DTLS session of the reset device.
1962     CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr;
1963     CAResult_t caResult = CACloseDtlsSession(endpoint);
1964     if(CA_STATUS_OK != caResult)
1965     {
1966         OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult);
1967     }
1968
1969     /**
1970      * If there is no linked device, PM does not send any request.
1971      * So we should directly invoke the result callback to inform the result of OCResetDevice.
1972      */
1973     if(OC_STACK_NO_RESOURCE == res)
1974     {
1975         res = OC_STACK_OK;
1976     }
1977
1978 error:
1979     OICFree(pTargetDev);
1980     return OC_STACK_DELETE_TRANSACTION;
1981
1982 }
1983
1984 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
1985                                                  OCProvisionDev_t* pOwnedDevList,
1986                                                  OCUuidList_t* pLinkedUuidList,
1987                                                  OCProvisionDev_t** ppLinkedDevList,
1988                                                  size_t *numOfLinkedDev)
1989 {
1990     // pOwnedDevList could be NULL. It means no alived and owned device now.
1991     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
1992         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
1993     {
1994         return OC_STACK_INVALID_PARAM;
1995     }
1996
1997     size_t cnt = 0;
1998     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
1999     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
2000     {
2001         // Mark the link status stale.
2002         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
2003         if (OC_STACK_OK != res)
2004         {
2005             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
2006             return OC_STACK_INCONSISTENT_DB;
2007         }
2008
2009         if (pOwnedDevList)
2010         {
2011             // If this linked device is alive (power-on), add the deivce to the list.
2012             OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2013             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
2014             {
2015                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
2016                 {
2017                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
2018                     if (NULL == targetDev)
2019                     {
2020                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
2021                         return OC_STACK_NO_MEMORY;
2022                     }
2023
2024                     LL_PREPEND(*ppLinkedDevList, targetDev);
2025                     cnt++;
2026                     break;
2027                 }
2028             }
2029         }
2030     }
2031     *numOfLinkedDev = cnt;
2032     return OC_STACK_OK;
2033 }
2034
2035 /*
2036 * Function to device revocation
2037 * This function will remove credential of target device from all devices in subnet.
2038 *
2039 * @param[in] ctx Application context would be returned in result callback
2040 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2041 * @param[in] pTargetDev Device information to be revoked.
2042 * @param[in] resultCallback callback provided by API user, callback will be called when
2043 *            credential revocation is finished.
2044 * @return  OC_STACK_OK in case of success and other value otherwise.
2045 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2046 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2047 */
2048 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2049                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2050 {
2051     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
2052
2053     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2054     {
2055         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
2056         return OC_STACK_INVALID_PARAM;
2057     }
2058     if (!resultCallback)
2059     {
2060         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
2061         return OC_STACK_INVALID_CALLBACK;
2062     }
2063
2064     // Declare variables in here to handle error cases with goto statement.
2065     OCProvisionDev_t* pOwnedDevList = NULL;
2066     OCProvisionDev_t* pLinkedDevList = NULL;
2067     RemoveData_t* removeData = NULL;
2068
2069     //1. Find all devices that has a credential of the revoked device
2070     OCUuidList_t* pLinkedUuidList = NULL;
2071     size_t numOfDevices = 0;
2072     OCStackResult res = OC_STACK_ERROR;
2073     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2074     if (OC_STACK_OK != res)
2075     {
2076         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
2077         return res;
2078     }
2079     // if there is no related device, we can skip further process.
2080     if (0 == numOfDevices)
2081     {
2082         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
2083         res = OC_STACK_CONTINUE;
2084         goto error;
2085     }
2086
2087     //2. Find owned device from the network
2088     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2089     if (OC_STACK_OK != res)
2090     {
2091         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
2092         goto error;
2093     }
2094
2095     //3. Make a list of devices to send DELETE credential request
2096     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2097     size_t numOfLinkedDev = 0;
2098     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2099                                       &pLinkedDevList, &numOfLinkedDev);
2100     if (OC_STACK_OK != res)
2101     {
2102         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
2103         goto error;
2104     }
2105     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2106     {                       // So we don't have to send request message.
2107         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
2108         res = OC_STACK_CONTINUE;
2109         goto error;
2110     }
2111
2112     // 4. Prepare RemoveData Context data.
2113     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2114     if (!removeData)
2115     {
2116         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2117         res = OC_STACK_NO_MEMORY;
2118         goto error;
2119     }
2120
2121     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2122     if (!removeData->revokeTargetDev)
2123     {
2124         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
2125         res = OC_STACK_NO_MEMORY;
2126         goto error;
2127     }
2128
2129     removeData->removeRes =
2130         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2131     if (!removeData->removeRes)
2132     {
2133         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2134         res = OC_STACK_NO_MEMORY;
2135         goto error;
2136     }
2137
2138     removeData->ctx = ctx;
2139     removeData->linkedDevList = pLinkedDevList;
2140     removeData->resultCallback = resultCallback;
2141     removeData->numOfResults = 0;
2142     removeData->sizeOfResArray = numOfLinkedDev;
2143     removeData->hasError = false;
2144
2145     // 5. Send DELETE credential request to linked devices.
2146     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2147     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2148     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2149     {
2150         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2151                                            removeData->revokeTargetDev, curDev);
2152         if (OC_STACK_OK != res)
2153         {
2154             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
2155                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2156         }
2157         else
2158         {
2159             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2160         }
2161     }
2162
2163     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2164     PMDeleteDeviceList(pOwnedDevList);
2165     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
2166
2167     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2168
2169 error:
2170     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2171     PMDeleteDeviceList(pOwnedDevList);
2172     PMDeleteDeviceList(pLinkedDevList);
2173     if (removeData)
2174     {
2175         OICFree(removeData->revokeTargetDev);
2176         OICFree(removeData->removeRes);
2177         OICFree(removeData);
2178     }
2179     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
2180     return res;
2181 }
2182
2183 /*
2184 * Function to device revocation
2185 * This function will remove credential of target device from all devices in subnet.
2186 *
2187 * @param[in] ctx Application context would be returned in result callback
2188 * @param[in] pOwnedDevList List of owned devices
2189 * @param[in] pTargetDev Device information to be revoked.
2190 * @param[in] resultCallback callback provided by API user, callback will be called when
2191 *            credential revocation is finished.
2192 * @return  OC_STACK_OK in case of success and other value otherwise.
2193 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2194 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2195 */
2196 OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList,
2197                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2198 {
2199     OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery");
2200
2201     if (!pOwnedDevList)
2202     {
2203         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Owned Device List is empty");
2204         return OC_STACK_CONTINUE;
2205     }
2206     if (!pTargetDev)
2207     {
2208         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters");
2209         return OC_STACK_INVALID_PARAM;
2210     }
2211     if (!resultCallback)
2212     {
2213         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback");
2214         return OC_STACK_INVALID_CALLBACK;
2215     }
2216
2217     // Declare variables in here to handle error cases with goto statement.
2218     OCProvisionDev_t* pLinkedDevList = NULL;
2219     RemoveData_t* removeData = NULL;
2220
2221     //1. Find all devices that has a credential of the revoked device
2222     OCUuidList_t* pLinkedUuidList = NULL;
2223     size_t numOfDevices = 0;
2224     OCStackResult res = OC_STACK_ERROR;
2225     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2226     if (OC_STACK_OK != res)
2227     {
2228         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information");
2229         return OC_STACK_CONTINUE;
2230     }
2231     // if there is no related device, we can skip further process.
2232     if (0 == numOfDevices)
2233     {
2234         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found.");
2235         return OC_STACK_CONTINUE;
2236     }
2237
2238     //2. Make a list of devices to send DELETE credential request
2239     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2240     size_t numOfLinkedDev = 0;
2241     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2242                                       &pLinkedDevList, &numOfLinkedDev);
2243     if (OC_STACK_OK != res)
2244     {
2245         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed");
2246         goto error;
2247     }
2248     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2249     {                       // So we don't have to send request message.
2250         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found.");
2251         return OC_STACK_CONTINUE;
2252     }
2253
2254     // 3. Prepare RemoveData Context data.
2255     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2256     if (!removeData)
2257     {
2258         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2259         res = OC_STACK_NO_MEMORY;
2260         goto error;
2261     }
2262
2263     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2264     if (!removeData->revokeTargetDev)
2265     {
2266         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed");
2267         res = OC_STACK_NO_MEMORY;
2268         goto error;
2269     }
2270
2271     removeData->removeRes =
2272         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2273     if (!removeData->removeRes)
2274     {
2275         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2276         res = OC_STACK_NO_MEMORY;
2277         goto error;
2278     }
2279
2280     removeData->ctx = ctx;
2281     removeData->linkedDevList = pLinkedDevList;
2282     removeData->resultCallback = resultCallback;
2283     removeData->numOfResults = 0;
2284     removeData->sizeOfResArray = numOfLinkedDev;
2285     removeData->hasError = false;
2286
2287     // 5. Send DELETE credential request to linked devices.
2288     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2289     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2290     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2291     {
2292         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2293                                            removeData->revokeTargetDev, curDev);
2294         if (OC_STACK_OK != res)
2295         {
2296             OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\
2297                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2298         }
2299         else
2300         {
2301             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2302         }
2303     }
2304
2305     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2306     OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery");
2307
2308     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2309
2310 error:
2311     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2312     PMDeleteDeviceList(pLinkedDevList);
2313     if (removeData)
2314     {
2315         OICFree(removeData->revokeTargetDev);
2316         OICFree(removeData->removeRes);
2317         OICFree(removeData);
2318     }
2319     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery");
2320     return res;
2321 }
2322
2323 /*
2324  * Function to sync-up credential and ACL of the target device.
2325  * This function will remove credential and ACL of target device from all devices in subnet.
2326  *
2327  * @param[in] ctx Application context would be returned in result callback
2328  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2329  * @param[in] pTargetDev Device information to be revoked.
2330  * @param[in] resultCallback callback provided by API user, callback will be called when
2331  *            credential revocation is finished.
2332  *            when there is an error, this user callback is called immediately.
2333  * @return OC_STACK_OK in case of success and other value otherwise.
2334  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2335  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2336  */
2337 OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2338                          const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2339 {
2340     OIC_LOG(INFO, TAG, "IN SRPSyncDevice");
2341     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2342     {
2343         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters");
2344         return OC_STACK_INVALID_PARAM;
2345     }
2346     if (!resultCallback)
2347     {
2348         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback");
2349         return OC_STACK_INVALID_CALLBACK;
2350     }
2351
2352     // Declare variables in here to handle error cases with goto statement.
2353     OCProvisionDev_t* pOwnedDevList = NULL;
2354     OCProvisionDev_t* pLinkedDevList = NULL;
2355     RemoveData_t* removeData = NULL;
2356
2357     //1. Find all devices that has a credential of the revoked device
2358     OCUuidList_t* pLinkedUuidList = NULL;
2359     size_t numOfDevices = 0;
2360     OCStackResult res = OC_STACK_ERROR;
2361     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2362     if (OC_STACK_OK != res)
2363     {
2364         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information");
2365         return res;
2366     }
2367     // if there is no related device, we can skip further process.
2368     if (0 == numOfDevices)
2369     {
2370         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found.");
2371         res = OC_STACK_CONTINUE;
2372         goto error;
2373     }
2374
2375     //2. Find owned device from the network
2376     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2377     if (OC_STACK_OK != res)
2378     {
2379         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery");
2380         goto error;
2381     }
2382
2383     //3. Make a list of devices to send DELETE credential request
2384     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2385     size_t numOfLinkedDev = 0;
2386     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2387                                       &pLinkedDevList, &numOfLinkedDev);
2388     if (OC_STACK_OK != res)
2389     {
2390         OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed");
2391         goto error;
2392     }
2393     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2394     {                       // So we don't have to send request message.
2395         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found.");
2396         res = OC_STACK_CONTINUE;
2397         goto error;
2398     }
2399
2400     // 4. Prepare RemoveData Context data.
2401     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2402     if (!removeData)
2403     {
2404         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to memory allocation");
2405         res = OC_STACK_NO_MEMORY;
2406         goto error;
2407     }
2408
2409     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2410     if (!removeData->revokeTargetDev)
2411     {
2412         OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed");
2413         res = OC_STACK_NO_MEMORY;
2414         goto error;
2415     }
2416
2417     removeData->removeRes =
2418         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2419     if (!removeData->removeRes)
2420     {
2421         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2422         res = OC_STACK_NO_MEMORY;
2423         goto error;
2424     }
2425
2426     removeData->ctx = ctx;
2427     removeData->linkedDevList = pLinkedDevList;
2428     removeData->resultCallback = resultCallback;
2429     removeData->numOfResults = 0;
2430     removeData->sizeOfResArray = numOfLinkedDev;
2431     removeData->hasError = false;
2432
2433     // 5. Send DELETE credential request to linked devices.
2434     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2435     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2436     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2437     {
2438         res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB,
2439                                            removeData->revokeTargetDev, curDev);
2440         if (OC_STACK_OK != res)
2441         {
2442             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\
2443                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2444             goto error;
2445         }
2446         res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB,
2447                                            removeData->revokeTargetDev, curDev);
2448         if (OC_STACK_OK != res)
2449         {
2450             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\
2451                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2452             totalRes = OC_STACK_ERROR;
2453         }
2454         else
2455         {
2456             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2457         }
2458     }
2459
2460     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2461     PMDeleteDeviceList(pOwnedDevList);
2462     OIC_LOG(INFO, TAG, "OUT SRPSyncDevice");
2463
2464     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2465
2466 error:
2467     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2468     PMDeleteDeviceList(pOwnedDevList);
2469     PMDeleteDeviceList(pLinkedDevList);
2470     if (removeData)
2471     {
2472         OICFree(removeData->revokeTargetDev);
2473         OICFree(removeData->removeRes);
2474         OICFree(removeData);
2475     }
2476     OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice");
2477     return res;
2478 }
2479
2480 /*
2481  * Function for remote reset
2482  * This function will send pstat PUT message to the target device to initiate remote reset.
2483  *
2484  * @param[in] pTargetDev Device information to be revoked.
2485  * @param[in] resultCallback callback provided by API user, callback will be called when
2486  *            credential revocation is finished.
2487  *            when there is an error, this user callback is called immediately.
2488  * @return OC_STACK_OK in case of success and other value otherwise.
2489  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2490  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2491  */
2492 OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev,
2493         OCProvisionResultCB resultCallback)
2494 {
2495     OIC_LOG(INFO, TAG, "IN SRPResetDevice");
2496     if (!pTargetDev)
2497     {
2498         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters");
2499         return OC_STACK_INVALID_PARAM;
2500     }
2501     if (!resultCallback)
2502     {
2503         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback");
2504         return OC_STACK_INVALID_CALLBACK;
2505     }
2506
2507     OCStackResult res = OC_STACK_ERROR;
2508     OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t));
2509     if (!pstat)
2510     {
2511         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2512         return OC_STACK_NO_MEMORY;
2513     }
2514
2515     pstat->cm = RESET;
2516     pstat->isOp = false;
2517     memcpy(pstat->deviceID.id, pTargetDev->doxm->deviceID.id, sizeof(OicUuid_t));
2518     pstat->tm = TAKE_OWNER;
2519     pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2520     pstat->smLen = 1;
2521     pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
2522     if (NULL == pstat->sm)
2523     {
2524         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2525         OICFree(pstat);
2526         return OC_STACK_NO_MEMORY;
2527     }
2528     pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2529
2530     OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload));
2531     if (!secPayload)
2532     {
2533         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2534         res = OC_STACK_NO_MEMORY;
2535         goto error;
2536     }
2537     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2538
2539     if (OC_STACK_OK != PstatToCBORPayload(pstat, &(secPayload->securityData),
2540                 &(secPayload->payloadSize), true))
2541     {
2542         OCPayloadDestroy((OCPayload *) secPayload);
2543         OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload");
2544         res = OC_STACK_NO_MEMORY;
2545         goto error;
2546     }
2547     OIC_LOG(DEBUG, TAG, "Created payload for pstat set");
2548     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2549
2550     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2551     if (!PMGenerateQuery(true,
2552                 pTargetDev->endpoint.addr,
2553                 pTargetDev->securePort,
2554                 pTargetDev->connType,
2555                 query, sizeof(query), OIC_RSRC_PSTAT_URI))
2556     {
2557         OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query");
2558         OCPayloadDestroy((OCPayload *) secPayload);
2559         res = OC_STACK_ERROR;
2560         goto error;
2561     }
2562     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2563     
2564     OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
2565     OCMethod method = OC_REST_POST;
2566     OCDoHandle handle = NULL;
2567     OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev);
2568     if (NULL == targetDev)
2569     {
2570         OIC_LOG(ERROR, TAG, "target dev is null");
2571         res = OC_STACK_ERROR;
2572         goto error;
2573     }
2574     cbData.cb = &SRPResetDeviceCB;
2575     cbData.context = (void *) targetDev;
2576     cbData.cd = NULL;
2577     OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server");
2578     res = OCDoResource(&handle, method, query,
2579             &targetDev->endpoint, (OCPayload *)secPayload,
2580             targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\
2581     if (OC_STACK_OK != res)
2582     {
2583         OIC_LOG(ERROR, TAG, "OCStack resource error");
2584     }
2585
2586 error:
2587     OICFree(pstat->sm);
2588     OICFree(pstat);
2589     OIC_LOG(INFO, TAG, "OUT SRPResetDevice");
2590     return res;
2591 }
2592
2593 /**
2594  * Internal Function to store results in result array during GetCredResourceCB.
2595  */
2596 static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
2597                                              OCStackResult stackresult)
2598 {
2599    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
2600            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2601    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2602           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2603    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2604    ++(GetSecData->numOfResults);
2605 }
2606
2607 /**
2608  * Callback handler of SRPGetCredResource.
2609  *
2610  * @param[in] ctx             ctx value passed to callback from calling function.
2611  * @param[in] UNUSED          handle to an invocation
2612  * @param[in] clientResponse  Response from queries to remote servers.
2613  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2614  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2615  */
2616 static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
2617                                                   OCClientResponse *clientResponse)
2618 {
2619     OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
2620     (void)UNUSED;
2621     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2622     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2623     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2624
2625     if (clientResponse)
2626     {
2627         if(OC_STACK_OK == clientResponse->result)
2628         {
2629             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2630             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2631
2632             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2633
2634             registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2635             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2636                                                     GetSecData->resArr,
2637                                                     false);
2638              OICFree(GetSecData->resArr);
2639              OICFree(GetSecData);
2640
2641             return OC_STACK_DELETE_TRANSACTION;
2642         }
2643     }
2644     registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2645     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2646                                             GetSecData->resArr,
2647                                             false);
2648     OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
2649     OICFree(GetSecData->resArr);
2650     OICFree(GetSecData);
2651
2652     return OC_STACK_DELETE_TRANSACTION;
2653 }
2654
2655
2656 OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2657         OCProvisionResultCB resultCallback)
2658 {
2659     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2660     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2661
2662     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2663     if(!PMGenerateQuery(true,
2664                         selectedDeviceInfo->endpoint.addr,
2665                         selectedDeviceInfo->securePort,
2666                         selectedDeviceInfo->connType,
2667                         query, sizeof(query), OIC_RSRC_CRED_URI))
2668     {
2669         OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
2670         return OC_STACK_ERROR;
2671     }
2672     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2673
2674     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2675     cbData.cb = &SRPGetCredResourceCB;
2676     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2677     if (NULL == GetSecData)
2678     {
2679         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2680         return OC_STACK_NO_MEMORY;
2681     }
2682     GetSecData->deviceInfo = selectedDeviceInfo;
2683     GetSecData->resultCallback = resultCallback;
2684     GetSecData->numOfResults=0;
2685     GetSecData->ctx = ctx;
2686
2687     int noOfRiCalls = 1;
2688     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2689     if (NULL == GetSecData->resArr)
2690     {
2691         OICFree(GetSecData);
2692         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2693         return OC_STACK_NO_MEMORY;
2694     }
2695     cbData.context = (void *)GetSecData;
2696     cbData.cd = NULL;
2697     OCMethod method = OC_REST_GET;
2698     OCDoHandle handle = NULL;
2699     OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
2700     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2701             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2702     if (OC_STACK_OK != ret)
2703     {
2704         OIC_LOG(ERROR, TAG, "OCStack resource error");
2705         OICFree(GetSecData->resArr);
2706         OICFree(GetSecData);
2707     }
2708     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2709     OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
2710
2711     return OC_STACK_OK;
2712 }
2713
2714 /**
2715  * Internal Function to store results in result array during GetACLResourceCB.
2716  */
2717 static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
2718                                              OCStackResult stackresult)
2719 {
2720    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
2721            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2722    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2723           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2724    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2725    ++(GetSecData->numOfResults);
2726 }
2727
2728 /**
2729  * Callback handler of SRPGetACLResource.
2730  *
2731  * @param[in] ctx             ctx value passed to callback from calling function.
2732  * @param[in] UNUSED          handle to an invocation
2733  * @param[in] clientResponse  Response from queries to remote servers.
2734  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2735  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2736  */
2737 static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
2738                                                   OCClientResponse *clientResponse)
2739 {
2740     OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
2741     (void)UNUSED;
2742     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2743     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2744     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2745
2746     if (clientResponse)
2747     {
2748         if(OC_STACK_OK == clientResponse->result)
2749         {
2750             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2751             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2752
2753             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2754
2755             registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2756             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2757                                                     GetSecData->resArr,
2758                                                     false);
2759              OICFree(GetSecData->resArr);
2760              OICFree(GetSecData);
2761
2762             return OC_STACK_DELETE_TRANSACTION;
2763         }
2764     }
2765     registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2766     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2767                                             GetSecData->resArr,
2768                                             false);
2769     OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
2770     OICFree(GetSecData->resArr);
2771     OICFree(GetSecData);
2772
2773     return OC_STACK_DELETE_TRANSACTION;
2774 }
2775
2776
2777 OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2778         OCProvisionResultCB resultCallback)
2779 {
2780     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2781     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2782
2783     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2784     if(!PMGenerateQuery(true,
2785                         selectedDeviceInfo->endpoint.addr,
2786                         selectedDeviceInfo->securePort,
2787                         selectedDeviceInfo->connType,
2788                         query, sizeof(query), OIC_RSRC_ACL_URI))
2789     {
2790         OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
2791         return OC_STACK_ERROR;
2792     }
2793     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2794
2795     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2796     cbData.cb = &SRPGetACLResourceCB;
2797     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2798     if (NULL == GetSecData)
2799     {
2800         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2801         return OC_STACK_NO_MEMORY;
2802     }
2803     GetSecData->deviceInfo = selectedDeviceInfo;
2804     GetSecData->resultCallback = resultCallback;
2805     GetSecData->numOfResults=0;
2806     GetSecData->ctx = ctx;
2807
2808     int noOfRiCalls = 1;
2809     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2810     if (NULL == GetSecData->resArr)
2811     {
2812         OICFree(GetSecData);
2813         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2814         return OC_STACK_NO_MEMORY;
2815     }
2816     cbData.context = (void *)GetSecData;
2817     cbData.cd = NULL;
2818     OCMethod method = OC_REST_GET;
2819     OCDoHandle handle = NULL;
2820     OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
2821     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2822             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2823     if (OC_STACK_OK != ret)
2824     {
2825         OIC_LOG(ERROR, TAG, "OCStack resource error");
2826         OICFree(GetSecData->resArr);
2827         OICFree(GetSecData);
2828     }
2829     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2830     OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
2831
2832     return OC_STACK_OK;
2833 }