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