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