f5768a08586b7c92c9dd9b304d3b092c64723488
[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 #ifdef HAVE_TIME_H
34 #include <time.h>
35 #endif
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39 #ifdef HAVE_SYS_TIME_H
40 #include <sys/time.h>
41 #endif
42 #include <stdbool.h>
43 #include <string.h>
44
45 #include "logger.h"
46 #include "oic_malloc.h"
47 #include "oic_string.h"
48 #include "cacommon.h"
49 #include "cainterface.h"
50 #include "base64.h"
51 #include "cJSON.h"
52 #include "global.h"
53
54 #include "srmresourcestrings.h"
55 #include "doxmresource.h"
56 #include "pstatresource.h"
57 #include "credresource.h"
58 #include "aclresource.h"
59 #include "ownershiptransfermanager.h"
60 #include "securevirtualresourcetypes.h"
61 #include "oxmjustworks.h"
62 #include "pmtypes.h"
63 #include "pmutility.h"
64 #include "srmutility.h"
65 #include "provisioningdatabasemanager.h"
66 #include "oxmrandompin.h"
67 #include "ocpayload.h"
68 #include "payload_logging.h"
69
70 #define TAG "OTM"
71
72 /**
73  * Array to store the callbacks for each owner transfer method.
74  */
75 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
76
77 /**
78  * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
79  */
80 static OTMContext_t* g_otmCtx = NULL;
81
82 /**
83  * Function to select appropriate  provisioning method.
84  *
85  * @param[in] supportedMethods   Array of supported methods
86  * @param[in] numberOfMethods   number of supported methods
87  * @param[out]  selectedMethod         Selected methods
88  * @return  OC_STACK_OK on success
89  */
90 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
91         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
92 {
93     OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
94
95     if(numberOfMethods == 0 || !supportedMethods)
96     {
97         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
98         return OC_STACK_ERROR;
99     }
100
101     *selectedMethod  = supportedMethods[0];
102     for(size_t i = 0; i < numberOfMethods; i++)
103     {
104         if(*selectedMethod < supportedMethods[i])
105         {
106             *selectedMethod =  supportedMethods[i];
107         }
108     }
109
110     return OC_STACK_OK;
111 }
112
113 /**
114  * Function to select operation mode.This function will return most secure common operation mode.
115  *
116  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
117  * @param[out]   selectedMode   selected operation mode
118  * @return  OC_STACK_OK on success
119  */
120 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
121                                 OicSecDpom_t *selectedMode)
122 {
123     OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
124     *selectedMode = selectedDeviceInfo->pstat->sm[0];
125     OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
126 }
127
128 /**
129  * Function to start ownership transfer.
130  * This function will send the first request for provisioning,
131  * The next request message is sent from the response handler for this request.
132  *
133  * @param[in] ctx   context value passed to callback from calling function.
134  * @param[in] selectedDevice   selected device information to performing provisioning.
135  * @return  OC_STACK_OK on success
136  */
137 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
138
139 /**
140  * Function to update owner transfer mode
141  *
142  * @param[in]  otmCtx  Context value of ownership transfer.
143  * @return  OC_STACK_OK on success
144  */
145 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx);
146
147 /**
148  * Function to send request to resource to get its pstat resource information.
149  *
150  * @param[in]  otmCtx  Context value of ownership transfer.
151  * @return  OC_STACK_OK on success
152  */
153 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
154
155
156 /**
157  * Function to send  uuid of owner device to new device.
158  * This function would update 'owner of doxm' as UUID for provisioning tool.
159  *
160  * @param[in]  otmCtx  Context value of ownership transfer.
161  * @return  OC_STACK_OK on success
162  */
163 static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx);
164
165 /**
166  * Function to update the operation mode. As per the spec. Operation mode in client driven
167  * single service provisioning it will be updated to 0x3
168  *
169  * @param[in]  otmCtx  Context value of ownership transfer.
170  * @return  OC_STACK_OK on success
171  */
172 static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx);
173
174 /**
175  * Function to update the owner credential to new device
176  *
177  * @param[in]  otmCtx  Context value of ownership transfer.
178  * @param[in] selectedOperationMode selected operation mode
179  * @return  OC_STACK_OK on success
180  */
181 static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx);
182
183 /**
184  * Function to send ownerShip info.
185  * This function would update 'owned of doxm' as true.
186  *
187  * @param[in]  otmCtx  Context value of ownership transfer.
188  * @return  OC_STACK_OK on success
189  */
190 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx);
191
192 /**
193  * Function to update pstat as Ready for provisioning.
194  * This function would update 'cm' from bx0000,0010 to bx0000,0000.
195  *
196  * @param[in] ctx   context value passed to callback from calling function.
197  * @param[in] selectedDevice   selected device information to performing provisioning.
198  * @return  OC_STACK_OK on success
199  */
200 static OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx);
201
202 /**
203  * Function to update pstat as Ready for Normal Operation.
204  * This function would update 'isop' from false to true.
205  *
206  * @param[in] ctx   context value passed to callback from calling function.
207  * @param[in] selectedDevice   selected device information to performing provisioning.
208  * @return  OC_STACK_OK on success
209  */
210 static OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx);
211
212 static bool IsComplete(OTMContext_t* otmCtx)
213 {
214     for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
215     {
216         if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
217         {
218             return false;
219         }
220     }
221
222     return true;
223 }
224
225 /**
226  * Function to save the result of provisioning.
227  *
228  * @param[in,out] otmCtx   Context value of ownership transfer.
229  * @param[in] res   result of provisioning
230  */
231 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
232 {
233     OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
234
235     if(!otmCtx)
236     {
237         OIC_LOG(WARNING, TAG, "OTMContext is NULL");
238         return;
239     }
240
241     if(otmCtx->selectedDeviceInfo)
242     {
243         //Revert psk_info callback and new deivce uuid in case of random PIN OxM
244         if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
245         {
246             if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
247             {
248                 OIC_LOG(WARNING, TAG, "Failed to revert  is DTLS credential handler.");
249             }
250             OicUuid_t emptyUuid = { .id={0}};
251             SetUuidForRandomPinOxm(&emptyUuid);
252         }
253
254         for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
255         {
256             if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
257                       otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
258             {
259                 otmCtx->ctxResultArray[i].res = res;
260                 if(OC_STACK_OK != res)
261                 {
262                     otmCtx->ctxHasError = true;
263                 }
264             }
265         }
266
267         g_otmCtx = NULL;
268
269         //If all request is completed, invoke the user callback.
270         if(IsComplete(otmCtx))
271         {
272             otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
273                                        otmCtx->ctxResultArray, otmCtx->ctxHasError);
274             OICFree(otmCtx->ctxResultArray);
275             OICFree(otmCtx);
276         }
277         else
278         {
279             if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
280                                                      otmCtx->selectedDeviceInfo->next))
281             {
282                 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
283             }
284         }
285     }
286
287     OIC_LOG(DEBUG, TAG, "OUT SetResult");
288 }
289
290 /**
291  * Function to handle the handshake result in OTM.
292  * This function will be invoked after DTLS handshake
293  * @param   endPoint  [IN] The remote endpoint.
294  * @param   errorInfo [IN] Error information from the endpoint.
295  * @return  NONE
296  */
297 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
298 {
299     if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
300        NULL != endpoint && NULL != info)
301     {
302         OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
303                  endpoint->addr, endpoint->port, info->result);
304
305         OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
306
307         if(NULL != newDevDoxm)
308         {
309             OicUuid_t emptyUuid = {.id={0}};
310
311             //Make sure the address matches.
312             if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
313                endpoint->addr,
314                sizeof(endpoint->addr)) == 0 &&
315                g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
316             {
317                 OCStackResult res = OC_STACK_ERROR;
318
319                 //If temporal secure sesstion established successfully
320                 if(CA_STATUS_OK == info->result &&
321                    false == newDevDoxm->owned &&
322                    memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
323                 {
324                     //Send request : PUT /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
325                     res = PutOwnerUuid(g_otmCtx);
326                     if(OC_STACK_OK != res)
327                     {
328                         OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
329                         SetResult(g_otmCtx, res);
330                     }
331                 }
332                 //In case of authentication failure
333                 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
334                 {
335                     //in case of error from owner credential
336                     if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
337                         true == newDevDoxm->owned)
338                     {
339                         OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
340
341                         if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
342                         {
343                             OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
344                         }
345                         SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
346                     }
347                     //in case of error from wrong PIN, re-start the ownership transfer
348                     else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
349                     {
350                         OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
351
352                         memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
353                         newDevDoxm->owned = false;
354                         g_otmCtx->attemptCnt++;
355
356                         if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
357                         {
358                             res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
359                             if(OC_STACK_OK != res)
360                             {
361                                 SetResult(g_otmCtx, res);
362                                 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
363                             }
364                         }
365                         else
366                         {
367                             OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
368                             SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
369                         }
370                     }
371                     else
372                     {
373                         OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
374                         SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
375                     }
376                 }
377             }
378         }
379     }
380 }
381
382 /**
383  * Function to save ownerPSK at provisioning tool end.
384  *
385  * @param[in] selectedDeviceInfo   selected device information to performing provisioning.
386  * @return  OC_STACK_OK on success
387  */
388 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
389 {
390     OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
391
392     OCStackResult res = OC_STACK_ERROR;
393
394     CAEndpoint_t endpoint;
395     memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
396     OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
397     endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
398     endpoint.port = selectedDeviceInfo->securePort;
399
400     OicUuid_t ptDeviceID = {.id={0}};
401     if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
402     {
403         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
404         return res;
405     }
406
407     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
408     OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
409
410     //Generating OwnerPSK
411     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
412             (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
413             strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
414             ptDeviceID.id, sizeof(ptDeviceID.id),
415             selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
416             ownerPSK, OWNER_PSK_LENGTH_128);
417
418     if (CA_STATUS_OK == pskRet)
419     {
420         OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
421         OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
422         //Generating new credential for provisioning tool
423         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
424                 SYMMETRIC_PAIR_WISE_KEY, NULL,
425                 &ownerKey, &ptDeviceID);
426         VERIFY_NON_NULL(TAG, cred, ERROR);
427
428         res = AddCredential(cred);
429         if(res != OC_STACK_OK)
430         {
431             DeleteCredList(cred);
432             return res;
433         }
434     }
435     else
436     {
437         OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
438     }
439
440     OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
441 exit:
442     return res;
443 }
444
445 /**
446  * Callback handler for OwnerShipTransferModeHandler API.
447  *
448  * @param[in] ctx             ctx value passed to callback from calling function.
449  * @param[in] UNUSED          handle to an invocation
450  * @param[in] clientResponse  Response from queries to remote servers.
451  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
452  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
453  */
454 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
455                                                          OCClientResponse *clientResponse)
456 {
457     OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
458
459     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
460     VERIFY_NON_NULL(TAG, ctx, WARNING);
461
462     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
463     (void)UNUSED;
464     if(clientResponse->result == OC_STACK_OK)
465     {
466         OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
467         //Send request : GET /oic/sec/pstat
468         OCStackResult res = GetProvisioningStatusResource(otmCtx);
469         if(OC_STACK_OK != res)
470         {
471             OIC_LOG(WARNING, TAG, "Failed to get pstat information");
472             SetResult(otmCtx, res);
473         }
474     }
475     else
476     {
477         OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
478         clientResponse->result);
479         SetResult(otmCtx, clientResponse->result);
480     }
481
482     OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
483
484 exit:
485     return  OC_STACK_DELETE_TRANSACTION;
486 }
487
488 /**
489  * Callback handler for ProvisioningStatusResouceHandler API.
490  *
491  * @param[in] ctx             ctx value passed to callback from calling function.
492  * @param[in] UNUSED          handle to an invocation
493  * @param[in] clientResponse  Response from queries to remote servers.
494  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
495  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
496  */
497 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
498                                                     OCClientResponse *clientResponse)
499 {
500     OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
501
502     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
503     VERIFY_NON_NULL(TAG, ctx, WARNING);
504
505     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
506     (void)UNUSED;
507     if  (OC_STACK_OK == clientResponse->result)
508     {
509         if  (NULL == clientResponse->payload)
510         {
511             OIC_LOG(INFO, TAG, "Skiping Null payload");
512             SetResult(otmCtx, OC_STACK_ERROR);
513             return OC_STACK_DELETE_TRANSACTION;
514         }
515
516         if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
517         {
518             OIC_LOG(INFO, TAG, "Unknown payload type");
519             SetResult(otmCtx, OC_STACK_ERROR);
520             return OC_STACK_DELETE_TRANSACTION;
521         }
522         OicSecPstat_t* pstat = NULL;
523         OCStackResult result = CBORPayloadToPstat(
524                 ((OCSecurityPayload*)clientResponse->payload)->securityData,
525                 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
526                 &pstat);
527         if(NULL == pstat || result != OC_STACK_OK)
528         {
529             OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
530             SetResult(otmCtx, OC_STACK_ERROR);
531             return OC_STACK_DELETE_TRANSACTION;
532         }
533         if(false == (TAKE_OWNER & pstat->cm))
534         {
535             OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
536             SetResult(otmCtx, OC_STACK_ERROR);
537             return OC_STACK_DELETE_TRANSACTION;
538         }
539         otmCtx->selectedDeviceInfo->pstat = pstat;
540
541         //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
542         SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
543
544         //Send request : PUT /oic/sec/pstat [{"om":"bx11", .. }]
545         OCStackResult res = PutUpdateOperationMode(otmCtx);
546         if (OC_STACK_OK != res)
547         {
548             OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
549             SetResult(otmCtx, res);
550         }
551     }
552     else
553     {
554         OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
555             clientResponse->result);
556         SetResult(otmCtx, clientResponse->result);
557     }
558
559     OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
560 exit:
561     return  OC_STACK_DELETE_TRANSACTION;
562 }
563
564 /**
565  * Response handler for update owner uuid request.
566  *
567  * @param[in] ctx             ctx value passed to callback from calling function.
568  * @param[in] UNUSED          handle to an invocation
569  * @param[in] clientResponse  Response from queries to remote servers.
570  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
571  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
572  */
573 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
574                                 OCClientResponse *clientResponse)
575 {
576     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
577     VERIFY_NON_NULL(TAG, ctx, WARNING);
578
579     OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
580     (void)UNUSED;
581     OCStackResult res = OC_STACK_OK;
582     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
583
584     if(OC_STACK_OK == clientResponse->result)
585     {
586         if(otmCtx && otmCtx->selectedDeviceInfo)
587         {
588             res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
589             if(OC_STACK_OK != res)
590             {
591                 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
592                 SetResult(otmCtx, res);
593                 return OC_STACK_DELETE_TRANSACTION;
594             }
595
596             //PUT owner credential to new device according to security spec B.
597             res = PutOwnerCredential(otmCtx);
598             if(OC_STACK_OK != res)
599             {
600                 OIC_LOG(ERROR, TAG,
601                         "OwnerUuidUpdateHandler:Failed to send PUT request for onwer credential");
602                 SetResult(otmCtx, res);
603                 return OC_STACK_DELETE_TRANSACTION;
604             }
605         }
606     }
607     else
608     {
609         res = clientResponse->result;
610         OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
611         SetResult(otmCtx, res);
612     }
613
614     OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
615
616 exit:
617     return  OC_STACK_DELETE_TRANSACTION;
618 }
619
620 /**
621  * Response handler for update operation mode.
622  *
623  * @param[in] ctx             ctx value passed to callback from calling function.
624  * @param[in] UNUSED          handle to an invocation
625  * @param[in] clientResponse  Response from queries to remote servers.
626  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
627  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
628  */
629 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
630                                 OCClientResponse *clientResponse)
631 {
632     OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
633
634     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
635     VERIFY_NON_NULL(TAG, ctx, WARNING);
636
637     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
638     (void) UNUSED;
639     if  (OC_STACK_OK == clientResponse->result)
640     {
641         OCStackResult res = OC_STACK_ERROR;
642         OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
643         //DTLS Handshake
644         //Load secret for temporal secure session.
645         if(g_OTMDatas[selOxm].loadSecretCB)
646         {
647             res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
648             if(OC_STACK_OK != res)
649             {
650                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
651                 SetResult(otmCtx, res);
652                 return  OC_STACK_DELETE_TRANSACTION;
653             }
654         }
655
656         //It will be used in handshake event handler
657         g_otmCtx = otmCtx;
658
659         //Try DTLS handshake to generate secure session
660         if(g_OTMDatas[selOxm].createSecureSessionCB)
661         {
662             res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
663             if(OC_STACK_OK != res)
664             {
665                 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
666                 SetResult(otmCtx, res);
667                 return OC_STACK_DELETE_TRANSACTION;
668             }
669         }
670     }
671     else
672     {
673         OIC_LOG(ERROR, TAG, "Error while update operation mode");
674         SetResult(otmCtx, clientResponse->result);
675     }
676
677     OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
678
679 exit:
680     return  OC_STACK_DELETE_TRANSACTION;
681 }
682
683 /**
684  * Response handler for update owner crendetial request.
685  *
686  * @param[in] ctx             ctx value passed to callback from calling function.
687  * @param[in] UNUSED          handle to an invocation
688  * @param[in] clientResponse  Response from queries to remote servers.
689  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
690  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
691  */
692 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
693                                 OCClientResponse *clientResponse)
694 {
695     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
696     VERIFY_NON_NULL(TAG, ctx, WARNING);
697
698     OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
699     (void)UNUSED;
700     OCStackResult res = OC_STACK_OK;
701     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
702
703     if(OC_STACK_RESOURCE_CREATED == clientResponse->result)
704     {
705         if(otmCtx && otmCtx->selectedDeviceInfo)
706         {
707             //Close the temporal secure session to verify the owner credential
708             CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
709             endpoint->port = otmCtx->selectedDeviceInfo->securePort;
710             CAResult_t caResult = CACloseDtlsSession(endpoint);
711             if(CA_STATUS_OK != caResult)
712             {
713                 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
714                 SetResult(otmCtx, caResult);
715                 return OC_STACK_DELETE_TRANSACTION;
716             }
717
718             /**
719              * If we select NULL cipher,
720              * client will select appropriate cipher suite according to server's cipher-suite list.
721              */
722             caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL);
723             if(CA_STATUS_OK != caResult)
724             {
725                 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
726                 SetResult(otmCtx, caResult);
727                 return OC_STACK_DELETE_TRANSACTION;
728             }
729
730             /**
731              * in case of random PIN based OxM,
732              * revert get_psk_info callback of tinyDTLS to use owner credential.
733              */
734             if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
735             {
736                 OicUuid_t emptyUuid = { .id={0}};
737                 SetUuidForRandomPinOxm(&emptyUuid);
738
739                 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
740                 {
741                     OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
742                     SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
743                     return OC_STACK_DELETE_TRANSACTION;
744                 }
745             }
746
747             //PUT /oic/sec/doxm [{ ..., "owned":"TRUE" }]
748             res = PutOwnershipInformation(otmCtx);
749             if(OC_STACK_OK != res)
750             {
751                 OIC_LOG(ERROR, TAG, "Failed to put ownership information to new device");
752                 SetResult(otmCtx, res);
753                 return OC_STACK_DELETE_TRANSACTION;
754             }
755         }
756     }
757     else
758     {
759         res = clientResponse->result;
760         OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
761         SetResult(otmCtx, res);
762     }
763
764     OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
765
766 exit:
767     return  OC_STACK_DELETE_TRANSACTION;
768 }
769
770
771 /**
772  * Response handler for update owner information request.
773  *
774  * @param[in] ctx             ctx value passed to callback from calling function.
775  * @param[in] UNUSED          handle to an invocation
776  * @param[in] clientResponse  Response from queries to remote servers.
777  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
778  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
779  */
780 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
781                                 OCClientResponse *clientResponse)
782 {
783     VERIFY_NON_NULL(TAG, clientResponse, WARNING);
784     VERIFY_NON_NULL(TAG, ctx, WARNING);
785
786     OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
787     (void)UNUSED;
788     OCStackResult res = OC_STACK_OK;
789     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
790
791     if(OC_STACK_OK == clientResponse->result)
792     {
793         if(otmCtx && otmCtx->selectedDeviceInfo)
794         {
795             OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
796             OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
797
798             res = PutProvisioningStatus(otmCtx);
799             if(OC_STACK_OK != res)
800             {
801                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
802                 SetResult(otmCtx, res);
803             }
804         }
805     }
806     else
807     {
808         res = clientResponse->result;
809         OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
810         SetResult(otmCtx, res);
811     }
812
813     OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
814
815 exit:
816     return  OC_STACK_DELETE_TRANSACTION;
817 }
818
819 /**
820  * Response handler of update provisioning status.
821  *
822  * @param[in] ctx             ctx value passed to callback from calling function.
823  * @param[in] UNUSED          handle to an invocation
824  * @param[in] clientResponse  Response from queries to remote servers.
825  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
826  *          and OC_STACK_KEEP_TRANSACTION to keep it.
827  */
828 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
829                                                        OCClientResponse *clientResponse)
830 {
831     OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
832
833     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
834     VERIFY_NON_NULL(TAG, ctx, ERROR);
835
836     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
837     (void)UNUSED;
838     OCStackResult res = OC_STACK_OK;
839
840     if(OC_STACK_OK == clientResponse->result)
841     {
842         if(otmCtx && otmCtx->selectedDeviceInfo)
843         {
844             OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
845
846             res = PutNormalOperationStatus(otmCtx);
847             if(OC_STACK_OK != res)
848             {
849                 OIC_LOG(ERROR, TAG, "Failed to update pstat");
850                 SetResult(otmCtx, res);
851             }
852         }
853     }
854     else
855     {
856         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
857                             clientResponse->result);
858         SetResult(otmCtx, clientResponse->result);
859     }
860
861 exit:
862     OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
863     return OC_STACK_DELETE_TRANSACTION;
864 }
865
866 /**
867  * Response handler of update provisioning status to Ready for Normal..
868  *
869  * @param[in] ctx             ctx value passed to callback from calling function.
870  * @param[in] UNUSED          handle to an invocation
871  * @param[in] clientResponse  Response from queries to remote servers.
872  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
873  *          and OC_STACK_KEEP_TRANSACTION to keep it.
874  */
875 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
876                                                        OCClientResponse *clientResponse)
877 {
878     OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
879
880     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
881     VERIFY_NON_NULL(TAG, ctx, ERROR);
882
883     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
884     (void)UNUSED;
885
886     if (OC_STACK_OK == clientResponse->result)
887     {
888         OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
889         OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
890          if (OC_STACK_OK == res)
891          {
892                 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
893                 SetResult(otmCtx, OC_STACK_OK);
894                 return OC_STACK_DELETE_TRANSACTION;
895          }
896           else
897          {
898               OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
899          }
900     }
901     else
902     {
903         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
904                             clientResponse->result);
905         SetResult(otmCtx, clientResponse->result);
906     }
907
908 exit:
909     OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
910     return OC_STACK_DELETE_TRANSACTION;
911 }
912
913 static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
914 {
915     OIC_LOG(DEBUG, TAG, "IN PutOwnerCredential");
916
917     if(!otmCtx || !otmCtx->selectedDeviceInfo)
918     {
919         OIC_LOG(ERROR, TAG, "Invalid parameters");
920         return OC_STACK_INVALID_PARAM;
921     }
922
923     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
924     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
925
926     if(!PMGenerateQuery(true,
927                         deviceInfo->endpoint.addr, deviceInfo->securePort,
928                         deviceInfo->connType,
929                         query, sizeof(query), OIC_RSRC_CRED_URI))
930     {
931         OIC_LOG(ERROR, TAG, "PutOwnerCredential : Failed to generate query");
932         return OC_STACK_ERROR;
933     }
934     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
935     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
936     if(!secPayload)
937     {
938         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
939         return OC_STACK_NO_MEMORY;
940     }
941
942     //Generate owner credential for new device
943     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
944     const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
945     if(!ownerCredential)
946     {
947         OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
948         return OC_STACK_NO_RESOURCE;
949     }
950
951     OicUuid_t credSubjectId = {.id={0}};
952     if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
953     {
954         OicSecCred_t newCredential;
955         memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
956         newCredential.next = NULL;
957
958         //Set subject ID as PT's ID
959         memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
960
961         //Fill private data as empty string
962         newCredential.privateData.data = NULL;
963         newCredential.privateData.len = 0;
964 #ifdef __WITH_X509__
965         newCredential.publicData.data = NULL;
966         newCredential.publicData.len = 0;
967 #endif
968
969         //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
970         if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData, &secPayload->payloadSize))
971         {
972             OICFree(secPayload);
973             OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
974             return OC_STACK_ERROR;
975         }
976         OIC_LOG(DEBUG, TAG, "Cred Payload:");
977         OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
978
979         OCCallbackData cbData;
980         cbData.cb = &OwnerCredentialHandler;
981         cbData.context = (void *)otmCtx;
982         cbData.cd = NULL;
983         OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
984                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
985                                          deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
986         if (res != OC_STACK_OK)
987         {
988             OIC_LOG(ERROR, TAG, "OCStack resource error");
989         }
990     }
991     else
992     {
993         OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
994         return OC_STACK_NO_RESOURCE;
995     }
996
997     OIC_LOG(DEBUG, TAG, "OUT PutOwnerCredential");
998
999     return OC_STACK_OK;
1000 }
1001
1002 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
1003 {
1004     OIC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
1005
1006     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1007     {
1008         OIC_LOG(ERROR, TAG, "Invalid parameters");
1009         return OC_STACK_INVALID_PARAM;
1010     }
1011
1012     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1013     OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1014     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1015
1016     if(!PMGenerateQuery(false,
1017                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1018                         deviceInfo->connType,
1019                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1020     {
1021         OIC_LOG(ERROR, TAG, "PutOwnerTransferModeToResource : Failed to generate query");
1022         return OC_STACK_ERROR;
1023     }
1024     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1025     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1026     if(!secPayload)
1027     {
1028         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1029         return OC_STACK_NO_MEMORY;
1030     }
1031     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1032     OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1033             &secPayload->securityData, &secPayload->payloadSize);
1034     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1035     {
1036         OCPayloadDestroy((OCPayload *)secPayload);
1037         OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1038         return OC_STACK_ERROR;
1039     }
1040
1041     OCCallbackData cbData;
1042     cbData.cb = &OwnerTransferModeHandler;
1043     cbData.context = (void *)otmCtx;
1044     cbData.cd = NULL;
1045     res = OCDoResource(NULL, OC_REST_PUT, query,
1046                        &deviceInfo->endpoint, (OCPayload *)secPayload,
1047                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1048     if (res != OC_STACK_OK)
1049     {
1050         OIC_LOG(ERROR, TAG, "OCStack resource error");
1051     }
1052
1053     OIC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
1054
1055     return res;
1056 }
1057
1058 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1059 {
1060     OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1061
1062     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1063     {
1064         OIC_LOG(ERROR, TAG, "Invailed parameters");
1065         return OC_STACK_INVALID_PARAM;
1066     }
1067
1068     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1069     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1070     if(!PMGenerateQuery(false,
1071                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1072                         deviceInfo->connType,
1073                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1074     {
1075         OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1076         return OC_STACK_ERROR;
1077     }
1078     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1079
1080     OCCallbackData cbData;
1081     cbData.cb = &ListMethodsHandler;
1082     cbData.context = (void *)otmCtx;
1083     cbData.cd = NULL;
1084     OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1085                                      deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1086     if (res != OC_STACK_OK)
1087     {
1088         OIC_LOG(ERROR, TAG, "OCStack resource error");
1089     }
1090
1091     OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1092
1093     return res;
1094 }
1095
1096 static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
1097 {
1098     OIC_LOG(DEBUG, TAG, "IN PutOwnerUuid");
1099
1100     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1101     {
1102         OIC_LOG(ERROR, TAG, "Invailed parameters");
1103         return OC_STACK_INVALID_PARAM;
1104     }
1105
1106     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1107     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1108     if(!PMGenerateQuery(true,
1109                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1110                         deviceInfo->connType,
1111                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1112     {
1113         OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
1114         return OC_STACK_ERROR;
1115     }
1116     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1117
1118     //PUT PT's uuid to new device
1119     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1120     if(!secPayload)
1121     {
1122         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1123         return OC_STACK_NO_MEMORY;
1124     }
1125     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1126     OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1127             otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1128     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1129     {
1130         OCPayloadDestroy((OCPayload *)secPayload);
1131         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1132         return OC_STACK_INVALID_PARAM;
1133     }
1134     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1135
1136     OCCallbackData cbData;
1137     cbData.cb = &OwnerUuidUpdateHandler;
1138     cbData.context = (void *)otmCtx;
1139     cbData.cd = NULL;
1140
1141     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
1142             deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1143     if (res != OC_STACK_OK)
1144     {
1145         OIC_LOG(ERROR, TAG, "OCStack resource error");
1146     }
1147
1148     OIC_LOG(DEBUG, TAG, "OUT PutOwnerUuid");
1149
1150     return res;
1151 }
1152
1153 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
1154 {
1155     OIC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
1156
1157     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1158     {
1159         OIC_LOG(ERROR, TAG, "Invailed parameters");
1160         return OC_STACK_INVALID_PARAM;
1161     }
1162
1163     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1164     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1165     if(!PMGenerateQuery(true,
1166                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1167                         deviceInfo->connType,
1168                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1169     {
1170         OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
1171         return OC_STACK_ERROR;
1172     }
1173     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1174
1175     //OwnershipInformationHandler
1176     OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1177     if (!secPayload)
1178     {
1179         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1180         return OC_STACK_NO_MEMORY;
1181     }
1182
1183     otmCtx->selectedDeviceInfo->doxm->owned = true;
1184
1185     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1186     OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1187             &secPayload->securityData, &secPayload->payloadSize);
1188     if (OC_STACK_OK != res && NULL == secPayload->securityData)
1189     {
1190         OCPayloadDestroy((OCPayload *)secPayload);
1191         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1192         return OC_STACK_INVALID_PARAM;
1193     }
1194
1195     OCCallbackData cbData;
1196     cbData.cb = &OwnershipInformationHandler;
1197     cbData.context = (void *)otmCtx;
1198     cbData.cd = NULL;
1199
1200     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1201                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1202     if (res != OC_STACK_OK)
1203     {
1204         OIC_LOG(ERROR, TAG, "OCStack resource error");
1205     }
1206
1207     OIC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
1208
1209     return res;
1210 }
1211
1212 static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
1213 {
1214     OIC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
1215
1216     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1217     {
1218         return OC_STACK_INVALID_PARAM;
1219     }
1220
1221     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1222     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1223     if(!PMGenerateQuery(false,
1224                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1225                         deviceInfo->connType,
1226                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1227     {
1228         OIC_LOG(ERROR, TAG, "PutUpdateOperationMode : Failed to generate query");
1229         return OC_STACK_ERROR;
1230     }
1231     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1232
1233     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1234     if(!secPayload)
1235     {
1236         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1237         return OC_STACK_NO_MEMORY;
1238     }
1239     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1240     OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1241                                            &secPayload->payloadSize);
1242    if (OC_STACK_OK != res)
1243     {
1244         OCPayloadDestroy((OCPayload *)secPayload);
1245         OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1246         return OC_STACK_INVALID_PARAM;
1247     }
1248
1249     OCCallbackData cbData;
1250     cbData.cb = &OperationModeUpdateHandler;
1251     cbData.context = (void *)otmCtx;
1252     cbData.cd = NULL;
1253     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
1254                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1255     if (res != OC_STACK_OK)
1256     {
1257         OIC_LOG(ERROR, TAG, "OCStack resource error");
1258     }
1259
1260     OIC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
1261
1262     return res;
1263 }
1264
1265 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1266 {
1267     OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1268     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1269     otmCtx->selectedDeviceInfo = selectedDevice;
1270
1271     //Set to the lowest level OxM, and then find more higher level OxM.
1272     OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1273                                                  selectedDevice->doxm->oxmLen,
1274                                                  &selectedDevice->doxm->oxmSel);
1275     if(OC_STACK_OK != res)
1276     {
1277         OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1278         SetResult(otmCtx, res);
1279         return res;
1280     }
1281     OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1282
1283     //Send Req: PUT /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1284     res = PutOwnerTransferModeToResource(otmCtx);
1285     if(OC_STACK_OK != res)
1286     {
1287         OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1288         SetResult(otmCtx, res);
1289         return res;
1290     }
1291
1292     //Register DTLS event handler to catch the dtls event while handshake
1293     if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DTLSHandshakeCB))
1294     {
1295         OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
1296     }
1297
1298     OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1299
1300     return res;
1301
1302 }
1303
1304 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1305 {
1306     OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1307
1308     if(!data)
1309     {
1310         OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1311         return OC_STACK_INVALID_PARAM;
1312     }
1313     if(oxmType >= OIC_OXM_COUNT)
1314     {
1315         OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1316         return OC_STACK_INVALID_PARAM;
1317     }
1318
1319     g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1320     g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1321     g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1322     g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1323
1324     OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1325
1326     return OC_STACK_OK;
1327 }
1328
1329 /**
1330  * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1331  */
1332 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1333                                      OCProvisionDev_t *selectedDevicelist,
1334                                      OCProvisionResultCB resultCallback)
1335 {
1336     OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1337
1338     if (NULL == selectedDevicelist)
1339     {
1340         return OC_STACK_INVALID_PARAM;
1341     }
1342     if (NULL == resultCallback)
1343     {
1344         return OC_STACK_INVALID_CALLBACK;
1345     }
1346
1347     OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1348     if(!otmCtx)
1349     {
1350         OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1351         return OC_STACK_NO_MEMORY;
1352     }
1353     otmCtx->ctxResultCallback = resultCallback;
1354     otmCtx->ctxHasError = false;
1355     otmCtx->userCtx = ctx;
1356     OCProvisionDev_t* pCurDev = selectedDevicelist;
1357
1358     //Counting number of selected devices.
1359     otmCtx->ctxResultArraySize = 0;
1360     while(NULL != pCurDev)
1361     {
1362         otmCtx->ctxResultArraySize++;
1363         pCurDev = pCurDev->next;
1364     }
1365
1366     otmCtx->ctxResultArray =
1367         (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1368     if(NULL == otmCtx->ctxResultArray)
1369     {
1370         OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1371         OICFree(otmCtx);
1372         return OC_STACK_NO_MEMORY;
1373     }
1374     pCurDev = selectedDevicelist;
1375
1376     OCStackResult res = OC_STACK_OK;
1377     //Fill the device UUID for result array.
1378     for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1379     {
1380         //Checking duplication of Device ID.
1381         bool isDuplicate = true;
1382         res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1383         if (OC_STACK_OK != res)
1384         {
1385             goto error;
1386         }
1387         if (isDuplicate)
1388         {
1389             OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device ID is duplicated");
1390             res = OC_STACK_INVALID_PARAM;
1391             goto error;
1392         }
1393         memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1394                pCurDev->doxm->deviceID.id,
1395                UUID_LENGTH);
1396         otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1397         pCurDev = pCurDev->next;
1398     }
1399
1400     StartOwnershipTransfer(otmCtx, selectedDevicelist);
1401
1402     OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1403     return OC_STACK_OK;
1404
1405 error:
1406     OICFree(otmCtx->ctxResultArray);
1407     OICFree(otmCtx);
1408     return res;
1409 }
1410
1411 OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
1412 {
1413     OIC_LOG(INFO, TAG, "IN PutProvisioningStatus");
1414
1415     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1416     {
1417         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1418         return OC_STACK_INVALID_PARAM;
1419     }
1420
1421     //Change the TAKE_OWNER bit of CM to 0.
1422     otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1423
1424     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1425     if (!secPayload)
1426     {
1427         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1428         return OC_STACK_NO_MEMORY;
1429     }
1430     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1431     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1432             &secPayload->securityData, &secPayload->payloadSize))
1433     {
1434         OCPayloadDestroy((OCPayload *)secPayload);
1435         return OC_STACK_INVALID_JSON;
1436     }
1437     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1438     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1439
1440     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1441     if(!PMGenerateQuery(true,
1442                         otmCtx->selectedDeviceInfo->endpoint.addr,
1443                         otmCtx->selectedDeviceInfo->securePort,
1444                         otmCtx->selectedDeviceInfo->connType,
1445                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1446     {
1447         OIC_LOG(ERROR, TAG, "PutProvisioningStatus : Failed to generate query");
1448         return OC_STACK_ERROR;
1449     }
1450     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1451
1452     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1453     cbData.cb = &ProvisioningStatusHandler;
1454     cbData.context = (void*)otmCtx;
1455     cbData.cd = NULL;
1456     OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1457             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1458     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1459     if (ret != OC_STACK_OK)
1460     {
1461         OIC_LOG(ERROR, TAG, "OCStack resource error");
1462     }
1463
1464     OIC_LOG(INFO, TAG, "OUT PutProvisioningStatus");
1465
1466     return ret;
1467 }
1468
1469 OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
1470 {
1471     OIC_LOG(INFO, TAG, "IN PutNormalOperationStatus");
1472
1473     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1474     {
1475         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1476         return OC_STACK_INVALID_PARAM;
1477     }
1478
1479     //Set isop to true.
1480     otmCtx->selectedDeviceInfo->pstat->isOp = true;
1481
1482     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1483     if (!secPayload)
1484     {
1485         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1486         return OC_STACK_NO_MEMORY;
1487     }
1488     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1489     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1490             &secPayload->securityData, &secPayload->payloadSize))
1491     {
1492         OCPayloadDestroy((OCPayload *)secPayload);
1493         return OC_STACK_INVALID_JSON;
1494     }
1495     OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1496     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1497
1498     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1499     if(!PMGenerateQuery(true,
1500                         otmCtx->selectedDeviceInfo->endpoint.addr,
1501                         otmCtx->selectedDeviceInfo->securePort,
1502                         otmCtx->selectedDeviceInfo->connType,
1503                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1504     {
1505         OIC_LOG(ERROR, TAG, "PutNormalOperationStatus : Failed to generate query");
1506         return OC_STACK_ERROR;
1507     }
1508     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1509
1510     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1511     cbData.cb = &ReadyForNomalStatusHandler;
1512     cbData.context = (void*)otmCtx;
1513     cbData.cd = NULL;
1514     OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1515             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1516     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1517     if (ret != OC_STACK_OK)
1518     {
1519         OIC_LOG(ERROR, TAG, "OCStack resource error");
1520     }
1521
1522     OIC_LOG(INFO, TAG, "OUT PutNormalOperationStatus");
1523
1524     return ret;
1525 }