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