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