Update the return value of MOT releated API.
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / multipleownershiptransfermanager.c
1 /* *****************************************************************
2  *
3  * Copyright 2016 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
21 #ifdef HAVE_TIME_H
22 #include <time.h>
23 #endif
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #ifdef HAVE_SYS_TIME_H
28 #include <sys/time.h>
29 #endif
30 #include <stdbool.h>
31 #include <string.h>
32
33 #include "utlist.h"
34 #include "logger.h"
35 #include "oic_malloc.h"
36 #include "oic_string.h"
37 #include "cacommon.h"
38 #include "cainterface.h"
39 #include "base64.h"
40 #include "cJSON.h"
41 #include "global.h"
42
43 #include "srmresourcestrings.h"
44 #include "doxmresource.h"
45 #include "pstatresource.h"
46 #include "credresource.h"
47 #include "aclresource.h"
48 #include "ownershiptransfermanager.h"
49 #include "securevirtualresourcetypes.h"
50 #include "oxmjustworks.h"
51 #include "pmtypes.h"
52 #include "pmutility.h"
53 #include "srmutility.h"
54 #include "provisioningdatabasemanager.h"
55 #include "oxmrandompin.h"
56 #include "ocpayload.h"
57 #include "payload_logging.h"
58 #include "oxmjustworks.h"
59 #include "oxmpreconfpin.h"
60 #include "oxmrandompin.h"
61
62 #define TAG "MULTIPLE_OTM"
63
64 /**********************************************************************
65  * API for Super Owner
66  **********************************************************************/
67
68 /**
69  * Structure to carry SuperOwner's multiple ownership transfer API data to callback.
70  */
71 typedef struct MOTContext MOTContext_t;
72 struct MOTContext
73 {
74     void *ctx;                                  /**< Pointer to user context.**/
75     const OCProvisionDev_t *deviceInfo;         /**< Pointer to OCProvisionDev_t.**/
76     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
77     OCProvisionResult_t *resArr;                /**< Result array.**/
78     int numOfResults;                           /**< Number of results in result array.**/
79     bool hasError;                              /**< Does MOT API have any error.. **/
80 };
81
82 /**
83  * Callback handler of security resource's POST request.
84  *
85  * @param[in] ctx             ctx value passed to callback from calling function.
86  * @param[in] UNUSED          handle to an invocation
87  * @param[in] clientResponse  Response from queries to remote servers.
88  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
89  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
90  */
91 static OCStackApplicationResult MOTUpdateSecurityResourceCB(void *ctx, OCDoHandle UNUSED,
92                                                 OCClientResponse *clientResponse)
93 {
94     OIC_LOG_V(INFO, TAG, "Inside MOTUpdateMomCB.");
95     (void)UNUSED;
96     MOTContext_t *motCtx = (MOTContext_t*)ctx;
97     VERIFY_NON_NULL(TAG, motCtx, ERROR);
98     VERIFY_NON_NULL(TAG, motCtx->resultCallback, ERROR);
99     VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
100
101     if(clientResponse)
102     {
103         memcpy(motCtx->resArr[0].deviceId.id, motCtx->deviceInfo->doxm->deviceID.id, sizeof(OicUuid_t));
104         motCtx->resArr[0].res = clientResponse->result;
105
106         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
107         {
108             motCtx->hasError = false;
109         }
110         else
111         {
112             motCtx->hasError = true;
113         }
114     }
115     else
116     {
117         OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
118         motCtx->resArr[0].res = OC_STACK_ERROR;
119         motCtx->hasError = true;
120     }
121
122     motCtx->resultCallback(motCtx->ctx, motCtx->numOfResults, motCtx->resArr, motCtx->hasError);
123
124 exit:
125     if(motCtx)
126     {
127         OICFree(motCtx->resArr);
128         OICFree(motCtx);
129     }
130     return OC_STACK_DELETE_TRANSACTION;
131 }
132
133 /**
134  * Internal API to send POST doxm request
135  */
136 static OCStackResult MOTSendPostDoxm(void *ctx,
137                                      const OCProvisionDev_t *targetDeviceInfo,
138                                      OCProvisionResultCB resultCallback,
139                                      const OicSecDoxm_t* doxm)
140 {
141     OCStackResult postMomRes = OC_STACK_ERROR;
142     OCSecurityPayload* secPayload = NULL;
143     MOTContext_t *motCtx = NULL;
144     bool freeFlag = true;
145
146     OIC_LOG(DEBUG, TAG, "IN MOTSendPostDoxm");
147
148     //Generate the security payload using updated doxm
149     secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
150     VERIFY_NON_NULL(TAG, secPayload, ERROR);
151     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
152
153     postMomRes = DoxmToCBORPayload(doxm, &secPayload->securityData, &secPayload->payloadSize, true);
154     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
155
156     OIC_LOG(DEBUG, TAG, "Created doxm payload to update doxm:");
157     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
158
159     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
160     bool queryGenRes = PMGenerateQuery(true,
161                                        targetDeviceInfo->endpoint.addr,
162                                        targetDeviceInfo->securePort,
163                                        targetDeviceInfo->connType,
164                                        query, sizeof(query), OIC_RSRC_DOXM_URI);
165     VERIFY_SUCCESS(TAG, (true == queryGenRes), ERROR);
166     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
167
168     //Create the MOT Context to handle the response message
169     motCtx = (MOTContext_t*)OICCalloc(1, sizeof(MOTContext_t));
170     VERIFY_NON_NULL(TAG, motCtx, ERROR);
171     motCtx->deviceInfo = targetDeviceInfo;
172     motCtx->resultCallback = resultCallback;
173     motCtx->numOfResults=1;
174     motCtx->hasError = false;
175     motCtx->ctx = ctx;
176     motCtx->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
177     VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
178
179     //Send POST request
180     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
181     cbData.cb = &MOTUpdateSecurityResourceCB;
182     cbData.context = (void *)motCtx;
183     OIC_LOG(DEBUG, TAG, "Sending POST 'doxm' request to resource server");
184     postMomRes = OCDoResource(NULL, OC_REST_POST, query,
185                               &targetDeviceInfo->endpoint, (OCPayload*)secPayload,
186                               targetDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
187     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
188
189     freeFlag = false;
190
191     OIC_LOG(DEBUG, TAG, "OUT MOTSendPostDoxm");
192
193 exit:
194     //If POST request successfully sent, motCtx will be cleaned from response handler.
195     if(freeFlag && motCtx)
196     {
197         OICFree(motCtx->resArr);
198         OICFree(motCtx);
199     }
200
201     return postMomRes;
202 }
203
204 /**
205  * API to update 'doxm.mom' to resource server.
206  *
207  * @param[in] targetDeviceInfo Selected target device.
208  * @param[in] momType Mode of multiple ownership transfer (ref. oic.sec.mom)
209  * @param[in] resultCallback callback provided by API user, callback will be called when
210  *            POST 'mom' request recieves a response from resource server.
211  * @return OC_STACK_OK in case of success and other value otherwise.
212  */
213 OCStackResult MOTChangeMode(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
214                             const OicSecMomType_t momType, OCProvisionResultCB resultCallback)
215 {
216     OCStackResult postMomRes = OC_STACK_INVALID_PARAM;
217     OicSecDoxm_t* doxm = NULL;
218     uint8_t* doxmPayload = NULL;
219     size_t doxmPayloadLen = 0;
220
221     OIC_LOG(DEBUG, TAG, "IN MOTChangeMode");
222
223     VERIFY_SUCCESS(TAG, (OIC_NUMBER_OF_MOM_TYPE > momType), ERROR);
224     VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
225     postMomRes = OC_STACK_INVALID_CALLBACK;
226     VERIFY_NON_NULL(TAG, resultCallback, ERROR);
227
228     //Dulpicate doxm resource to update the 'mom' property
229     postMomRes = DoxmToCBORPayload(targetDeviceInfo->doxm, &doxmPayload, &doxmPayloadLen, false);
230     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
231
232     postMomRes = CBORPayloadToDoxm(doxmPayload, doxmPayloadLen, &doxm);
233     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
234     VERIFY_NON_NULL(TAG, doxm, ERROR);
235
236     if(NULL == doxm->mom)
237     {
238         postMomRes = OC_STACK_NO_MEMORY;
239         doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
240         VERIFY_NON_NULL(TAG, (doxm->mom), ERROR);
241     }
242     doxm->mom->mode = momType;
243
244     //Send POST reuqest for update doxm
245     postMomRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, doxm);
246     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
247
248     OIC_LOG(DEBUG, TAG, "OUT MOTChangeMode");
249
250 exit:
251     OICFree(doxmPayload);
252     DeleteDoxmBinData(doxm);
253     return postMomRes;
254 }
255
256 /**
257  * API to add 'doxm.oxms' to resource server.
258  *
259  * @param[in] targetDeviceInfo Selected target device.
260  * @param[in] newOxm  OxMs to be added (ref. oic.sec.oxm)
261  * @param[in] resultCallback callback provided by API user, callback will be called when
262  *            POST 'oxms' request recieves a response from resource server.
263  * @return OC_STACK_OK in case of success and other value otherwise.
264  */
265 OCStackResult MOTAddMOTMethod(void *ctx, OCProvisionDev_t *targetDeviceInfo,
266                                  const OicSecOxm_t newOxm, OCProvisionResultCB resultCallback)
267 {
268     OCStackResult postOxmRes = OC_STACK_INVALID_PARAM;
269     OicSecOxm_t* newOxms = NULL;
270     uint8_t* doxmPayload = NULL;
271     size_t doxmPayloadLen = 0;
272
273     OIC_LOG(DEBUG, TAG, "IN MOTAddMOTMethod");
274
275     VERIFY_SUCCESS(TAG, (OIC_OXM_COUNT > newOxm), ERROR);
276     VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
277     postOxmRes = OC_STACK_INVALID_CALLBACK;
278     VERIFY_NON_NULL(TAG, resultCallback, ERROR);
279     postOxmRes = OC_STACK_NO_MEMORY;
280
281     for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
282     {
283         if(targetDeviceInfo->doxm->oxm[i] == newOxm)
284         {
285             OIC_LOG_V(INFO, TAG, "[%d] OxM already supported", (int)newOxm);
286             OCProvisionResult_t* resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
287             VERIFY_NON_NULL(TAG, resArr, ERROR);
288             resArr->res = OC_STACK_OK;
289             memcpy(resArr->deviceId.id, targetDeviceInfo->doxm->deviceID.id, sizeof(resArr->deviceId.id));
290             resultCallback(ctx, 1, resArr, false);
291             return OC_STACK_OK;
292         }
293     }
294
295     newOxms = (OicSecOxm_t*)OICMalloc(sizeof(OicSecOxm_t) * (targetDeviceInfo->doxm->oxmLen + 1));
296     VERIFY_NON_NULL(TAG, newOxms , ERROR);
297
298     for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
299     {
300         newOxms[i] = targetDeviceInfo->doxm->oxm[i];
301     }
302     newOxms[targetDeviceInfo->doxm->oxmLen] = newOxm;
303     targetDeviceInfo->doxm->oxmLen++;
304     OICFree(targetDeviceInfo->doxm->oxm);
305     targetDeviceInfo->doxm->oxm = newOxms;
306
307     //Send POST reuqest for update doxm
308     postOxmRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, targetDeviceInfo->doxm);
309     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postOxmRes), ERROR);
310
311     OIC_LOG(DEBUG, TAG, "OUT MOTAddMOTMethod");
312
313 exit:
314     OICFree(doxmPayload);
315     return postOxmRes;
316 }
317
318 /**
319  * API to update 'doxm.oxmsel' to resource server.
320  *
321  * @param[in] targetDeviceInfo Selected target device.
322   * @param[in] oxmSelValue Method of multiple ownership transfer (ref. oic.sec.oxm)
323  * @param[in] resultCallback callback provided by API user, callback will be called when
324  *            POST 'oxmsel' request recieves a response from resource server.
325  * @return OC_STACK_OK in case of success and other value otherwise.
326  */
327 OCStackResult MOTSelectMOTMethod(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
328                                  const OicSecOxm_t oxmSelValue, OCProvisionResultCB resultCallback)
329 {
330     OCStackResult postMomRes = OC_STACK_INVALID_PARAM;
331     OicSecDoxm_t* doxm = NULL;
332     uint8_t* doxmPayload = NULL;
333     size_t doxmPayloadLen = 0;
334
335     OIC_LOG(DEBUG, TAG, "IN MOTSelectOTMethod");
336
337     VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
338     VERIFY_NON_NULL(TAG, resultCallback, ERROR);
339
340     bool isValidOxmsel = false;
341     for(size_t i = 0; i < targetDeviceInfo->doxm->oxmLen; i++)
342     {
343         if(targetDeviceInfo->doxm->oxm[i] == oxmSelValue)
344         {
345             isValidOxmsel = true;
346             break;
347         }
348     }
349     VERIFY_SUCCESS(TAG, isValidOxmsel, ERROR);
350
351     //Dulpicate doxm resource to update the 'oxmsel' property
352     postMomRes = DoxmToCBORPayload(targetDeviceInfo->doxm, &doxmPayload, &doxmPayloadLen, false);
353     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
354
355     postMomRes = CBORPayloadToDoxm(doxmPayload, doxmPayloadLen, &doxm);
356     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
357     VERIFY_NON_NULL(TAG, doxm, ERROR);
358
359     doxm->oxmSel = oxmSelValue;
360
361     //Send POST reuqest for update doxm
362     postMomRes = MOTSendPostDoxm(ctx, targetDeviceInfo, resultCallback, doxm);
363     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postMomRes), ERROR);
364
365     OIC_LOG(DEBUG, TAG, "OUT MOTSelectOTMethod");
366
367 exit:
368     OICFree(doxmPayload);
369     DeleteDoxmBinData(doxm);
370     return postMomRes;
371 }
372
373 /**
374  * API to provision preconfigured PIN to resource server.
375  *
376  * @param[in] targetDeviceInfo Selected target device.
377  * @param[in] preconfPIN Preconfig PIN which is used while multiple owner authentication
378  * @param[in] preconfPINLen Byte length of preconfig PIN
379  * @param[in] resultCallback callback provided by API user, callback will be called when
380  *            POST credential request recieves a response from resource server.
381  * @return OC_STACK_OK in case of success and other value otherwise.
382  */
383 OCStackResult MOTProvisionPreconfigPIN(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
384                                  const char* preconfPIN, size_t preconfPINLen, OCProvisionResultCB resultCallback)
385 {
386     OCStackResult postCredRes = OC_STACK_INVALID_PARAM;
387     bool freeFlag = true;
388     OCSecurityPayload* secPayload = NULL;
389     MOTContext_t *motCtx = NULL;
390     OicSecCred_t* pinCred = NULL;
391
392     OIC_LOG(DEBUG, TAG, "IN MOTProvisionPreconfigPIN");
393
394     VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
395     VERIFY_NON_NULL(TAG, resultCallback, ERROR);
396     VERIFY_NON_NULL(TAG, preconfPIN, ERROR);
397     VERIFY_SUCCESS(TAG, (0 != preconfPINLen), ERROR);
398     VERIFY_SUCCESS(TAG, (0 != preconfPINLen && OXM_PRECONFIG_PIN_SIZE >= preconfPINLen), ERROR);
399
400     postCredRes = OC_STACK_NO_MEMORY;
401     //Generate PIN based credential
402     pinCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
403     VERIFY_NON_NULL(TAG, pinCred, ERROR);
404
405     pinCred->privateData.data = (uint8_t*)OICMalloc(preconfPINLen + 1);
406     VERIFY_NON_NULL(TAG, pinCred->privateData.data, ERROR);
407
408     memcpy(pinCred->privateData.data, preconfPIN, preconfPINLen);
409     pinCred->privateData.data[preconfPINLen] = '\0';
410     pinCred->privateData.len = preconfPINLen;
411     pinCred->privateData.encoding = OIC_ENCODING_RAW;
412     pinCred->credType = PIN_PASSWORD;
413     OICStrcpy(pinCred->subject.id, sizeof(pinCred->subject.id), WILDCARD_SUBJECT_ID.id);
414
415     //Generate the security payload using updated doxm
416     secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
417     VERIFY_NON_NULL(TAG, secPayload, ERROR);
418     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
419
420     postCredRes = CredToCBORPayload(pinCred, &secPayload->securityData, &secPayload->payloadSize, false);
421     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postCredRes), ERROR);
422
423     OIC_LOG(DEBUG, TAG, "Created Credential payload to register PIN credential:");
424     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
425
426     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
427     bool queryGenRes = PMGenerateQuery(true,
428                                        targetDeviceInfo->endpoint.addr,
429                                        targetDeviceInfo->securePort,
430                                        targetDeviceInfo->connType,
431                                        query, sizeof(query), OIC_RSRC_CRED_URI);
432     VERIFY_SUCCESS(TAG, (true == queryGenRes), ERROR);
433     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
434
435     //Create the MOT Context to handle the response message
436     motCtx = (MOTContext_t*)OICCalloc(1, sizeof(MOTContext_t));
437     VERIFY_NON_NULL(TAG, motCtx, ERROR);
438     motCtx->deviceInfo = targetDeviceInfo;
439     motCtx->resultCallback = resultCallback;
440     motCtx->numOfResults=1;
441     motCtx->hasError = false;
442     motCtx->ctx = ctx;
443     motCtx->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
444     VERIFY_NON_NULL(TAG, motCtx->resArr, ERROR);
445
446     //Send POST request
447     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
448     cbData.cb = &MOTUpdateSecurityResourceCB;
449     cbData.context = (void *)motCtx;
450     OIC_LOG(DEBUG, TAG, "Sending POST Preconfiged PIN credenatial request to resource server");
451     postCredRes = OCDoResource(NULL, OC_REST_POST, query,
452                               &targetDeviceInfo->endpoint, (OCPayload*)secPayload,
453                               targetDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
454     VERIFY_SUCCESS(TAG, (OC_STACK_OK == postCredRes), ERROR);
455
456     freeFlag = false;
457
458     OIC_LOG(DEBUG, TAG, "OUT MOTProvisionPreconfigPIN");
459
460     return postCredRes;
461
462 exit:
463     //If POST request successfully sent, motCtx will be cleaned from response handler.
464     if(freeFlag && motCtx)
465     {
466         OICFree(motCtx->resArr);
467         OICFree(motCtx);
468     }
469     if(pinCred)
470     {
471         OICFree(pinCred->privateData.data);
472         OICFree(pinCred);
473     }
474     return postCredRes;
475 }
476
477
478 /**********************************************************************
479  * API for Sub Owner
480  **********************************************************************/
481
482 static OCStackResult StartMultipleOwnershipTransfer(OTMContext_t* motCtx,
483                                                     OCProvisionDev_t* selectedDevice);
484
485 /**
486  * Array to store the callbacks for each owner transfer method.
487  */
488 static OTMCallbackData_t g_MOTCbDatas[OIC_OXM_COUNT] = {
489         //Just works
490         {.loadSecretCB = LoadSecretJustWorksCallback,
491           .createSecureSessionCB = CreateSecureSessionJustWorksCallback,
492           .createSelectOxmPayloadCB = NULL,
493           .createOwnerTransferPayloadCB = NULL},
494
495           //Random PIN
496         {.loadSecretCB = InputPinCodeCallback,
497           .createSecureSessionCB = CreateSecureSessionRandomPinCallback,
498           .createSelectOxmPayloadCB = NULL,
499           .createOwnerTransferPayloadCB = NULL},
500
501         //Manufacturer Cert
502         {.loadSecretCB = NULL,
503           .createSecureSessionCB = NULL,
504           .createSelectOxmPayloadCB = NULL,
505           .createOwnerTransferPayloadCB = NULL},
506
507           //Preconfig PIN
508         {.loadSecretCB = LoadPreconfPinCodeCallback,
509           .createSecureSessionCB = CreateSecureSessionPreconfPinCallback,
510           .createSelectOxmPayloadCB = NULL,
511           .createOwnerTransferPayloadCB = NULL},
512 };
513
514 static OTMContext_t* g_MotCtx = NULL;
515
516 static bool IsComplete(OTMContext_t* otmCtx)
517 {
518     for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
519     {
520         if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
521         {
522             return false;
523         }
524     }
525
526     return true;
527 }
528
529 /**
530  * Function to save the result of multiple ownership transfer.
531  *
532  * @param[in,out] motCtx   Context instance of multiple ownership transfer.
533  * @param[in] res   result of multiple ownership transfer.
534  */
535 static void SetMOTResult(OTMContext_t* motCtx, const OCStackResult res)
536 {
537     OIC_LOG_V(DEBUG, TAG, "IN SetMOTResult : %d ", res);
538
539     VERIFY_NON_NULL(TAG, motCtx, ERROR);
540
541     if(motCtx->selectedDeviceInfo)
542     {
543         //Revert psk_info callback in case of random PIN OxM
544         if(OIC_RANDOM_DEVICE_PIN == motCtx->selectedDeviceInfo->doxm->oxmSel ||
545            OIC_PRECONFIG_PIN == motCtx->selectedDeviceInfo->doxm->oxmSel)
546         {
547             if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
548             {
549                 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler.");
550             }
551             OicUuid_t emptyUuid = { .id={0}};
552             SetUuidForPinBasedOxm(&emptyUuid);
553         }
554
555         for(size_t i = 0; i < motCtx->ctxResultArraySize; i++)
556         {
557             if(memcmp(motCtx->selectedDeviceInfo->doxm->deviceID.id,
558                       motCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
559             {
560                 motCtx->ctxResultArray[i].res = res;
561                 if(OC_STACK_OK != res)
562                 {
563                     motCtx->ctxHasError = true;
564                 }
565             }
566         }
567
568         g_MotCtx = NULL;
569
570         //If all request is completed, invoke the user callback.
571         if(IsComplete(motCtx))
572         {
573             motCtx->ctxResultCallback(motCtx->userCtx, motCtx->ctxResultArraySize,
574                                        motCtx->ctxResultArray, motCtx->ctxHasError);
575
576             OICFree(motCtx->ctxResultArray);
577             OICFree(motCtx);
578         }
579         else
580         {
581             if(OC_STACK_OK != StartMultipleOwnershipTransfer(motCtx,
582                                                      motCtx->selectedDeviceInfo->next))
583             {
584                 OIC_LOG(ERROR, TAG, "Failed to StartMultipleOwnershipTransfer");
585             }
586         }
587     }
588
589 exit:
590     OIC_LOG(DEBUG, TAG, "OUT SetMOTResult");
591 }
592
593 /**
594  * API to add preconfigured PIN to local SVR DB.
595  *
596  * @param[in] targetDeviceInfo Selected target device.
597  * @param[in] preconfPIN Preconfig PIN which is used while multiple owner authentication
598  * @param[in] preconfPINLen Byte length of preconfig PIN
599  * @param[in] resultCallback callback provided by API user, callback will be called when
600  *            POST credential request recieves a response from resource server.
601  * @return OC_STACK_OK in case of success and other value otherwise.
602  */
603 OCStackResult MOTAddPreconfigPIN(const OCProvisionDev_t *targetDeviceInfo,
604                                  const char* preconfPIN, size_t preconfPINLen)
605 {
606     OCStackResult addCredRes = OC_STACK_INVALID_PARAM;
607     OicSecCred_t* pinCred = NULL;
608     bool freeFlag = true;
609
610     OIC_LOG(DEBUG, TAG, "IN MOTAddPreconfigPIN");
611
612     VERIFY_NON_NULL(TAG, targetDeviceInfo, ERROR);
613     VERIFY_NON_NULL(TAG, preconfPIN, ERROR);
614     VERIFY_SUCCESS(TAG, (0 != preconfPINLen), ERROR);
615     VERIFY_SUCCESS(TAG, (0 != preconfPINLen && OXM_PRECONFIG_PIN_SIZE >= preconfPINLen), ERROR);
616
617     OicSecCred_t* prevCred = GetCredResourceData(&targetDeviceInfo->doxm->deviceID);
618     if(NULL != prevCred)
619     {
620         OIC_LOG(INFO, TAG, "PIN/PW Credential already exist!");
621         return OC_STACK_OK;
622     }
623
624     addCredRes = OC_STACK_NO_MEMORY;
625     //Generate PIN based credential
626     pinCred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
627     VERIFY_NON_NULL(TAG, pinCred, ERROR);
628
629     pinCred->privateData.data = (uint8_t*)OICMalloc(preconfPINLen + 1);
630     VERIFY_NON_NULL(TAG, pinCred->privateData.data, ERROR);
631
632     memcpy(pinCred->privateData.data, preconfPIN, preconfPINLen);
633     pinCred->privateData.data[preconfPINLen] = '\0';
634     pinCred->privateData.len = preconfPINLen;
635     pinCred->privateData.encoding = OIC_ENCODING_RAW;
636     pinCred->credType = PIN_PASSWORD;
637     memcpy(pinCred->subject.id, targetDeviceInfo->doxm->deviceID.id, sizeof(pinCred->subject.id));
638
639     addCredRes = AddCredential(pinCred);
640     VERIFY_SUCCESS(TAG, (OC_STACK_OK == addCredRes), ERROR);
641
642     OIC_LOG(DEBUG, TAG, "OUT MOTAddPreconfigPIN");
643
644     return addCredRes;
645
646 exit:
647     if(pinCred)
648     {
649         OICFree(pinCred->privateData.data);
650         OICFree(pinCred);
651     }
652     return addCredRes;
653 }
654
655 /**
656  * Function to save the SubOwner PSK.
657  *
658  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
659  * @return  OC_STACK_OK on success
660  */
661 static OCStackResult SaveSubOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
662 {
663     OIC_LOG(DEBUG, TAG, "IN SaveSubOwnerPSK");
664
665     OCStackResult res = OC_STACK_ERROR;
666
667     CAEndpoint_t endpoint;
668     memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
669     OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
670     endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
671     endpoint.port = selectedDeviceInfo->securePort;
672     endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
673
674     OicUuid_t ownerDeviceID = {.id={0}};
675     if (OC_STACK_OK != GetDoxmDeviceID(&ownerDeviceID))
676     {
677         OIC_LOG(ERROR, TAG, "Error while retrieving SubOwner's device ID");
678         return res;
679     }
680
681     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
682     OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
683
684     //Generating SubOwnerPSK
685     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
686             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
687             strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
688             ownerDeviceID.id, sizeof(ownerDeviceID.id),
689             selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
690             ownerPSK, OWNER_PSK_LENGTH_128);
691
692     if (CA_STATUS_OK == pskRet)
693     {
694         OIC_LOG(INFO, TAG, "SubOwner PSK dump:");
695         OIC_LOG_BUFFER(INFO, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
696         //Generating new credential for provisioning tool
697         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
698                                       SYMMETRIC_PAIR_WISE_KEY, NULL,
699                                       &ownerKey, &ownerDeviceID, &ownerDeviceID);
700         VERIFY_NON_NULL(TAG, cred, ERROR);
701
702         uint32_t outSize = 0;
703         size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
704         char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
705         VERIFY_NON_NULL(TAG, b64Buf, ERROR);
706         b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
707
708         OICFree( cred->privateData.data );
709         cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
710         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
711
712         strncpy(cred->privateData.data, b64Buf, outSize);
713         cred->privateData.data[outSize] = '\0';
714         cred->privateData.encoding = OIC_ENCODING_BASE64;
715         cred->privateData.len = outSize;
716         OICFree(b64Buf);
717
718         //Add SubOwnerPSK
719         res = AddCredential(cred);
720         if(res != OC_STACK_OK)
721         {
722             DeleteCredList(cred);
723             return res;
724         }
725     }
726     else
727     {
728         OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
729     }
730
731     OIC_LOG(DEBUG, TAG, "OUT SaveSubOwnerPSK");
732 exit:
733     return res;
734 }
735
736
737 /**
738  * Response handler for update subowner crendetial request.
739  *
740  * @param[in] ctx             ctx value passed to callback from calling function.
741  * @param[in] UNUSED          handle to an invocation
742  * @param[in] clientResponse  Response from queries to remote servers.
743  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
744  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
745  */
746 static OCStackApplicationResult SubOwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
747                                 OCClientResponse *clientResponse)
748 {
749     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
750     VERIFY_NON_NULL(TAG, ctx, WARNING);
751
752     OIC_LOG(DEBUG, TAG, "IN SubOwnerCredentialHandler");
753     (void)UNUSED;
754     OCStackResult res = OC_STACK_ERROR;
755     OTMContext_t* motCtx = (OTMContext_t*)ctx;
756
757     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
758     {
759         if(motCtx && motCtx->selectedDeviceInfo)
760         {
761             //Close the temporal secure session to verify the owner credential
762             CAEndpoint_t* endpoint = (CAEndpoint_t *)&motCtx->selectedDeviceInfo->endpoint;
763             endpoint->port = motCtx->selectedDeviceInfo->securePort;
764             CAResult_t caResult = CAcloseSslSession(endpoint);
765             if(CA_STATUS_OK != caResult)
766             {
767                 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
768                 SetMOTResult(motCtx, OC_STACK_ERROR);
769                 return OC_STACK_DELETE_TRANSACTION;
770             }
771
772             // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
773             caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
774             if(CA_STATUS_OK != caResult)
775             {
776                 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
777                 SetMOTResult(motCtx, OC_STACK_ERROR);
778                 return OC_STACK_DELETE_TRANSACTION;
779             }
780
781             res = PDMAddDevice(&motCtx->selectedDeviceInfo->doxm->deviceID);
782              if (OC_STACK_OK == res)
783              {
784                     OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
785              }
786               else
787              {
788                   OIC_LOG(ERROR, TAG, "MOT is complete but adding information to DB is failed.");
789              }
790
791             SetMOTResult(motCtx, res);
792         }
793     }
794     else
795     {
796         res = clientResponse->result;
797         OIC_LOG_V(ERROR, TAG, "SubOwnerCredentialHandler : Unexpected result %d", res);
798         SetMOTResult(motCtx, res);
799     }
800
801     OIC_LOG(DEBUG, TAG, "OUT SubOwnerCredentialHandler");
802
803 exit:
804     return  OC_STACK_DELETE_TRANSACTION;
805 }
806
807
808 static OCStackResult PostSubOwnerCredential(OTMContext_t* motCtx)
809 {
810     OIC_LOG(DEBUG, TAG, "IN PostSubOwnerCredential");
811
812     if(!motCtx || !motCtx->selectedDeviceInfo)
813     {
814         OIC_LOG(ERROR, TAG, "Invalid parameters");
815         return OC_STACK_INVALID_PARAM;
816     }
817
818     OCProvisionDev_t* deviceInfo = motCtx->selectedDeviceInfo;
819     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
820
821     if(!PMGenerateQuery(true,
822                         deviceInfo->endpoint.addr, deviceInfo->securePort,
823                         deviceInfo->connType,
824                         query, sizeof(query), OIC_RSRC_CRED_URI))
825     {
826         OIC_LOG(ERROR, TAG, "PostSubOwnerCredential : Failed to generate query");
827         return OC_STACK_ERROR;
828     }
829     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
830     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
831     if(!secPayload)
832     {
833         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
834         return OC_STACK_NO_MEMORY;
835     }
836
837     //Generate sub-owner credential for new device
838     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
839     const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
840     if(!ownerCredential)
841     {
842         OIC_LOG(ERROR, TAG, "Can not find SubOwnerPSK.");
843         return OC_STACK_NO_RESOURCE;
844     }
845
846     OicUuid_t ownerId = {.id={0}};
847     if(OC_STACK_OK == GetDoxmDeviceID(&ownerId))
848     {
849         OicSecCred_t newCredential;
850         memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
851         newCredential.next = NULL;
852
853         //Set subject ID as SubOwner's ID
854         memcpy(&(newCredential.subject), &ownerId, sizeof(OicUuid_t));
855
856         //Set eowner ID as SubOwner's ID
857         if(NULL == newCredential.eownerID)
858         {
859             newCredential.eownerID = OICCalloc(1, sizeof(OicUuid_t));
860             if(NULL == newCredential.eownerID)
861             {
862                 return OC_STACK_NO_MEMORY;
863             }
864         }
865         memcpy(newCredential.eownerID->id, ownerId.id, sizeof(ownerId.id));
866
867         //Fill private data as empty string
868         newCredential.privateData.data = "";
869         newCredential.privateData.len = 0;
870         newCredential.privateData.encoding = ownerCredential->privateData.encoding;
871 #ifdef __WITH_X509__
872         newCredential.publicData.data = NULL;
873         newCredential.publicData.len = 0;
874 #endif
875         //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
876         if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
877                                         &secPayload->payloadSize, 0))
878         {
879             OICFree(secPayload);
880             OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
881             return OC_STACK_ERROR;
882         }
883         OIC_LOG(DEBUG, TAG, "Cred Payload:");
884         OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
885
886         OCCallbackData cbData;
887         cbData.cb = &SubOwnerCredentialHandler;
888         cbData.context = (void *)motCtx;
889         cbData.cd = NULL;
890         OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
891                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
892                                          deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
893         if (res != OC_STACK_OK)
894         {
895             OIC_LOG(ERROR, TAG, "OCStack resource error");
896         }
897     }
898     else
899     {
900         OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
901         return OC_STACK_NO_RESOURCE;
902     }
903
904     OIC_LOG(DEBUG, TAG, "OUT PostSubOwnerCredential");
905
906     return OC_STACK_OK;
907 }
908
909
910 /**
911  * Function to handle the handshake result in MOT.
912  * This function will be invoked after DTLS handshake
913  * @param   endPoint  [IN] The remote endpoint.
914  * @param   errorInfo [IN] Error information from the endpoint.
915  * @return  NONE
916  */
917 static void MOTDtlsHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
918 {
919     if(NULL != g_MotCtx && NULL != g_MotCtx->selectedDeviceInfo &&
920        NULL != endpoint && NULL != info)
921     {
922         OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
923                  endpoint->addr, endpoint->port, info->result);
924
925         OicSecDoxm_t* newDevDoxm = g_MotCtx->selectedDeviceInfo->doxm;
926
927         if(NULL != newDevDoxm)
928         {
929             OicUuid_t emptyUuid = {.id={0}};
930
931             //Make sure the address matches.
932             if(strncmp(g_MotCtx->selectedDeviceInfo->endpoint.addr,
933                endpoint->addr,
934                sizeof(endpoint->addr)) == 0 &&
935                g_MotCtx->selectedDeviceInfo->securePort == endpoint->port)
936             {
937                 OCStackResult res = OC_STACK_ERROR;
938
939                 //If temporal secure sesstion established successfully
940                 if(CA_STATUS_OK == info->result)
941                 {
942                     //Delete previous credential such as preconfigured-pin
943                     RemoveCredential(&(g_MotCtx->selectedDeviceInfo->doxm->deviceID));
944
945                     res = SaveSubOwnerPSK(g_MotCtx->selectedDeviceInfo);
946                     if(OC_STACK_OK == res)
947                     {
948                         //POST sub owner credential to new device.
949                         res = PostSubOwnerCredential(g_MotCtx);
950                         if(OC_STACK_OK != res)
951                         {
952                             OIC_LOG(ERROR, TAG,
953                                     "Failed to send POST request for SubOwner Credential");
954                             SetMOTResult(g_MotCtx, res);
955                         }
956                     }
957                     else
958                     {
959                         OIC_LOG(ERROR, TAG, "Failed to save the SubOwner PSK.");
960                         SetMOTResult(g_MotCtx, res);
961                     }
962                 }
963                 //In case of authentication failure
964                 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
965                 {
966                     //in case of error from wrong PIN, re-start the ownership transfer
967                     if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
968                     {
969                         OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
970
971                         g_MotCtx->attemptCnt++;
972
973                         if(WRONG_PIN_MAX_ATTEMP > g_MotCtx->attemptCnt)
974                         {
975                             res = StartMultipleOwnershipTransfer(g_MotCtx, g_MotCtx->selectedDeviceInfo);
976                             if(OC_STACK_OK != res)
977                             {
978                                 SetMOTResult(g_MotCtx, res);
979                                 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
980                             }
981                         }
982                         else
983                         {
984                             OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
985                             SetMOTResult(g_MotCtx, OC_STACK_AUTHENTICATION_FAILURE);
986                         }
987                     }
988                     else
989                     {
990                         OIC_LOG(ERROR, TAG, "Failed to establish DTLS session.");
991                         SetMOTResult(g_MotCtx, OC_STACK_AUTHENTICATION_FAILURE);
992                     }
993                 }
994             }
995         }
996     }
997 }
998
999 static OCStackResult StartMultipleOwnershipTransfer(OTMContext_t* motCtx,
1000                                                     OCProvisionDev_t* selectedDevice)
1001 {
1002     OIC_LOG(INFO, TAG, "IN StartMultipleOwnershipTransfer");
1003     OCStackResult res = OC_STACK_INVALID_PARAM;
1004
1005     VERIFY_NON_NULL(TAG, selectedDevice, ERROR);
1006     VERIFY_NON_NULL(TAG, selectedDevice->doxm, ERROR);
1007
1008     motCtx->selectedDeviceInfo = selectedDevice;
1009
1010     //Register DTLS event handler to catch the dtls event while handshake
1011     if(CA_STATUS_OK != CAregisterSslHandshakeCallback(MOTDtlsHandshakeCB))
1012     {
1013         OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
1014     }
1015
1016     size_t oxmSel = (size_t)(selectedDevice->doxm->oxmSel);
1017     OIC_LOG_V(DEBUG, TAG, "Multiple Ownership Transfer method = %d", selectedDevice->doxm->oxmSel);
1018
1019     if(OIC_PRECONFIG_PIN != oxmSel && OIC_RANDOM_DEVICE_PIN != oxmSel)
1020     {
1021         OIC_LOG(ERROR, TAG, "Unsupported OxM");
1022         return OC_STACK_ERROR;
1023     }
1024
1025     if(OIC_RANDOM_DEVICE_PIN == selectedDevice->doxm->oxmSel)
1026     {
1027         if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm))
1028         {
1029             OIC_LOG(ERROR, TAG, "Failed to register DTLS credential handler for Random PIN OxM.");
1030         }
1031     }
1032
1033     res = g_MOTCbDatas[oxmSel].loadSecretCB(motCtx);
1034     VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1035
1036     //Save the current context instance to use on the dtls handshake callback
1037     g_MotCtx = motCtx;
1038
1039     res = g_MOTCbDatas[oxmSel].createSecureSessionCB(motCtx);
1040     VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1041
1042     OIC_LOG(INFO, TAG, "OUT StartMultipleOwnershipTransfer");
1043
1044 exit:
1045     return res;
1046 }
1047
1048 OCStackResult MOTDoOwnershipTransfer(void* ctx,
1049                                      OCProvisionDev_t *selectedDevicelist,
1050                                      OCProvisionResultCB resultCallback)
1051 {
1052     OIC_LOG(DEBUG, TAG, "IN MOTDoOwnershipTransfer");
1053     OCStackResult res = OC_STACK_INVALID_PARAM;
1054     OTMContext_t* motCtx = NULL;
1055     OCProvisionDev_t* pCurDev = NULL;
1056
1057     VERIFY_NON_NULL(TAG, selectedDevicelist, ERROR);
1058     VERIFY_NON_NULL(TAG, resultCallback, ERROR);
1059
1060     res = OC_STACK_NO_MEMORY;
1061     motCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1062     VERIFY_NON_NULL(TAG, motCtx, ERROR);
1063
1064     motCtx->ctxResultCallback = resultCallback;
1065     motCtx->ctxHasError = false;
1066     motCtx->userCtx = ctx;
1067     motCtx->ctxResultArraySize = 0;
1068     LL_FOREACH(selectedDevicelist, pCurDev)
1069     {
1070         motCtx->ctxResultArraySize++;
1071     }
1072
1073     motCtx->ctxResultArray =
1074         (OCProvisionResult_t*)OICCalloc(motCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1075     VERIFY_NON_NULL(TAG, motCtx->ctxResultArray, ERROR);
1076
1077     //Fill the device UUID for result array.
1078     size_t devIdx = 0;
1079     res = OC_STACK_OK;
1080     pCurDev = NULL;
1081     LL_FOREACH(selectedDevicelist, pCurDev)
1082     {
1083         //Checking duplication of Device ID.
1084         bool isDuplicate = true;
1085         res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1086         VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1087
1088         if (isDuplicate)
1089         {
1090             bool isStale = false;
1091             res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1092             VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1093             VERIFY_SUCCESS(TAG, isStale, ERROR);
1094
1095             if(isStale)
1096             {
1097                 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1098                                    "this UUID will be removed from PDM");
1099
1100                 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1101                 VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1102             }
1103         }
1104
1105         memcpy(motCtx->ctxResultArray[devIdx].deviceId.id,
1106                pCurDev->doxm->deviceID.id,
1107                UUID_LENGTH);
1108         motCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1109         devIdx++;
1110     }
1111
1112     res = StartMultipleOwnershipTransfer(motCtx, selectedDevicelist);
1113     VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
1114
1115     OIC_LOG(DEBUG, TAG, "OUT MOTDoOwnershipTransfer");
1116
1117 exit:
1118     if(OC_STACK_OK != res)
1119     {
1120         if(motCtx)
1121         {
1122             OICFree(motCtx->ctxResultArray);
1123             OICFree(motCtx);
1124         }
1125     }
1126     return res;
1127 }