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