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