e07ebab3fb9d34313513cc844ced673952e7886c
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / ownershiptransfermanager.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
21 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
25 //
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
31 #endif
32
33 #include "iotivity_config.h"
34 #ifdef HAVE_TIME_H
35 #include <time.h>
36 #endif
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #ifdef HAVE_SYS_TIME_H
41 #include <sys/time.h>
42 #endif
43 #include <stdbool.h>
44 #include <string.h>
45
46 #include "logger.h"
47 #include "oic_malloc.h"
48 #include "oic_string.h"
49 #include "cacommon.h"
50 #include "cainterface.h"
51 #include "base64.h"
52 #include "cJSON.h"
53 #include "global.h"
54 #include "utlist.h"
55 #include "srmresourcestrings.h"
56 #include "doxmresource.h"
57 #include "pstatresource.h"
58 #include "credresource.h"
59 #include "aclresource.h"
60 #include "ownershiptransfermanager.h"
61 #include "securevirtualresourcetypes.h"
62 #include "oxmjustworks.h"
63 #include "oxmrandompin.h"
64 #include "oxmmanufacturercert.h"
65 #ifdef _ENABLE_MULTIPLE_OWNER_
66 #include "oxmpreconfpin.h"
67 #endif //_ENABLE_MULTIPLE_OWNER_
68 #include "otmcontextlist.h"
69 #include "pmtypes.h"
70 #include "pmutility.h"
71 #include "srmutility.h"
72 #include "provisioningdatabasemanager.h"
73 #include "ocpayload.h"
74 #include "payload_logging.h"
75 #include "pkix_interface.h"
76
77 #define TAG "OIC_OTM"
78
79
80 #define ALLOWED_OXM         1
81 #define NOT_ALLOWED_OXM     0
82
83 /**
84  * List of allowed oxm list.
85  * All oxm methods are allowed as default.
86  */
87 static uint8_t g_OxmAllowStatus[OIC_OXM_COUNT] = {ALLOWED_OXM, ALLOWED_OXM, ALLOWED_OXM, NOT_ALLOWED_OXM};
88
89 /**
90  * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
91  */
92 static OTMContext_t* g_otmCtx = NULL;
93
94 OCStackResult OTMSetOTCallback(OicSecOxm_t oxm, OTMCallbackData_t* callbacks)
95 {
96     OCStackResult res = OC_STACK_INVALID_PARAM;
97
98     OIC_LOG(INFO, TAG, "IN OTMSetOTCallback");
99
100     VERIFY_NON_NULL(TAG, callbacks, ERROR);
101 #ifdef _ENABLE_MULTIPLE_OWNER_
102     VERIFY_SUCCESS(TAG, (OIC_OXM_COUNT > oxm || OIC_PRECONFIG_PIN == oxm), ERROR);
103 #else
104     VERIFY_SUCCESS(TAG, (OIC_OXM_COUNT > oxm), ERROR);
105 #endif //_ENABLE_MULTIPLE_OWNER_
106
107     switch(oxm)
108     {
109     case OIC_JUST_WORKS:
110         callbacks->loadSecretCB = LoadSecretJustWorksCallback;
111         callbacks->createSecureSessionCB = CreateSecureSessionJustWorksCallback;
112         callbacks->createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
113         callbacks->createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload;
114         break;
115     case OIC_RANDOM_DEVICE_PIN:
116         callbacks->loadSecretCB = InputPinCodeCallback;
117         callbacks->createSecureSessionCB = CreateSecureSessionRandomPinCallback;
118         callbacks->createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
119         callbacks->createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
120         break;
121     case OIC_MANUFACTURER_CERTIFICATE:
122         callbacks->loadSecretCB = PrepareMCertificateCallback;
123         callbacks->createSecureSessionCB = CreateSecureSessionMCertificateCallback;
124         callbacks->createSelectOxmPayloadCB = CreateMCertificateBasedSelectOxmPayload;
125         callbacks->createOwnerTransferPayloadCB = CreateMCertificateBasedOwnerTransferPayload;
126         break;
127     case OIC_DECENTRALIZED_PUBLIC_KEY:
128         OIC_LOG(ERROR, TAG, "OIC_DECENTRALIZED_PUBLIC_KEY not supported yet.");
129         return OC_STACK_INVALID_METHOD;
130 #ifdef _ENABLE_MULTIPLE_OWNER_
131     case OIC_PRECONFIG_PIN:
132         callbacks->loadSecretCB = LoadPreconfigPinCodeCallback;
133         callbacks->createSecureSessionCB = CreateSecureSessionPreconfigPinCallback;
134         callbacks->createSelectOxmPayloadCB = CreatePreconfigPinBasedSelectOxmPayload;
135         callbacks->createOwnerTransferPayloadCB = CreatePreconfigPinBasedOwnerTransferPayload;
136         break;
137 #endif //_ENABLE_MULTIPLE_OWNER_
138     default:
139         OIC_LOG_V(ERROR, TAG, "Unknown OxM : %d", (int)oxm);
140         return OC_STACK_INVALID_PARAM;
141         break;
142     }
143
144     res = OC_STACK_OK;
145 exit:
146     OIC_LOG(INFO, TAG, "OUT OTMSetOTCallback");
147     return res;
148 }
149
150 /**
151  * Function to select appropriate  provisioning method.
152  *
153  * @param[in] supportedMethods   Array of supported methods
154  * @param[in] numberOfMethods   number of supported methods
155  * @param[out]  selectedMethod         Selected methods
156  * @return  OC_STACK_OK on success
157  */
158 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
159         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
160 {
161     bool isOxmSelected = false;
162
163     OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
164
165     if(numberOfMethods == 0 || !supportedMethods)
166     {
167         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
168         return OC_STACK_ERROR;
169     }
170
171     for(size_t i = 0; i < numberOfMethods; i++)
172     {
173         if(ALLOWED_OXM == g_OxmAllowStatus[supportedMethods[i]])
174         {
175             *selectedMethod  = supportedMethods[i];
176             isOxmSelected = true;
177             break;
178         }
179     }
180     if(!isOxmSelected)
181     {
182         OIC_LOG(ERROR, TAG, "Can not find the allowed OxM.");
183         return OC_STACK_NOT_ALLOWED_OXM;
184     }
185
186     for(size_t i = 0; i < numberOfMethods; i++)
187     {
188         if(*selectedMethod < supportedMethods[i] &&
189            ALLOWED_OXM == g_OxmAllowStatus[supportedMethods[i]])
190         {
191             *selectedMethod =  supportedMethods[i];
192         }
193     }
194
195     OIC_LOG(DEBUG, TAG, "OUT SelectProvisioningMethod");
196
197     return OC_STACK_OK;
198 }
199
200 /**
201  * Function to select operation mode.This function will return most secure common operation mode.
202  *
203  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
204  * @param[out]   selectedMode   selected operation mode
205  * @return  OC_STACK_OK on success
206  */
207 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
208                                 OicSecDpom_t *selectedMode)
209 {
210     OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
211     *selectedMode = selectedDeviceInfo->pstat->sm[0];
212     OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
213 }
214
215 /**
216  * Function to start ownership transfer.
217  * This function will send the first request for provisioning,
218  * The next request message is sent from the response handler for this request.
219  *
220  * @param[in] ctx   context value passed to callback from calling function.
221  * @param[in] selectedDevice   selected device information to performing provisioning.
222  * @return  OC_STACK_OK on success
223  */
224 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
225
226 /**
227  * Function to update owner transfer mode
228  *
229  * @param[in]  otmCtx  Context value of ownership transfer.
230  * @return  OC_STACK_OK on success
231  */
232 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
233
234 /**
235  * Function to send request to resource to get its pstat resource information.
236  *
237  * @param[in]  otmCtx  Context value of ownership transfer.
238  * @return  OC_STACK_OK on success
239  */
240 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
241
242
243 /**
244  * Function to send  uuid of owner device to new device.
245  * This function would update 'owner of doxm' as UUID for provisioning tool.
246  *
247  * @param[in]  otmCtx  Context value of ownership transfer.
248  * @return  OC_STACK_OK on success
249  */
250 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
251
252 /**
253  * Function to update the operation mode. As per the spec. Operation mode in client driven
254  * single service provisioning it will be updated to 0x3
255  *
256  * @param[in]  otmCtx  Context value of ownership transfer.
257  * @return  OC_STACK_OK on success
258  */
259 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
260
261 /**
262  * Function to update the owner credential to new device
263  *
264  * @param[in]  otmCtx  Context value of ownership transfer.
265  * @param[in] selectedOperationMode selected operation mode
266  * @return  OC_STACK_OK on success
267  */
268 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
269
270 /**
271  * Function to update the owner ACL to new device.
272  *
273  * @param[in]  otmCtx  Context value of ownership transfer.
274  * @return  OC_STACK_OK on success
275  */
276 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx);
277
278 /**
279  * Function to send ownerShip info.
280  * This function would update 'owned of doxm' as true.
281  *
282  * @param[in]  otmCtx  Context value of ownership transfer.
283  * @return  OC_STACK_OK on success
284  */
285 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
286
287 /**
288  * Function to update pstat as Ready for provisioning.
289  * This function would update 'cm' from bx0000,0010 to bx0000,0000.
290  *
291  * @param[in] ctx   context value passed to callback from calling function.
292  * @param[in] selectedDevice   selected device information to performing provisioning.
293  * @return  OC_STACK_OK on success
294  */
295 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
296
297 /**
298  * Function to update pstat as Ready for Normal Operation.
299  * This function would update 'isop' from false to true.
300  *
301  * @param[in] ctx   context value passed to callback from calling function.
302  * @param[in] selectedDevice   selected device information to performing provisioning.
303  * @return  OC_STACK_OK on success
304  */
305 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
306
307 static bool IsComplete(OTMContext_t* otmCtx)
308 {
309     for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
310     {
311         if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
312         {
313             return false;
314         }
315     }
316
317     return true;
318 }
319
320 /**
321  * Function to save the result of provisioning.
322  *
323  * @param[in,out] otmCtx   Context value of ownership transfer.
324  * @param[in] res   result of provisioning
325  */
326 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
327 {
328     OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
329
330     if(NULL == otmCtx || NULL == otmCtx->selectedDeviceInfo)
331     {
332         OIC_LOG(WARNING, TAG, "OTMContext is NULL");
333         return;
334     }
335
336     //If OTM Context was removed from previous response handler, just exit the current OTM process.
337     if(NULL == GetOTMContext(otmCtx->selectedDeviceInfo->endpoint.addr,
338                              otmCtx->selectedDeviceInfo->securePort))
339     {
340         OIC_LOG(WARNING, TAG, "Current OTM Process has already ended.");
341         return;
342     }
343
344     //Revert psk_info callback and new deivce uuid in case of random PIN OxM
345     if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
346     {
347         if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
348         {
349             OIC_LOG(WARNING, TAG, "Failed to revert  is DTLS credential handler.");
350         }
351         OicUuid_t emptyUuid = { .id={0}};
352         SetUuidForPinBasedOxm(&emptyUuid);
353     }
354     else if(OIC_MANUFACTURER_CERTIFICATE == otmCtx->selectedDeviceInfo->doxm->oxmSel)
355     {
356         //Revert back certificate related callbacks.
357         if(CA_STATUS_OK != CAregisterPkixInfoHandler(GetPkixInfo))
358         {
359             OIC_LOG(WARNING, TAG, "Failed to revert PkixInfoHandler.");
360         }
361         if(CA_STATUS_OK != CAregisterGetCredentialTypesHandler(InitCipherSuiteList))
362         {
363             OIC_LOG(WARNING, TAG, "Failed to revert CredentialTypesHandler.");
364         }
365     }
366
367     for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
368     {
369         if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
370                   otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
371         {
372             otmCtx->ctxResultArray[i].res = res;
373             if(OC_STACK_OK != res && OC_STACK_CONTINUE != res && OC_STACK_DUPLICATE_REQUEST != res)
374             {
375                 otmCtx->ctxHasError = true;
376                 if (OC_STACK_OK != PDMDeleteDevice(&otmCtx->ctxResultArray[i].deviceId))
377                 {
378                     OIC_LOG(WARNING, TAG, "Internal error in PDMDeleteDevice");
379                 }
380                 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
381                 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
382                 if (CA_STATUS_OK != CAcloseSslConnection(endpoint))
383                 {
384                     OIC_LOG(WARNING, TAG, "Failed to close Secure session");
385                 }
386             }
387         }
388     }
389
390     //In case of duplicated OTM process, OTMContext and OCDoHandle should not be removed.
391     if(OC_STACK_DUPLICATE_REQUEST != res)
392     {
393         //Remove the current OTM Context from OTM queue
394         RemoveOTMContext(otmCtx->selectedDeviceInfo->endpoint.addr,
395                          otmCtx->selectedDeviceInfo->securePort);
396
397         //If there is a request being performed, cancel it to prevent retransmission.
398         if(otmCtx->ocDoHandle)
399         {
400             OIC_LOG_V(DEBUG, TAG, "OCCancel - %s : %d",
401                     otmCtx->selectedDeviceInfo->endpoint.addr,
402                     otmCtx->selectedDeviceInfo->securePort);
403             if(OC_STACK_OK != OCCancel(otmCtx->ocDoHandle, OC_HIGH_QOS, NULL, 0))
404             {
405                 OIC_LOG(WARNING, TAG, "Failed to remove registered callback");
406             }
407             else
408             {
409                 otmCtx->ocDoHandle = NULL;
410             }
411         }
412     }
413
414     //If all OTM process is complete, invoke the user callback.
415     if(IsComplete(otmCtx))
416     {
417         otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
418                                    otmCtx->ctxResultArray, otmCtx->ctxHasError);
419         OICFree(otmCtx->ctxResultArray);
420         OICFree(otmCtx);
421     }
422     else
423     {
424         if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
425                                                  otmCtx->selectedDeviceInfo->next))
426         {
427             OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
428         }
429     }
430
431     OIC_LOG(DEBUG, TAG, "OUT SetResult");
432 }
433
434 /**
435  * Function to handle the handshake result in OTM.
436  * This function will be invoked after DTLS handshake
437  * @param   endPoint  [IN] The remote endpoint.
438  * @param   errorInfo [IN] Error information from the endpoint.
439  * @return  NONE
440  */
441 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
442 {
443     if(NULL != endpoint && NULL != info)
444     {
445         OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
446                  endpoint->addr, endpoint->port, info->result);
447
448         OTMContext_t* otmCtx = GetOTMContext(endpoint->addr, endpoint->port);
449         if(otmCtx)
450         {
451             OicSecDoxm_t* newDevDoxm = otmCtx->selectedDeviceInfo->doxm;
452             if(NULL != newDevDoxm)
453             {
454                 OicUuid_t emptyUuid = {.id={0}};
455
456                 //Make sure the address matches.
457                 if(strncmp(otmCtx->selectedDeviceInfo->endpoint.addr,
458                    endpoint->addr,
459                    sizeof(endpoint->addr)) == 0 &&
460                    otmCtx->selectedDeviceInfo->securePort == endpoint->port)
461                 {
462                     OCStackResult res = OC_STACK_ERROR;
463
464                     //If temporal secure sesstion established successfully
465                     if(CA_STATUS_OK == info->result &&
466                        false == newDevDoxm->owned &&
467                        memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
468                     {
469                         //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
470                         res = PostOwnerUuid(otmCtx);
471                         if(OC_STACK_OK != res)
472                         {
473                             OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
474                             SetResult(otmCtx, res);
475                         }
476                     }
477                     //In case of authentication failure
478                     else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
479                     {
480                         //in case of error from owner credential
481                         if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
482                             true == newDevDoxm->owned)
483                         {
484                             OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
485
486                             if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
487                             {
488                                 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
489                             }
490                             SetResult(otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
491                         }
492                         //in case of error from wrong PIN, re-start the ownership transfer
493                         else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
494                         {
495                             OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
496
497                             memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
498                             newDevDoxm->owned = false;
499                             otmCtx->attemptCnt++;
500
501                             if(WRONG_PIN_MAX_ATTEMP > otmCtx->attemptCnt)
502                             {
503                                 res = StartOwnershipTransfer(otmCtx, otmCtx->selectedDeviceInfo);
504                                 if(OC_STACK_OK != res)
505                                 {
506                                     SetResult(otmCtx, res);
507                                     OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
508                                 }
509                             }
510                             else
511                             {
512                                 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
513                                 SetResult(otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
514                             }
515                         }
516                         else
517                         {
518                             OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
519                             SetResult(otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
520                         }
521                     }
522                 }
523             }
524         }
525         else
526         {
527             OIC_LOG(ERROR, TAG, "Can not find the OTM Context.");
528         }
529     }
530 }
531
532 /**
533  * Function to save the Owner/SubOwner PSK.
534  *
535  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
536  * @return  OC_STACK_OK on success
537  */
538 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
539 {
540     OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
541
542     OCStackResult res = OC_STACK_ERROR;
543
544     CAEndpoint_t endpoint;
545     memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
546     OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
547     endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
548     endpoint.port = selectedDeviceInfo->securePort;
549     endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
550
551     OicUuid_t ownerDeviceID = {.id={0}};
552     if (OC_STACK_OK != GetDoxmDeviceID(&ownerDeviceID))
553     {
554         OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
555         return res;
556     }
557
558     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
559     OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
560
561     //Generating OwnerPSK
562     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
563             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
564             strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
565             ownerDeviceID.id, sizeof(ownerDeviceID.id),
566             selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
567             ownerPSK, OWNER_PSK_LENGTH_128);
568
569     if (CA_STATUS_OK == pskRet)
570     {
571         OIC_LOG(DEBUG, TAG,"Owner PSK dump:\n");
572         OIC_LOG_BUFFER(DEBUG, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
573         //Generating new credential for provisioning tool
574         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
575                                   SYMMETRIC_PAIR_WISE_KEY, NULL,
576                                   &ownerKey, &ownerDeviceID, NULL);
577         OICClearMemory(ownerPSK, sizeof(ownerPSK));
578         VERIFY_NON_NULL(TAG, cred, ERROR);
579
580         // TODO: Added as workaround. Will be replaced soon.
581         cred->privateData.encoding = OIC_ENCODING_RAW;
582
583 #if 1
584         // NOTE: Test codes to use BASE64 encoded owner PSK.
585         uint32_t outSize = 0;
586         size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
587         char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
588         VERIFY_NON_NULL(TAG, b64Buf, ERROR);
589         b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
590
591         OICFree( cred->privateData.data );
592         cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
593         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
594
595         strncpy(cred->privateData.data, b64Buf, outSize);
596         cred->privateData.data[outSize] = '\0';
597         cred->privateData.encoding = OIC_ENCODING_BASE64;
598         cred->privateData.len = outSize;
599         OICFree(b64Buf);
600 #endif //End of Test codes
601
602         //Finding previous ownerPSK.
603         const OicSecCred_t* credList = GetCredList();
604         OicSecCred_t* prevCred = NULL;
605         uint16_t credId = 0;
606         LL_FOREACH(credList, prevCred)
607         {
608             //OwnerPSK's type is SYMMETRIC_PAIR_WISE_KEY
609             if (SYMMETRIC_PAIR_WISE_KEY == prevCred->credType &&
610                 0 == memcmp(prevCred->subject.id, cred->subject.id, sizeof(cred->subject.id)))
611             {
612                 credId = prevCred->credId;
613                 break;
614             }
615         }
616
617         //If duplicate owner PSK is exists, remove it.
618         if(0 < credId)
619         {
620             OIC_LOG(WARNING, TAG, "Duplicate OwnerPSK was detected.");
621             OIC_LOG(WARNING, TAG, "[Subject] : ");
622             OIC_LOG_BUFFER(WARNING, TAG, prevCred->subject.id, sizeof(prevCred->subject.id));
623             OIC_LOG_V(WARNING, TAG, "[Encoding Type] : %d", prevCred->privateData.encoding);
624             OIC_LOG(DEBUG, TAG, "[Private Data] : ");
625             OIC_LOG_BUFFER(DEBUG, TAG, prevCred->privateData.data, prevCred->privateData.len);
626             OIC_LOG(WARNING, TAG, "Previous OwnerPSK will be removed.");
627
628             res = RemoveCredentialByCredId(credId);
629             if(OC_STACK_RESOURCE_DELETED != res)
630             {
631                 OIC_LOG(ERROR, TAG, "Failed to remove the previous OwnerPSK");
632                 DeleteCredList(cred);
633                 goto exit;
634             }
635         }
636
637         res = AddCredential(cred);
638         if(res != OC_STACK_OK)
639         {
640             DeleteCredList(cred);
641             return res;
642         }
643     }
644     else
645     {
646         OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
647     }
648
649     OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
650 exit:
651     return res;
652 }
653
654 /**
655  * Callback handler for OwnerShipTransferModeHandler API.
656  *
657  * @param[in] ctx             ctx value passed to callback from calling function.
658  * @param[in] UNUSED          handle to an invocation
659  * @param[in] clientResponse  Response from queries to remote servers.
660  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
661  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
662  */
663 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
664                                                          OCClientResponse *clientResponse)
665 {
666     OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
667
668     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
669     VERIFY_NON_NULL(TAG, ctx, WARNING);
670
671     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
672     otmCtx->ocDoHandle = NULL;
673     (void)UNUSED;
674     if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
675     {
676         OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
677         //Send request : GET /oic/sec/pstat
678         OCStackResult res = GetProvisioningStatusResource(otmCtx);
679         if(OC_STACK_OK != res)
680         {
681             OIC_LOG(WARNING, TAG, "Failed to get pstat information");
682             SetResult(otmCtx, res);
683         }
684     }
685     else
686     {
687         OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
688         clientResponse->result);
689         SetResult(otmCtx, clientResponse->result);
690     }
691
692     OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
693
694 exit:
695     return  OC_STACK_DELETE_TRANSACTION;
696 }
697
698 /**
699  * Callback handler for ProvisioningStatusResouceHandler API.
700  *
701  * @param[in] ctx             ctx value passed to callback from calling function.
702  * @param[in] UNUSED          handle to an invocation
703  * @param[in] clientResponse  Response from queries to remote servers.
704  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
705  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
706  */
707 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
708                                                     OCClientResponse *clientResponse)
709 {
710     OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
711
712     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
713     VERIFY_NON_NULL(TAG, ctx, WARNING);
714
715     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
716     otmCtx->ocDoHandle = NULL;
717     (void)UNUSED;
718     if  (OC_STACK_OK == clientResponse->result)
719     {
720         if  (NULL == clientResponse->payload)
721         {
722             OIC_LOG(INFO, TAG, "Skiping Null payload");
723             SetResult(otmCtx, OC_STACK_ERROR);
724             return OC_STACK_DELETE_TRANSACTION;
725         }
726
727         if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
728         {
729             OIC_LOG(INFO, TAG, "Unknown payload type");
730             SetResult(otmCtx, OC_STACK_ERROR);
731             return OC_STACK_DELETE_TRANSACTION;
732         }
733         OicSecPstat_t* pstat = NULL;
734         OCStackResult result = CBORPayloadToPstat(
735                 ((OCSecurityPayload*)clientResponse->payload)->securityData,
736                 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
737                 &pstat);
738         if(NULL == pstat || result != OC_STACK_OK)
739         {
740             OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
741             SetResult(otmCtx, OC_STACK_ERROR);
742             return OC_STACK_DELETE_TRANSACTION;
743         }
744         if(false == (TAKE_OWNER & pstat->cm))
745         {
746             OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
747             SetResult(otmCtx, OC_STACK_ERROR);
748             return OC_STACK_DELETE_TRANSACTION;
749         }
750         otmCtx->selectedDeviceInfo->pstat = pstat;
751
752         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
753         SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
754
755         //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
756         OCStackResult res = PostUpdateOperationMode(otmCtx);
757         if (OC_STACK_OK != res)
758         {
759             OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
760             SetResult(otmCtx, res);
761         }
762     }
763     else
764     {
765         OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
766             clientResponse->result);
767         SetResult(otmCtx, clientResponse->result);
768     }
769
770     OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
771 exit:
772     return  OC_STACK_DELETE_TRANSACTION;
773 }
774
775 /**
776  * Response handler for update owner uuid request.
777  *
778  * @param[in] ctx             ctx value passed to callback from calling function.
779  * @param[in] UNUSED          handle to an invocation
780  * @param[in] clientResponse  Response from queries to remote servers.
781  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
782  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
783  */
784 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
785                                 OCClientResponse *clientResponse)
786 {
787     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
788     VERIFY_NON_NULL(TAG, ctx, WARNING);
789
790     OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
791     (void)UNUSED;
792     OCStackResult res = OC_STACK_OK;
793     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
794     otmCtx->ocDoHandle = NULL;
795
796     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
797     {
798         if(otmCtx && otmCtx->selectedDeviceInfo)
799         {
800             res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
801             if(OC_STACK_OK != res)
802             {
803                 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
804                 SetResult(otmCtx, res);
805                 return OC_STACK_DELETE_TRANSACTION;
806             }
807
808             //POST owner credential to new device according to security spec B.
809             res = PostOwnerCredential(otmCtx);
810             if(OC_STACK_OK != res)
811             {
812                 OIC_LOG(ERROR, TAG,
813                         "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
814                 SetResult(otmCtx, res);
815                 return OC_STACK_DELETE_TRANSACTION;
816             }
817         }
818     }
819     else
820     {
821         res = clientResponse->result;
822         OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
823         SetResult(otmCtx, res);
824     }
825
826     OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
827
828 exit:
829     return  OC_STACK_DELETE_TRANSACTION;
830 }
831
832 /**
833  * Response handler for update operation mode.
834  *
835  * @param[in] ctx             ctx value passed to callback from calling function.
836  * @param[in] UNUSED          handle to an invocation
837  * @param[in] clientResponse  Response from queries to remote servers.
838  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
839  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
840  */
841 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
842                                 OCClientResponse *clientResponse)
843 {
844     OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
845
846     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
847     VERIFY_NON_NULL(TAG, ctx, WARNING);
848
849     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
850     otmCtx->ocDoHandle = NULL;
851     (void) UNUSED;
852     if  (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
853     {
854         OCStackResult res = OC_STACK_ERROR;
855
856         //DTLS Handshake
857         //Load secret for temporal secure session.
858         if(otmCtx->otmCallback.loadSecretCB)
859         {
860             res = otmCtx->otmCallback.loadSecretCB(otmCtx);
861             if(OC_STACK_OK != res)
862             {
863                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
864                 SetResult(otmCtx, res);
865                 return  OC_STACK_DELETE_TRANSACTION;
866             }
867         }
868
869         //Save the current context instance to use on the dtls handshake callback
870         if(OC_STACK_OK != AddOTMContext(otmCtx,
871                                          otmCtx->selectedDeviceInfo->endpoint.addr,
872                                          otmCtx->selectedDeviceInfo->securePort))
873         {
874             OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to add OTM Context into OTM List.");
875             SetResult(otmCtx, res);
876             return OC_STACK_DELETE_TRANSACTION;
877         }
878
879         //Try DTLS handshake to generate secure session
880         if(otmCtx->otmCallback.createSecureSessionCB)
881         {
882             res = otmCtx->otmCallback.createSecureSessionCB(otmCtx);
883             if(OC_STACK_OK != res)
884             {
885                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
886                 SetResult(otmCtx, res);
887                 return OC_STACK_DELETE_TRANSACTION;
888             }
889         }
890     }
891     else
892     {
893         OIC_LOG(ERROR, TAG, "Error while update operation mode");
894         SetResult(otmCtx, clientResponse->result);
895     }
896
897     OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
898
899 exit:
900     return  OC_STACK_DELETE_TRANSACTION;
901 }
902
903 /**
904  * Response handler for update owner crendetial request.
905  *
906  * @param[in] ctx             ctx value passed to callback from calling function.
907  * @param[in] UNUSED          handle to an invocation
908  * @param[in] clientResponse  Response from queries to remote servers.
909  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
910  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
911  */
912 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
913                                 OCClientResponse *clientResponse)
914 {
915     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
916     VERIFY_NON_NULL(TAG, ctx, WARNING);
917
918     OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
919     (void)UNUSED;
920     OCStackResult res = OC_STACK_OK;
921     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
922     otmCtx->ocDoHandle = NULL;
923
924     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
925     {
926         if(otmCtx && otmCtx->selectedDeviceInfo)
927         {
928             //Close the temporal secure session to verify the owner credential
929             CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
930             endpoint->port = otmCtx->selectedDeviceInfo->securePort;
931             CAResult_t caResult = CA_STATUS_OK;
932             caResult = CAcloseSslConnection(endpoint);
933
934             if(CA_STATUS_OK != caResult)
935             {
936                 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
937                 SetResult(otmCtx, caResult);
938                 return OC_STACK_DELETE_TRANSACTION;
939             }
940
941             /**
942              * If we select NULL cipher,
943              * client will select appropriate cipher suite according to server's cipher-suite list.
944              */
945             // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
946             caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
947
948             if(CA_STATUS_OK != caResult)
949             {
950                 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
951                 SetResult(otmCtx, caResult);
952                 return OC_STACK_DELETE_TRANSACTION;
953             }
954
955             /**
956              * in case of random PIN based OxM,
957              * revert get_psk_info callback of tinyDTLS to use owner credential.
958              */
959             if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
960             {
961                 OicUuid_t emptyUuid = { .id={0}};
962                 SetUuidForPinBasedOxm(&emptyUuid);
963
964                 caResult = CAregisterPskCredentialsHandler(GetDtlsPskCredentials);
965
966                 if(CA_STATUS_OK != caResult)
967                 {
968                     OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
969                     SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
970                     return OC_STACK_DELETE_TRANSACTION;
971                 }
972             }
973 #ifdef __WITH_TLS__
974            otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
975 #endif
976             res = PostOwnerAcl(otmCtx);
977             if(OC_STACK_OK != res)
978             {
979                 OIC_LOG(ERROR, TAG, "Failed to update owner ACL to new device");
980                 SetResult(otmCtx, res);
981                 return OC_STACK_DELETE_TRANSACTION;
982             }
983         }
984     }
985     else
986     {
987         res = clientResponse->result;
988         OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
989         SetResult(otmCtx, res);
990     }
991
992     OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
993
994 exit:
995     return  OC_STACK_DELETE_TRANSACTION;
996 }
997
998 /**
999  * Response handler for update owner ACL request.
1000  *
1001  * @param[in] ctx             ctx value passed to callback from calling function.
1002  * @param[in] UNUSED          handle to an invocation
1003  * @param[in] clientResponse  Response from queries to remote servers.
1004  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1005  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1006  */
1007 static OCStackApplicationResult OwnerAclHandler(void *ctx, OCDoHandle UNUSED,
1008                                 OCClientResponse *clientResponse)
1009 {
1010     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
1011     VERIFY_NON_NULL(TAG, ctx, WARNING);
1012
1013     OIC_LOG(DEBUG, TAG, "IN OwnerAclHandler");
1014     (void)UNUSED;
1015     OCStackResult res = OC_STACK_OK;
1016     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1017     otmCtx->ocDoHandle = NULL;
1018
1019     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1020     {
1021         if(otmCtx && otmCtx->selectedDeviceInfo)
1022         {
1023             //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
1024             res = PostOwnershipInformation(otmCtx);
1025             if(OC_STACK_OK != res)
1026             {
1027                 OIC_LOG(ERROR, TAG, "Failed to update ownership information to new device");
1028                 SetResult(otmCtx, res);
1029             }
1030         }
1031     }
1032     else
1033     {
1034         res = clientResponse->result;
1035         OIC_LOG_V(ERROR, TAG, "OwnerAclHandler : Unexpected result %d", res);
1036         SetResult(otmCtx, res);
1037     }
1038
1039     OIC_LOG(DEBUG, TAG, "OUT OwnerAclHandler");
1040
1041 exit:
1042     return  OC_STACK_DELETE_TRANSACTION;
1043 }
1044
1045
1046 /**
1047  * Response handler for update owner information request.
1048  *
1049  * @param[in] ctx             ctx value passed to callback from calling function.
1050  * @param[in] UNUSED          handle to an invocation
1051  * @param[in] clientResponse  Response from queries to remote servers.
1052  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1053  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1054  */
1055 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
1056                                 OCClientResponse *clientResponse)
1057 {
1058     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
1059     VERIFY_NON_NULL(TAG, ctx, WARNING);
1060
1061     OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
1062     (void)UNUSED;
1063     OCStackResult res = OC_STACK_OK;
1064     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1065     otmCtx->ocDoHandle = NULL;
1066
1067     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1068     {
1069         if(otmCtx && otmCtx->selectedDeviceInfo)
1070         {
1071             OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
1072             OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
1073
1074             res = PostProvisioningStatus(otmCtx);
1075             if(OC_STACK_OK != res)
1076             {
1077                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
1078                 SetResult(otmCtx, res);
1079             }
1080         }
1081     }
1082     else
1083     {
1084         res = clientResponse->result;
1085         OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
1086         SetResult(otmCtx, res);
1087     }
1088
1089     OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
1090
1091 exit:
1092     return  OC_STACK_DELETE_TRANSACTION;
1093 }
1094
1095 /**
1096  * Response handler of update provisioning status.
1097  *
1098  * @param[in] ctx             ctx value passed to callback from calling function.
1099  * @param[in] UNUSED          handle to an invocation
1100  * @param[in] clientResponse  Response from queries to remote servers.
1101  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1102  *          and OC_STACK_KEEP_TRANSACTION to keep it.
1103  */
1104 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
1105                                                        OCClientResponse *clientResponse)
1106 {
1107     OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
1108
1109     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1110     VERIFY_NON_NULL(TAG, ctx, ERROR);
1111
1112     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1113     otmCtx->ocDoHandle = NULL;
1114     (void)UNUSED;
1115     OCStackResult res = OC_STACK_OK;
1116
1117     if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1118     {
1119         if(otmCtx && otmCtx->selectedDeviceInfo)
1120         {
1121             OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
1122
1123             res = PostNormalOperationStatus(otmCtx);
1124             if(OC_STACK_OK != res)
1125             {
1126                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
1127                 SetResult(otmCtx, res);
1128             }
1129         }
1130     }
1131     else
1132     {
1133         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1134                             clientResponse->result);
1135         SetResult(otmCtx, clientResponse->result);
1136     }
1137
1138 exit:
1139     OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
1140     return OC_STACK_DELETE_TRANSACTION;
1141 }
1142
1143 /**
1144  * Response handler of update provisioning status to Ready for Normal..
1145  *
1146  * @param[in] ctx             ctx value passed to callback from calling function.
1147  * @param[in] UNUSED          handle to an invocation
1148  * @param[in] clientResponse  Response from queries to remote servers.
1149  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1150  *          and OC_STACK_KEEP_TRANSACTION to keep it.
1151  */
1152 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
1153                                                        OCClientResponse *clientResponse)
1154 {
1155     OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
1156
1157     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1158     VERIFY_NON_NULL(TAG, ctx, ERROR);
1159
1160     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1161     otmCtx->ocDoHandle = NULL;
1162     (void)UNUSED;
1163
1164     if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1165     {
1166         OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
1167         OCStackResult res = PDMSetDeviceState(&otmCtx->selectedDeviceInfo->doxm->deviceID,
1168                                               PDM_DEVICE_ACTIVE);
1169          if (OC_STACK_OK == res)
1170          {
1171                 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
1172                 SetResult(otmCtx, OC_STACK_OK);
1173                 return OC_STACK_DELETE_TRANSACTION;
1174          }
1175           else
1176          {
1177               OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
1178          }
1179     }
1180     else
1181     {
1182         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1183                             clientResponse->result);
1184         SetResult(otmCtx, clientResponse->result);
1185     }
1186
1187 exit:
1188     OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
1189     return OC_STACK_DELETE_TRANSACTION;
1190 }
1191
1192 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
1193 {
1194     OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
1195
1196     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1197     {
1198         OIC_LOG(ERROR, TAG, "Invalid parameters");
1199         return OC_STACK_INVALID_PARAM;
1200     }
1201
1202     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1203     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1204
1205     if(!PMGenerateQuery(true,
1206                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1207                         deviceInfo->connType,
1208                         query, sizeof(query), OIC_RSRC_CRED_URI))
1209     {
1210         OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1211         return OC_STACK_ERROR;
1212     }
1213     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1214     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1215     if(!secPayload)
1216     {
1217         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1218         return OC_STACK_NO_MEMORY;
1219     }
1220
1221     //Generate owner credential for new device
1222     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1223     const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1224     if(!ownerCredential)
1225     {
1226         OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1227         return OC_STACK_NO_RESOURCE;
1228     }
1229
1230     OicUuid_t credSubjectId = {.id={0}};
1231     if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1232     {
1233         OicSecCred_t newCredential;
1234         memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1235         newCredential.next = NULL;
1236
1237         //Set subject ID as PT's ID
1238         memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1239
1240         //Fill private data as empty string
1241         newCredential.privateData.data = "";
1242         newCredential.privateData.len = 0;
1243         newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1244
1245         newCredential.publicData.data = NULL;
1246         newCredential.publicData.len = 0;
1247
1248         int secureFlag = 0;
1249         //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1250         if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1251                                         &secPayload->payloadSize, secureFlag))
1252         {
1253             OICFree(secPayload);
1254             OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1255             return OC_STACK_ERROR;
1256         }
1257         OIC_LOG(DEBUG, TAG, "Cred Payload:");
1258         OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1259
1260         OCCallbackData cbData;
1261         cbData.cb = &OwnerCredentialHandler;
1262         cbData.context = (void *)otmCtx;
1263         cbData.cd = NULL;
1264         OCStackResult res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query,
1265                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
1266                                          deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1267         if (res != OC_STACK_OK)
1268         {
1269             OIC_LOG(ERROR, TAG, "OCStack resource error");
1270         }
1271     }
1272     else
1273     {
1274         OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1275         return OC_STACK_NO_RESOURCE;
1276     }
1277
1278     OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1279
1280     return OC_STACK_OK;
1281 }
1282
1283 static OicSecAcl_t* GenerateOwnerAcl(const OicUuid_t* owner)
1284 {
1285     OicSecAcl_t* ownerAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
1286     OicSecAce_t* ownerAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
1287     OicSecRsrc_t* wildcardRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
1288     if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1289     {
1290         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1291         goto error;
1292     }
1293     LL_APPEND(ownerAcl->aces, ownerAce);
1294     LL_APPEND(ownerAce->resources, wildcardRsrc);
1295
1296     //Set resource owner as PT
1297     memcpy(ownerAcl->rownerID.id, owner->id, sizeof(owner->id));
1298
1299     //PT has full permission.
1300     ownerAce->permission = PERMISSION_FULL_CONTROL;
1301
1302     //Set subject as PT's UUID
1303     memcpy(ownerAce->subjectuuid.id, owner->id, sizeof(owner->id));
1304
1305     wildcardRsrc->href = OICStrdup(WILDCARD_RESOURCE_URI);
1306     if(NULL == wildcardRsrc->href)
1307     {
1308         goto error;
1309     }
1310
1311     wildcardRsrc->interfaceLen = 1;
1312     wildcardRsrc->interfaces = (char**)OICMalloc(wildcardRsrc->interfaceLen * sizeof(char*));
1313     if(NULL == wildcardRsrc->interfaces)
1314     {
1315         goto error;
1316     }
1317     wildcardRsrc->interfaces[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1318     if(NULL == wildcardRsrc->interfaces[0])
1319     {
1320         goto error;
1321     }
1322
1323     wildcardRsrc->typeLen = 1;
1324     wildcardRsrc->types = (char**)OICMalloc(wildcardRsrc->typeLen * sizeof(char*));
1325     if(NULL == wildcardRsrc->types)
1326     {
1327         goto error;
1328     }
1329     wildcardRsrc->types[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1330     if(NULL == wildcardRsrc->types[0])
1331     {
1332         goto error;
1333     }
1334
1335     return ownerAcl;
1336
1337 error:
1338     //in case of memory allocation failed, each resource should be removed individually.
1339     if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1340     {
1341         OICFree(ownerAcl);
1342         OICFree(ownerAce);
1343         OICFree(wildcardRsrc);
1344     }
1345     else
1346     {
1347         DeleteACLList(ownerAcl);
1348     }
1349     return NULL;
1350 }
1351
1352 /**
1353  * Function to update the owner ACL to new device.
1354  *
1355  * @param[in]  otmCtx  Context value of ownership transfer.
1356  * @return  OC_STACK_OK on success
1357  */
1358 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx)
1359 {
1360     OCStackResult res = OC_STACK_ERROR;
1361
1362     OIC_LOG(DEBUG, TAG, "IN PostOwnerAcl");
1363
1364     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1365     {
1366         OIC_LOG(ERROR, TAG, "Invalid parameters");
1367         return OC_STACK_INVALID_PARAM;
1368     }
1369
1370     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1371     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1372     OicSecAcl_t* ownerAcl = NULL;
1373
1374     if(!PMGenerateQuery(true,
1375                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1376                         deviceInfo->connType,
1377                         query, sizeof(query), OIC_RSRC_ACL_URI))
1378     {
1379         OIC_LOG(ERROR, TAG, "Failed to generate query");
1380         return OC_STACK_ERROR;
1381     }
1382     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1383
1384     OicUuid_t ownerID;
1385     res = GetDoxmDeviceID(&ownerID);
1386     if(OC_STACK_OK != res)
1387     {
1388         OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1389         return res;
1390     }
1391
1392     //Generate owner ACL for new device
1393     ownerAcl = GenerateOwnerAcl(&ownerID);
1394     if(NULL == ownerAcl)
1395     {
1396         OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1397         return OC_STACK_NO_MEMORY;
1398     }
1399
1400     //Generate ACL payload
1401     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1402     if(!secPayload)
1403     {
1404         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1405         res = OC_STACK_NO_MEMORY;
1406         goto error;
1407     }
1408
1409     res = AclToCBORPayload(ownerAcl, &secPayload->securityData, &secPayload->payloadSize);
1410     if (OC_STACK_OK != res)
1411     {
1412         OICFree(secPayload);
1413         OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1414         goto error;
1415     }
1416     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1417
1418     OIC_LOG(DEBUG, TAG, "Owner ACL Payload:");
1419     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1420
1421     //Send owner ACL to new device : POST /oic/sec/cred [ owner credential ]
1422     OCCallbackData cbData;
1423     cbData.cb = &OwnerAclHandler;
1424     cbData.context = (void *)otmCtx;
1425     cbData.cd = NULL;
1426     res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query,
1427                                      &deviceInfo->endpoint, (OCPayload*)secPayload,
1428                                      deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1429     if (res != OC_STACK_OK)
1430     {
1431         OIC_LOG(ERROR, TAG, "OCStack resource error");
1432         goto error;
1433     }
1434
1435     OIC_LOG(DEBUG, TAG, "OUT PostOwnerAcl");
1436
1437 error:
1438     DeleteACLList(ownerAcl);
1439
1440     return OC_STACK_OK;
1441 }
1442
1443 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1444 {
1445     OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1446
1447     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1448     {
1449         OIC_LOG(ERROR, TAG, "Invalid parameters");
1450         return OC_STACK_INVALID_PARAM;
1451     }
1452
1453     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1454     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1455
1456     if(!PMGenerateQuery(false,
1457                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1458                         deviceInfo->connType,
1459                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1460     {
1461         OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1462         return OC_STACK_ERROR;
1463     }
1464     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1465
1466     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1467     if(!secPayload)
1468     {
1469         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1470         return OC_STACK_NO_MEMORY;
1471     }
1472
1473     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1474     OCStackResult res = otmCtx->otmCallback.createSelectOxmPayloadCB(otmCtx,
1475             &secPayload->securityData, &secPayload->payloadSize);
1476     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1477     {
1478         OCPayloadDestroy((OCPayload *)secPayload);
1479         OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1480         return OC_STACK_ERROR;
1481     }
1482
1483     OCCallbackData cbData;
1484     cbData.cb = &OwnerTransferModeHandler;
1485     cbData.context = (void *)otmCtx;
1486     cbData.cd = NULL;
1487     res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query,
1488                        &deviceInfo->endpoint, (OCPayload *)secPayload,
1489                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1490     if (res != OC_STACK_OK)
1491     {
1492         OIC_LOG(ERROR, TAG, "OCStack resource error");
1493     }
1494
1495     OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1496
1497     return res;
1498 }
1499
1500 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1501 {
1502     OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1503
1504     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1505     {
1506         OIC_LOG(ERROR, TAG, "Invailed parameters");
1507         return OC_STACK_INVALID_PARAM;
1508     }
1509
1510     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1511     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1512     if(!PMGenerateQuery(false,
1513                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1514                         deviceInfo->connType,
1515                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1516     {
1517         OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1518         return OC_STACK_ERROR;
1519     }
1520     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1521
1522     OCCallbackData cbData;
1523     cbData.cb = &ListMethodsHandler;
1524     cbData.context = (void *)otmCtx;
1525     cbData.cd = NULL;
1526     OCStackResult res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_GET, query, NULL, NULL,
1527                                      deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1528     if (res != OC_STACK_OK)
1529     {
1530         OIC_LOG(ERROR, TAG, "OCStack resource error");
1531     }
1532
1533     OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1534
1535     return res;
1536 }
1537
1538 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1539 {
1540     OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1541
1542     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1543     {
1544         OIC_LOG(ERROR, TAG, "Invailed parameters");
1545         return OC_STACK_INVALID_PARAM;
1546     }
1547
1548     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1549     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1550     if(!PMGenerateQuery(true,
1551                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1552                         deviceInfo->connType,
1553                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1554     {
1555         OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1556         return OC_STACK_ERROR;
1557     }
1558     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1559
1560     //Post PT's uuid to new device
1561     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1562     if(!secPayload)
1563     {
1564         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1565         return OC_STACK_NO_MEMORY;
1566     }
1567     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1568     OCStackResult res = otmCtx->otmCallback.createOwnerTransferPayloadCB(
1569             otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1570     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1571     {
1572         OCPayloadDestroy((OCPayload *)secPayload);
1573         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1574         return OC_STACK_INVALID_PARAM;
1575     }
1576     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1577
1578     OCCallbackData cbData;
1579     cbData.cb = &OwnerUuidUpdateHandler;
1580     cbData.context = (void *)otmCtx;
1581     cbData.cd = NULL;
1582
1583     res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1584             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1585     if (res != OC_STACK_OK)
1586     {
1587         OIC_LOG(ERROR, TAG, "OCStack resource error");
1588     }
1589
1590     OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1591
1592     return res;
1593 }
1594
1595 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1596 {
1597     OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1598
1599     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1600     {
1601         OIC_LOG(ERROR, TAG, "Invailed parameters");
1602         return OC_STACK_INVALID_PARAM;
1603     }
1604
1605     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1606     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1607     if(!PMGenerateQuery(true,
1608                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1609                         deviceInfo->connType,
1610                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1611     {
1612         OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1613         return OC_STACK_ERROR;
1614     }
1615     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1616
1617     //OwnershipInformationHandler
1618     OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1619     if (!secPayload)
1620     {
1621         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1622         return OC_STACK_NO_MEMORY;
1623     }
1624
1625     otmCtx->selectedDeviceInfo->doxm->owned = true;
1626
1627     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1628     OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1629             &secPayload->securityData, &secPayload->payloadSize, true);
1630     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1631     {
1632         OCPayloadDestroy((OCPayload *)secPayload);
1633         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1634         return OC_STACK_INVALID_PARAM;
1635     }
1636
1637     OCCallbackData cbData;
1638     cbData.cb = &OwnershipInformationHandler;
1639     cbData.context = (void *)otmCtx;
1640     cbData.cd = NULL;
1641
1642     res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1643                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1644     if (res != OC_STACK_OK)
1645     {
1646         OIC_LOG(ERROR, TAG, "OCStack resource error");
1647     }
1648
1649     OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1650
1651     return res;
1652 }
1653
1654 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1655 {
1656     OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1657
1658     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1659     {
1660         return OC_STACK_INVALID_PARAM;
1661     }
1662
1663     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1664     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1665     if(!PMGenerateQuery(false,
1666                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1667                         deviceInfo->connType,
1668                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1669     {
1670         OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1671         return OC_STACK_ERROR;
1672     }
1673     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1674
1675     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1676     if(!secPayload)
1677     {
1678         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1679         return OC_STACK_NO_MEMORY;
1680     }
1681     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1682     OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1683                                            &secPayload->payloadSize, true);
1684    if (OC_STACK_OK != res)
1685     {
1686         OCPayloadDestroy((OCPayload *)secPayload);
1687         OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1688         return OC_STACK_INVALID_PARAM;
1689     }
1690
1691     OCCallbackData cbData;
1692     cbData.cb = &OperationModeUpdateHandler;
1693     cbData.context = (void *)otmCtx;
1694     cbData.cd = NULL;
1695     res = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1696                        deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1697     if (res != OC_STACK_OK)
1698     {
1699         OIC_LOG(ERROR, TAG, "OCStack resource error");
1700     }
1701
1702     OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1703
1704     return res;
1705 }
1706
1707 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1708 {
1709     OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1710     OCStackResult res = OC_STACK_INVALID_PARAM;
1711
1712     VERIFY_NON_NULL(TAG, selectedDevice, ERROR);
1713     VERIFY_NON_NULL(TAG, selectedDevice->doxm, ERROR);
1714
1715     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1716     otmCtx->selectedDeviceInfo = selectedDevice;
1717
1718     //Checking duplication of Device ID.
1719     bool isDuplicate = true;
1720     res = PDMIsDuplicateDevice(&selectedDevice->doxm->deviceID, &isDuplicate);
1721     if (OC_STACK_OK != res)
1722     {
1723         OIC_LOG(ERROR, TAG, "Internal error in PDMIsDuplicateDevice");
1724         return res;
1725     }
1726     if (isDuplicate)
1727     {
1728         PdmDeviceState_t state = PDM_DEVICE_UNKNOWN;
1729         res = PDMGetDeviceState(&selectedDevice->doxm->deviceID, &state);
1730         if(OC_STACK_OK != res)
1731         {
1732             OIC_LOG(ERROR, TAG, "Internal error in PDMGetDeviceState");
1733             SetResult(otmCtx, res);
1734             return res;
1735         }
1736
1737         char* strUuid = NULL;
1738         res = ConvertUuidToStr(&selectedDevice->doxm->deviceID, &strUuid);
1739         if(OC_STACK_OK != res)
1740         {
1741             OIC_LOG(ERROR, TAG, "Failed to convert UUID to str");
1742             SetResult(otmCtx, res);
1743             return res;
1744         }
1745
1746         if(PDM_DEVICE_STALE == state)
1747         {
1748             OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "
1749                                "device status will revert back to initial status.");
1750             res = PDMSetDeviceState(&selectedDevice->doxm->deviceID, PDM_DEVICE_INIT);
1751             if(OC_STACK_OK != res)
1752             {
1753                 OIC_LOG(ERROR, TAG, "Internal error in PDMSetDeviceState");
1754                 OICFree(strUuid);
1755                 SetResult(otmCtx, res);
1756                 return res;
1757             }
1758         }
1759         else if(PDM_DEVICE_INIT == state)
1760         {
1761             OIC_LOG_V(ERROR, TAG, "[%s]'s ownership transfer process is already started.", strUuid);
1762             OICFree(strUuid);
1763             SetResult(otmCtx, OC_STACK_DUPLICATE_REQUEST);
1764             return OC_STACK_OK;
1765         }
1766         else
1767         {
1768             OIC_LOG(ERROR, TAG, "Unknow device status while OTM.");
1769             OICFree(strUuid);
1770             SetResult(otmCtx, OC_STACK_ERROR);
1771             return OC_STACK_ERROR;
1772         }
1773     }
1774     else
1775     {
1776         res = PDMAddDevice(&selectedDevice->doxm->deviceID);
1777         if(OC_STACK_OK != res)
1778         {
1779             OIC_LOG(ERROR, TAG, "Internal error in PDMAddDevice");
1780             SetResult(otmCtx, res);
1781             return res;
1782         }
1783     }
1784
1785
1786     //Set to the lowest level OxM, and then find more higher level OxM.
1787     res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1788                                    selectedDevice->doxm->oxmLen,
1789                                    &selectedDevice->doxm->oxmSel);
1790     if(OC_STACK_OK != res)
1791     {
1792         OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1793         SetResult(otmCtx, res);
1794         return res;
1795     }
1796     OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1797
1798     res = OTMSetOTCallback(selectedDevice->doxm->oxmSel, &otmCtx->otmCallback);
1799     if(OC_STACK_OK != res)
1800     {
1801         OIC_LOG_V(ERROR, TAG, "Error in OTMSetOTCallback : %d", res);
1802         return res;
1803     }
1804
1805     //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMCbDatas[Index of Selected OxM].OXMString,...}]
1806     res = PostOwnerTransferModeToResource(otmCtx);
1807     if(OC_STACK_OK != res)
1808     {
1809         OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1810         SetResult(otmCtx, res);
1811         return res;
1812     }
1813
1814 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1815     //Register TLS event handler to catch the tls event while handshake
1816     if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeCB))
1817     {
1818         OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback.");
1819     }
1820 #endif // __WITH_DTLS__ or __WITH_TLS__
1821     OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1822
1823 exit:
1824     return res;
1825 }
1826
1827 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1828 {
1829     OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1830
1831     if(!data)
1832     {
1833         OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1834         return OC_STACK_INVALID_PARAM;
1835     }
1836     if(oxmType >= OIC_OXM_COUNT)
1837     {
1838         OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1839         return OC_STACK_INVALID_PARAM;
1840     }
1841
1842     // TODO: Remove this API, Please see the jira ticket IOT-1484
1843
1844     OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1845
1846     return OC_STACK_OK;
1847 }
1848
1849 /**
1850  * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1851  */
1852 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1853                                      OCProvisionDev_t *selectedDevicelist,
1854                                      OCProvisionResultCB resultCallback)
1855 {
1856     OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1857
1858     if (NULL == selectedDevicelist)
1859     {
1860         return OC_STACK_INVALID_PARAM;
1861     }
1862     if (NULL == resultCallback)
1863     {
1864         return OC_STACK_INVALID_CALLBACK;
1865     }
1866
1867     OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1868     if(!otmCtx)
1869     {
1870         OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1871         return OC_STACK_NO_MEMORY;
1872     }
1873     otmCtx->ctxResultCallback = resultCallback;
1874     otmCtx->ctxHasError = false;
1875     otmCtx->userCtx = ctx;
1876     OCProvisionDev_t* pCurDev = selectedDevicelist;
1877
1878     //Counting number of selected devices.
1879     otmCtx->ctxResultArraySize = 0;
1880     while(NULL != pCurDev)
1881     {
1882         otmCtx->ctxResultArraySize++;
1883         pCurDev = pCurDev->next;
1884     }
1885
1886     otmCtx->ctxResultArray =
1887         (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1888     if(NULL == otmCtx->ctxResultArray)
1889     {
1890         OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1891         OICFree(otmCtx);
1892         return OC_STACK_NO_MEMORY;
1893     }
1894     pCurDev = selectedDevicelist;
1895
1896     OCStackResult res = OC_STACK_OK;
1897     //Fill the device UUID for result array.
1898     for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1899     {
1900         memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1901                pCurDev->doxm->deviceID.id,
1902                UUID_LENGTH);
1903         otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1904         pCurDev = pCurDev->next;
1905     }
1906
1907     StartOwnershipTransfer(otmCtx, selectedDevicelist);
1908
1909     OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1910     return OC_STACK_OK;
1911 }
1912
1913 OCStackResult OTMSetOxmAllowStatus(const OicSecOxm_t oxm, const bool allowStatus)
1914 {
1915     OIC_LOG_V(INFO, TAG, "IN %s : oxm=%d, allow status=%s",
1916               __func__, oxm, (allowStatus ? "true" : "false"));
1917
1918     if(OIC_OXM_COUNT <= oxm)
1919     {
1920         return OC_STACK_INVALID_PARAM;
1921     }
1922
1923     g_OxmAllowStatus[oxm] = (allowStatus ? ALLOWED_OXM : NOT_ALLOWED_OXM);
1924
1925     OIC_LOG_V(INFO, TAG, "OUT %s", __func__);
1926
1927     return OC_STACK_OK;
1928 }
1929
1930 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1931 {
1932     OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1933
1934     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1935     {
1936         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1937         return OC_STACK_INVALID_PARAM;
1938     }
1939
1940     //Change the TAKE_OWNER bit of CM to 0.
1941     otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1942
1943     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1944     if (!secPayload)
1945     {
1946         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1947         return OC_STACK_NO_MEMORY;
1948     }
1949     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1950     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1951             &secPayload->securityData, &secPayload->payloadSize, true))
1952     {
1953         OCPayloadDestroy((OCPayload *)secPayload);
1954         return OC_STACK_INVALID_JSON;
1955     }
1956     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1957     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1958
1959     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1960     if(!PMGenerateQuery(true,
1961                         otmCtx->selectedDeviceInfo->endpoint.addr,
1962                         otmCtx->selectedDeviceInfo->securePort,
1963                         otmCtx->selectedDeviceInfo->connType,
1964                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1965     {
1966         OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1967         return OC_STACK_ERROR;
1968     }
1969     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1970
1971     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1972     cbData.cb = &ProvisioningStatusHandler;
1973     cbData.context = (void*)otmCtx;
1974     cbData.cd = NULL;
1975     OCStackResult ret = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1976             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1977     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1978     if (ret != OC_STACK_OK)
1979     {
1980         OIC_LOG(ERROR, TAG, "OCStack resource error");
1981     }
1982
1983     OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1984
1985     return ret;
1986 }
1987
1988 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1989 {
1990     OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1991
1992     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1993     {
1994         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1995         return OC_STACK_INVALID_PARAM;
1996     }
1997
1998     //Set isop to true.
1999     otmCtx->selectedDeviceInfo->pstat->isOp = true;
2000
2001     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
2002     if (!secPayload)
2003     {
2004         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
2005         return OC_STACK_NO_MEMORY;
2006     }
2007     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2008     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
2009             &secPayload->securityData, &secPayload->payloadSize, true))
2010     {
2011         OCPayloadDestroy((OCPayload *)secPayload);
2012         return OC_STACK_INVALID_JSON;
2013     }
2014     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
2015     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2016
2017     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2018     if(!PMGenerateQuery(true,
2019                         otmCtx->selectedDeviceInfo->endpoint.addr,
2020                         otmCtx->selectedDeviceInfo->securePort,
2021                         otmCtx->selectedDeviceInfo->connType,
2022                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
2023     {
2024         OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
2025         return OC_STACK_ERROR;
2026     }
2027     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2028
2029     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
2030     cbData.cb = &ReadyForNomalStatusHandler;
2031     cbData.context = (void*)otmCtx;
2032     cbData.cd = NULL;
2033     OCStackResult ret = OCDoResource(&otmCtx->ocDoHandle, OC_REST_POST, query, 0, (OCPayload*)secPayload,
2034             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2035     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
2036     if (ret != OC_STACK_OK)
2037     {
2038         OIC_LOG(ERROR, TAG, "OCStack resource error");
2039     }
2040
2041     OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");
2042
2043     return ret;
2044 }