Modify to update rowner as PT's UUID when ownership transfer is done.
[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  * Number of supported provisioning methods
73  * current version supports only one.
74  */
75 static size_t gNumOfProvisioningMethodsPT = 1;
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)->securityData1,
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     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->securityData1, &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_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
977
978         OCCallbackData cbData;
979         cbData.cb = &OwnerCredentialHandler;
980         cbData.context = (void *)otmCtx;
981         cbData.cd = NULL;
982         OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
983                                          &deviceInfo->endpoint, (OCPayload*)secPayload,
984                                          deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
985         if (res != OC_STACK_OK)
986         {
987             OIC_LOG(ERROR, TAG, "OCStack resource error");
988         }
989     }
990     else
991     {
992         OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
993         return OC_STACK_NO_RESOURCE;
994     }
995
996     OIC_LOG(DEBUG, TAG, "OUT PutOwnerCredential");
997
998     return OC_STACK_OK;
999 }
1000
1001 static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
1002 {
1003     OIC_LOG(DEBUG, TAG, "IN PutOwnerTransferModeToResource");
1004
1005     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1006     {
1007         OIC_LOG(ERROR, TAG, "Invalid parameters");
1008         return OC_STACK_INVALID_PARAM;
1009     }
1010
1011     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1012     OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1013     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1014
1015     if(!PMGenerateQuery(false,
1016                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1017                         deviceInfo->connType,
1018                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1019     {
1020         OIC_LOG(ERROR, TAG, "PutOwnerTransferModeToResource : Failed to generate query");
1021         return OC_STACK_ERROR;
1022     }
1023     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1024     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1025     if(!secPayload)
1026     {
1027         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1028         return OC_STACK_NO_MEMORY;
1029     }
1030     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1031     OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1032             &secPayload->securityData1, &secPayload->payloadSize);
1033     if (OC_STACK_OK != res && NULL == secPayload->securityData1)
1034     {
1035         OCPayloadDestroy((OCPayload *)secPayload);
1036         OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1037         return OC_STACK_ERROR;
1038     }
1039
1040     OCCallbackData cbData;
1041     cbData.cb = &OwnerTransferModeHandler;
1042     cbData.context = (void *)otmCtx;
1043     cbData.cd = NULL;
1044     res = OCDoResource(NULL, OC_REST_PUT, query,
1045                        &deviceInfo->endpoint, (OCPayload *)secPayload,
1046                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1047     if (res != OC_STACK_OK)
1048     {
1049         OIC_LOG(ERROR, TAG, "OCStack resource error");
1050     }
1051
1052     OIC_LOG(DEBUG, TAG, "OUT PutOwnerTransferModeToResource");
1053
1054     return res;
1055 }
1056
1057 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1058 {
1059     OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1060
1061     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1062     {
1063         OIC_LOG(ERROR, TAG, "Invailed parameters");
1064         return OC_STACK_INVALID_PARAM;
1065     }
1066
1067     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1068     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1069     if(!PMGenerateQuery(false,
1070                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1071                         deviceInfo->connType,
1072                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1073     {
1074         OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1075         return OC_STACK_ERROR;
1076     }
1077     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1078
1079     OCCallbackData cbData;
1080     cbData.cb = &ListMethodsHandler;
1081     cbData.context = (void *)otmCtx;
1082     cbData.cd = NULL;
1083     OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1084                                      deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1085     if (res != OC_STACK_OK)
1086     {
1087         OIC_LOG(ERROR, TAG, "OCStack resource error");
1088     }
1089
1090     OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1091
1092     return res;
1093 }
1094
1095 static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
1096 {
1097     OIC_LOG(DEBUG, TAG, "IN PutOwnerUuid");
1098
1099     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1100     {
1101         OIC_LOG(ERROR, TAG, "Invailed parameters");
1102         return OC_STACK_INVALID_PARAM;
1103     }
1104
1105     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1106     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1107     if(!PMGenerateQuery(true,
1108                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1109                         deviceInfo->connType,
1110                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1111     {
1112         OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
1113         return OC_STACK_ERROR;
1114     }
1115     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1116
1117     //PUT PT's uuid to new device
1118     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1119     if(!secPayload)
1120     {
1121         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1122         return OC_STACK_NO_MEMORY;
1123     }
1124     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1125     OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1126             otmCtx, &secPayload->securityData1, &secPayload->payloadSize);
1127     if (NULL == secPayload->securityData1)
1128     {
1129         OCPayloadDestroy((OCPayload *)secPayload);
1130         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1131         return OC_STACK_INVALID_PARAM;
1132     }
1133     OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
1134
1135     OCCallbackData cbData;
1136     cbData.cb = &OwnerUuidUpdateHandler;
1137     cbData.context = (void *)otmCtx;
1138     cbData.cd = NULL;
1139
1140     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
1141             deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1142     if (res != OC_STACK_OK)
1143     {
1144         OIC_LOG(ERROR, TAG, "OCStack resource error");
1145     }
1146
1147     OIC_LOG(DEBUG, TAG, "OUT PutOwnerUuid");
1148
1149     return res;
1150 }
1151
1152 static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
1153 {
1154     OIC_LOG(DEBUG, TAG, "IN PutOwnershipInformation");
1155
1156     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1157     {
1158         OIC_LOG(ERROR, TAG, "Invailed parameters");
1159         return OC_STACK_INVALID_PARAM;
1160     }
1161
1162     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1163     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1164     if(!PMGenerateQuery(true,
1165                         deviceInfo->endpoint.addr, deviceInfo->securePort,
1166                         deviceInfo->connType,
1167                         query, sizeof(query), OIC_RSRC_DOXM_URI))
1168     {
1169         OIC_LOG(ERROR, TAG, "PutOwnershipInformation : Failed to generate query");
1170         return OC_STACK_ERROR;
1171     }
1172     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1173
1174     //OwnershipInformationHandler
1175     OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1176     if (!secPayload)
1177     {
1178         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1179         return OC_STACK_NO_MEMORY;
1180     }
1181
1182     otmCtx->selectedDeviceInfo->doxm->owned = true;
1183
1184     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1185     OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1186             &secPayload->securityData1, &secPayload->payloadSize);
1187     if (OC_STACK_OK != res && NULL == secPayload->securityData1)
1188     {
1189         OCPayloadDestroy((OCPayload *)secPayload);
1190         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1191         return OC_STACK_INVALID_PARAM;
1192     }
1193
1194     OCCallbackData cbData;
1195     cbData.cb = &OwnershipInformationHandler;
1196     cbData.context = (void *)otmCtx;
1197     cbData.cd = NULL;
1198
1199     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1200                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1201     if (res != OC_STACK_OK)
1202     {
1203         OIC_LOG(ERROR, TAG, "OCStack resource error");
1204     }
1205
1206     OIC_LOG(DEBUG, TAG, "OUT PutOwnershipInformation");
1207
1208     return res;
1209 }
1210
1211 static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
1212 {
1213     OIC_LOG(DEBUG, TAG, "IN PutUpdateOperationMode");
1214
1215     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1216     {
1217         return OC_STACK_INVALID_PARAM;
1218     }
1219
1220     OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1221     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1222     if(!PMGenerateQuery(false,
1223                         deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1224                         deviceInfo->connType,
1225                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1226     {
1227         OIC_LOG(ERROR, TAG, "PutUpdateOperationMode : Failed to generate query");
1228         return OC_STACK_ERROR;
1229     }
1230     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1231
1232     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1233     if(!secPayload)
1234     {
1235         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1236         return OC_STACK_NO_MEMORY;
1237     }
1238     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1239     OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData1,
1240                                            &secPayload->payloadSize);
1241    if (OC_STACK_OK != res)
1242     {
1243         OCPayloadDestroy((OCPayload *)secPayload);
1244         OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1245         return OC_STACK_INVALID_PARAM;
1246     }
1247
1248     OCCallbackData cbData;
1249     cbData.cb = &OperationModeUpdateHandler;
1250     cbData.context = (void *)otmCtx;
1251     cbData.cd = NULL;
1252     res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
1253                        deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
1254     if (res != OC_STACK_OK)
1255     {
1256         OIC_LOG(ERROR, TAG, "OCStack resource error");
1257     }
1258
1259     OIC_LOG(DEBUG, TAG, "OUT PutUpdateOperationMode");
1260
1261     return res;
1262 }
1263
1264 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1265 {
1266     OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1267     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1268     otmCtx->selectedDeviceInfo = selectedDevice;
1269
1270     //Set to the lowest level OxM, and then find more higher level OxM.
1271     OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1272                                                  selectedDevice->doxm->oxmLen,
1273                                                  &selectedDevice->doxm->oxmSel);
1274     if(OC_STACK_OK != res)
1275     {
1276         OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1277         SetResult(otmCtx, res);
1278         return res;
1279     }
1280     OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1281
1282     //Send Req: PUT /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1283     res = PutOwnerTransferModeToResource(otmCtx);
1284     if(OC_STACK_OK != res)
1285     {
1286         OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1287         SetResult(otmCtx, res);
1288         return res;
1289     }
1290
1291     //Register DTLS event handler to catch the dtls event while handshake
1292     if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DTLSHandshakeCB))
1293     {
1294         OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
1295     }
1296
1297     OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1298
1299     return res;
1300
1301 }
1302
1303 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1304 {
1305     OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1306
1307     if(!data)
1308     {
1309         OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1310         return OC_STACK_INVALID_PARAM;
1311     }
1312     if(oxmType >= OIC_OXM_COUNT)
1313     {
1314         OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1315         return OC_STACK_INVALID_PARAM;
1316     }
1317
1318     g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1319     g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1320     g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1321     g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1322
1323     OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1324
1325     return OC_STACK_OK;
1326 }
1327
1328 /**
1329  * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1330  */
1331 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1332                                      OCProvisionDev_t *selectedDevicelist,
1333                                      OCProvisionResultCB resultCallback)
1334 {
1335     OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1336
1337     if (NULL == selectedDevicelist)
1338     {
1339         return OC_STACK_INVALID_PARAM;
1340     }
1341     if (NULL == resultCallback)
1342     {
1343         return OC_STACK_INVALID_CALLBACK;
1344     }
1345
1346     OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1347     if(!otmCtx)
1348     {
1349         OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1350         return OC_STACK_NO_MEMORY;
1351     }
1352     otmCtx->ctxResultCallback = resultCallback;
1353     otmCtx->ctxHasError = false;
1354     otmCtx->userCtx = ctx;
1355     OCProvisionDev_t* pCurDev = selectedDevicelist;
1356
1357     //Counting number of selected devices.
1358     otmCtx->ctxResultArraySize = 0;
1359     while(NULL != pCurDev)
1360     {
1361         otmCtx->ctxResultArraySize++;
1362         pCurDev = pCurDev->next;
1363     }
1364
1365     otmCtx->ctxResultArray =
1366         (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1367     if(NULL == otmCtx->ctxResultArray)
1368     {
1369         OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1370         OICFree(otmCtx);
1371         return OC_STACK_NO_MEMORY;
1372     }
1373     pCurDev = selectedDevicelist;
1374
1375     OCStackResult res = OC_STACK_OK;
1376     //Fill the device UUID for result array.
1377     for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1378     {
1379         //Checking duplication of Device ID.
1380         bool isDuplicate = true;
1381         res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1382         if (OC_STACK_OK != res)
1383         {
1384             goto error;
1385         }
1386         if (isDuplicate)
1387         {
1388             OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device ID is duplicated");
1389             res = OC_STACK_INVALID_PARAM;
1390             goto error;
1391         }
1392         memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1393                pCurDev->doxm->deviceID.id,
1394                UUID_LENGTH);
1395         otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1396         pCurDev = pCurDev->next;
1397     }
1398
1399     StartOwnershipTransfer(otmCtx, selectedDevicelist);
1400
1401     OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1402     return OC_STACK_OK;
1403
1404 error:
1405     OICFree(otmCtx->ctxResultArray);
1406     OICFree(otmCtx);
1407     return res;
1408 }
1409
1410 /**
1411  * Callback handler of SRPFinalizeProvisioning.
1412  *
1413  * @param[in] ctx             ctx value passed to callback from calling function.
1414  * @param[in] UNUSED          handle to an invocation
1415  * @param[in] clientResponse  Response from queries to remote servers.
1416  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1417  *          and OC_STACK_KEEP_TRANSACTION to keep it.
1418  */
1419 static OCStackApplicationResult FinalizeProvisioningCB(void *ctx, OCDoHandle UNUSED,
1420                                                        OCClientResponse *clientResponse)
1421 {
1422     OIC_LOG_V(INFO, TAG, "IN FinalizeProvisioningCB.");
1423
1424     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1425     VERIFY_NON_NULL(TAG, ctx, ERROR);
1426
1427     OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1428     (void)UNUSED;
1429     if(OC_STACK_OK == clientResponse->result)
1430     {
1431         OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
1432
1433          if (OC_STACK_OK == res)
1434          {
1435                 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
1436                 SetResult(otmCtx, OC_STACK_OK);
1437                 return OC_STACK_DELETE_TRANSACTION;
1438          }
1439          else
1440          {
1441               OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
1442          }
1443     }
1444 exit:
1445     return OC_STACK_DELETE_TRANSACTION;
1446 }
1447
1448 /**
1449  * Callback handler of default ACL provisioning.
1450  *
1451  * @param[in] ctx             ctx value passed to callback from calling function.
1452  * @param[in] UNUSED          handle to an invocation
1453  * @param[in] clientResponse  Response from queries to remote servers.
1454  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1455  *          and OC_STACK_KEEP_TRANSACTION to keep it.
1456  */
1457 static OCStackApplicationResult ProvisionDefaultACLCB(void *ctx, OCDoHandle UNUSED,
1458                                                        OCClientResponse *clientResponse)
1459 {
1460     OIC_LOG_V(INFO, TAG, "IN ProvisionDefaultACLCB.");
1461
1462     VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1463     VERIFY_NON_NULL(TAG, ctx, ERROR);
1464
1465     OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1466     (void)UNUSED;
1467
1468     if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
1469     {
1470         OIC_LOG_V(INFO, TAG, "Staring commit hash task.");
1471         // TODO hash currently have fixed value 0.
1472         uint16_t aclHash = 0;
1473         otmCtx->selectedDeviceInfo->pstat->commitHash = aclHash;
1474         otmCtx->selectedDeviceInfo->pstat->tm = NORMAL;
1475         OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1476         if(!secPayload)
1477         {
1478             OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1479             return OC_STACK_NO_MEMORY;
1480         }
1481         secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1482         OCStackResult res = PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1483                 &secPayload->securityData1, &secPayload->payloadSize);
1484         if (OC_STACK_OK != res || NULL == secPayload->securityData1)
1485         {
1486             OICFree(secPayload);
1487             SetResult(otmCtx, OC_STACK_INVALID_JSON);
1488             return OC_STACK_DELETE_TRANSACTION;
1489         }
1490
1491         char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1492         if(!PMGenerateQuery(true,
1493                             otmCtx->selectedDeviceInfo->endpoint.addr,
1494                             otmCtx->selectedDeviceInfo->securePort,
1495                             otmCtx->selectedDeviceInfo->connType,
1496                             query, sizeof(query), OIC_RSRC_PSTAT_URI))
1497         {
1498             OIC_LOG(ERROR, TAG, "ProvisionDefaultACLCB : Failed to generate query");
1499             return OC_STACK_ERROR;
1500         }
1501         OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1502
1503         OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1504         cbData.cb = &FinalizeProvisioningCB;
1505         cbData.context = (void*)otmCtx;
1506         cbData.cd = NULL;
1507         OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1508                 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1509         OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1510         if (ret != OC_STACK_OK)
1511         {
1512             OIC_LOG(ERROR, TAG, "OCStack resource error");
1513             SetResult(otmCtx, ret);
1514         }
1515     }
1516     else
1517     {
1518         OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1519                             clientResponse->result);
1520         SetResult(otmCtx, clientResponse->result);
1521     }
1522 exit:
1523     return OC_STACK_DELETE_TRANSACTION;
1524 }
1525
1526 OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
1527 {
1528     OIC_LOG(INFO, TAG, "IN PutProvisioningStatus");
1529
1530     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1531     {
1532         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1533         return OC_STACK_INVALID_PARAM;
1534     }
1535
1536     //Change the TAKE_OWNER bit of CM to 0.
1537     otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1538
1539     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1540     if (!secPayload)
1541     {
1542         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1543         return OC_STACK_NO_MEMORY;
1544     }
1545     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1546     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1547             &secPayload->securityData1, &secPayload->payloadSize))
1548     {
1549         OCPayloadDestroy((OCPayload *)secPayload);
1550         return OC_STACK_INVALID_JSON;
1551     }
1552     OIC_LOG_V(INFO, TAG, "Created payload for chage to Provisiong state : %s",secPayload->securityData1);
1553
1554     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1555     if(!PMGenerateQuery(true,
1556                         otmCtx->selectedDeviceInfo->endpoint.addr,
1557                         otmCtx->selectedDeviceInfo->securePort,
1558                         otmCtx->selectedDeviceInfo->connType,
1559                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1560     {
1561         OIC_LOG(ERROR, TAG, "PutProvisioningStatus : Failed to generate query");
1562         return OC_STACK_ERROR;
1563     }
1564     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1565
1566     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1567     cbData.cb = &ProvisioningStatusHandler;
1568     cbData.context = (void*)otmCtx;
1569     cbData.cd = NULL;
1570     OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1571             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1572     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1573     if (ret != OC_STACK_OK)
1574     {
1575         OIC_LOG(ERROR, TAG, "OCStack resource error");
1576     }
1577
1578     OIC_LOG(INFO, TAG, "OUT PutProvisioningStatus");
1579
1580     return ret;
1581 }
1582
1583 OCStackResult PutNormalOperationStatus(OTMContext_t* otmCtx)
1584 {
1585     OIC_LOG(INFO, TAG, "IN PutNormalOperationStatus");
1586
1587     if(!otmCtx || !otmCtx->selectedDeviceInfo)
1588     {
1589         OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1590         return OC_STACK_INVALID_PARAM;
1591     }
1592
1593     //Set isop to true.
1594     otmCtx->selectedDeviceInfo->pstat->isOp = true;
1595
1596     OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1597     if (!secPayload)
1598     {
1599         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1600         return OC_STACK_NO_MEMORY;
1601     }
1602     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1603     if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1604             &secPayload->securityData1, &secPayload->payloadSize))
1605     {
1606         OCPayloadDestroy((OCPayload *)secPayload);
1607         return OC_STACK_INVALID_JSON;
1608     }
1609     OIC_LOG_V(INFO, TAG, "Created payload for chage to Provisiong state: %s",secPayload->securityData1);
1610
1611     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1612     if(!PMGenerateQuery(true,
1613                         otmCtx->selectedDeviceInfo->endpoint.addr,
1614                         otmCtx->selectedDeviceInfo->securePort,
1615                         otmCtx->selectedDeviceInfo->connType,
1616                         query, sizeof(query), OIC_RSRC_PSTAT_URI))
1617     {
1618         OIC_LOG(ERROR, TAG, "PutNormalOperationStatus : Failed to generate query");
1619         return OC_STACK_ERROR;
1620     }
1621     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1622
1623     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1624     cbData.cb = &ReadyForNomalStatusHandler;
1625     cbData.context = (void*)otmCtx;
1626     cbData.cd = NULL;
1627     OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
1628             otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1629     OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1630     if (ret != OC_STACK_OK)
1631     {
1632         OIC_LOG(ERROR, TAG, "OCStack resource error");
1633     }
1634
1635     OIC_LOG(INFO, TAG, "OUT PutNormalOperationStatus");
1636
1637     return ret;
1638 }