d75ed460207b8fb2227b5b83f8ea2815061489d6
[platform/core/connectivity/bluetooth-frwk.git] / bt-otp / bt-otpserver.c
1 /*
2  * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *              http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 #include <dlog.h>
19 #include <gio/gio.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <time.h>
25 #include <sys/stat.h>
26 #include <langinfo.h>
27 #include <inttypes.h>
28 #include <errno.h>
29 #include <gio/gunixfdlist.h>
30
31 #include "bt-otpserver.h"
32 #include "bluetooth-api.h"
33
34
35 #undef LOG_TAG
36 #define LOG_TAG "BLUETOOTH_OTP"
37
38 #define BT_INFO(fmt, arg...) SLOGI(fmt, ##arg)
39 #define BT_ERR(fmt, arg...) SLOGE(fmt, ##arg)
40 #define BT_DBG(fmt, arg...) SLOGD(fmt, ##arg)
41
42 /* OTP object paths */
43 char *otp_obj_path = NULL;
44 char *otp_feature_obj_path = NULL;
45 char *otp_object_name_obj_path = NULL;
46 char *otp_object_type_obj_path = NULL;
47 char *otp_object_size_obj_path = NULL;
48 char *otp_object_first_created_obj_path = NULL;
49 char *otp_object_last_modified_obj_path = NULL;
50 char *otp_object_id_obj_path = NULL;
51 char *otp_object_prop_obj_path = NULL;
52 char *otp_oacp_obj_path = NULL;
53 char *otp_olcp_obj_path = NULL;
54 char *otp_oacp_desc_obj_path = NULL;
55 char *otp_olcp_desc_obj_path = NULL;
56
57 static GMainLoop *main_loop;
58 GDBusNodeInfo *otp_node_info = NULL;
59 static GDBusConnection *conn;
60 static GDBusConnection *g_conn;
61
62 static int property_sub_id = -1;
63 static int adapter_sub_id = -1;
64 static int device_sub_id = -1;
65 static guint g_owner_id = 0;
66
67 struct otp_char_info {
68         gchar *char_path;
69         gchar *char_value;
70         int value_length;
71 };
72
73 struct indicate_info {
74         uint8_t resp_opcode;
75         uint8_t req_opcode;
76         uint8_t result_code;
77         uint8_t *resp_param;
78 };
79
80 /* Object metadata */
81 struct object_metadata {
82         gchar *name;
83         gchar *type;
84         uint32_t curr_size;
85         uint32_t alloc_size;
86         time_t first_created;
87         time_t last_modified;
88         uint64_t id;
89         uint32_t props;
90 };
91
92 struct oacp_operation {
93         char *remote_address;
94         uint32_t offset;
95         uint32_t length;
96         uint8_t opcode;
97         uint8_t mode;
98         int fd;
99 };
100
101 struct oacp_create_operation {
102         char *remote_address;
103         char *filename;
104         char *uuid;
105         uint32_t size;
106         time_t first_created;
107 };
108
109 static struct object_metadata *selected_object = NULL;
110 static uint64_t object_id = OBJECT_START_ID;
111 static GSList *otp_object_list = NULL;
112 static GSList *otp_char_list = NULL;
113 static guint obj_curr_index;
114 static int adv_handle = 0;
115 static gboolean OACP_indicate = FALSE;
116 static gboolean OLCP_indicate = FALSE;
117 char *directory = NULL;
118 gboolean mutiple_obj_support = false;
119 static gboolean otc_connection_status = FALSE;
120 struct oacp_operation *oacp_read = NULL;
121 struct oacp_create_operation *oacp_create = NULL;
122 unsigned int timeout_id;
123
124 static const gchar otp_introspection_xml[] =
125 "<node name='/'>"
126 "       <interface name='org.projectx.otp_service'>"
127 "               <method name='enable'>"
128 "                       <arg type='s' name='directory'/>"
129 "                       <arg type='i' name='status' direction='out'/>"
130 "               </method>"
131 "               <method name='disable'>"
132 "                       <arg type='i' name='status' direction='out'/>"
133 "               </method>"
134 "     <method name='NewConnection'>"
135 "          <arg type='o' name='object' direction='in'/>"
136 "          <arg type='h' name='fd' direction='in'/>"
137 "     </method>"
138 "       </interface>"
139 "</node>";
140
141 void _bt_otp_deinit_event_receiver(void);
142 void _bt_otp_unregister_interface(void);
143 void update_obj_metadata_charc_value(struct object_metadata *object);
144 void _bt_convert_device_path_to_address(const char *device_path,
145                                                 char *device_address);
146
147 static void delete_all_objects(void)
148 {
149         GSList *tmp = NULL;
150         for (tmp = otp_object_list; tmp != NULL; tmp = tmp->next) {
151                 if (tmp->data) {
152                         struct object_metadata *obj_info = tmp->data;
153                         if (obj_info->name)
154                                 g_free(obj_info->name);
155                         if (obj_info->type)
156                                 g_free(obj_info->type);
157                         otp_object_list = g_slist_delete_link(otp_object_list, tmp->data);
158                 }
159         }
160         g_slist_free(otp_object_list);
161         otp_object_list = NULL;
162 }
163
164 static void delete_all_characterisitc(void)
165 {
166         GSList *tmp = NULL;
167         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
168                 if (tmp->data) {
169                         struct otp_char_info *char_info = tmp->data;
170                         if (char_info->char_path)
171                                 g_free(char_info->char_path);
172                         if (char_info->char_value)
173                                 g_free(char_info->char_value);
174                         otp_char_list = g_slist_delete_link(otp_char_list, tmp->data);
175                 }
176         }
177         g_slist_free(otp_char_list);
178         otp_char_list = NULL;
179 }
180
181 void _bt_otp_exit(void)
182 {
183         int ret;
184         BT_DBG("");
185
186         if (otp_char_list)
187                 delete_all_characterisitc();
188
189         if (otp_object_list)
190                 delete_all_objects();
191
192         ret = bluetooth_gatt_deinit();
193         if (ret != BLUETOOTH_ERROR_NONE)
194                 BT_ERR("Failed to Deinit GATT %d", ret);
195
196         _bt_otp_deinit_event_receiver();
197
198         _bt_otp_unregister_interface();
199
200         /* TODO: Advertising is not getting stopped by this API.
201          * This is because OTP_SERVER_DEINIT dbus call is blocking
202          * BT_SET_ADVERTISING_DATA dbus call. But now advertisment
203          * is stopped because of terminated process logic.
204          */
205         ret = bluetooth_set_advertising(adv_handle, FALSE);
206         if (ret != BLUETOOTH_ERROR_NONE)
207                 BT_ERR("Failed to stop ADV %d", ret);
208
209         if (main_loop != NULL) {
210                 g_main_loop_quit(main_loop);
211         }
212 }
213
214 static void _bt_otp_set_char_value(const char *obj_path,
215                                 const char *value, int value_length)
216 {
217         GSList *tmp = NULL;
218
219         if (!value)
220                 return;
221         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
222                 if (tmp->data) {
223                         struct otp_char_info *char_info = tmp->data;
224                         if (!g_strcmp0(char_info->char_path, obj_path)) {
225                                 char_info->char_value = g_try_realloc(char_info->char_value, value_length);
226                                 if (char_info->char_value) {
227                                         memcpy(char_info->char_value, value, value_length);
228                                         char_info->value_length = value_length;
229                                 }
230                                 return;
231                         }
232                 }
233         }
234         return;
235 }
236
237 int add_new_characteristic(const char *char_uuid, bt_gatt_permission_t perms,
238                 bt_gatt_characteristic_property_t props, char **obj_path)
239 {
240         int ret = BLUETOOTH_ERROR_NONE;
241         struct otp_char_info *char_info = NULL;
242
243         ret = bluetooth_gatt_add_new_characteristic(otp_obj_path,
244                                         char_uuid, perms, props, obj_path);
245         if (ret != BLUETOOTH_ERROR_NONE) {
246                 BT_ERR("Failed to add new char %d", ret);
247                 return ret;
248         }
249
250         char_info = g_new0(struct otp_char_info, 1);
251         char_info->char_path = g_strdup(*obj_path);
252         otp_char_list = g_slist_append(otp_char_list, char_info);
253
254         return ret;
255 }
256
257 static char *_otp_convert_uuid_to_uuid128(const char *uuid)
258 {
259         int len;
260         char *uuid128;
261
262         len = strlen(uuid);
263
264         switch (len) {
265         case 4:
266                 /* UUID 16bits */
267                 uuid128 = g_strdup_printf("0000%s-0000-1000-8000-00805f9b34fb",
268                                                                         uuid);
269                 break;
270
271         case 8:
272                 /* UUID 32bits */
273                 uuid128 = g_strdup_printf("%s-0000-1000-8000-00805f9b34fb",
274                                                                         uuid);
275                 break;
276
277         case 36:
278                 /* UUID 128bits */
279                 uuid128 = strdup(uuid);
280                 break;
281
282         default:
283                 return NULL;
284         }
285
286         return uuid128;
287 }
288
289 int _bt_otp_prepare_ots(void)
290 {
291         BT_DBG("+");
292         int ret = BLUETOOTH_ERROR_NONE;
293         char *service_uuid;
294         char *char_uuid;
295         char *desc_uuid;
296         bt_gatt_characteristic_property_t props;
297         bt_gatt_permission_t perms;
298         char supp_feat[OTP_FEATURE_LENGTH] = { 0x88, 0x00, 0x00, 0x00,
299                                                 0x80, 0x00, 0x00, 0x00 };
300
301         ret = bluetooth_gatt_init();
302         if (ret != BLUETOOTH_ERROR_NONE) {
303                 BT_ERR("Failed to Init GATT %d", ret);
304                 goto fail;
305         }
306
307         service_uuid = _otp_convert_uuid_to_uuid128(OTP_UUID);
308         ret = bluetooth_gatt_add_service(service_uuid, &otp_obj_path);
309         if (ret != BLUETOOTH_ERROR_NONE) {
310                 BT_ERR("Failed to add service %d", ret);
311                 goto fail;
312         }
313
314         /* Characteristic OTP Feature */
315         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
316         perms = BLUETOOTH_GATT_PERMISSION_READ;
317         char_uuid = _otp_convert_uuid_to_uuid128(OTP_FEATURE_UUID);
318         ret = add_new_characteristic(char_uuid, perms, props,
319                                                 &otp_feature_obj_path);
320         if (ret != BLUETOOTH_ERROR_NONE)
321                 goto fail;
322
323         ret = bluetooth_gatt_set_characteristic_value(otp_feature_obj_path,
324                                                 supp_feat, OTP_FEATURE_LENGTH);
325         if (ret != BLUETOOTH_ERROR_NONE) {
326                 BT_ERR("Failed to set char value %d", ret);
327                 return ret;
328         }
329
330         _bt_otp_set_char_value(otp_feature_obj_path, supp_feat,
331                                                 OTP_FEATURE_LENGTH);
332
333         /* Characteristic Object Name */
334         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
335                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
336         perms = BLUETOOTH_GATT_PERMISSION_READ |
337                 BLUETOOTH_GATT_PERMISSION_WRITE;
338         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_NAME_UUID);
339         ret = add_new_characteristic(char_uuid, perms, props,
340                                         &otp_object_name_obj_path);
341         if (ret != BLUETOOTH_ERROR_NONE)
342                 goto fail;
343
344         /* Characteristic Object Type */
345         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
346         perms = BLUETOOTH_GATT_PERMISSION_READ;
347         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_TYPE_UUID);
348         ret = add_new_characteristic(char_uuid, perms, props,
349                                         &otp_object_type_obj_path);
350         if (ret != BLUETOOTH_ERROR_NONE)
351                 goto fail;
352
353         /* Characteristic Object Size */
354         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
355         perms = BLUETOOTH_GATT_PERMISSION_READ;
356         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_SIZE_UUID);
357         ret = add_new_characteristic(char_uuid, perms, props,
358                                         &otp_object_size_obj_path);
359         if (ret != BLUETOOTH_ERROR_NONE)
360                 goto fail;
361
362         /* Characteristic Object First-Created */
363         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
364                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
365         perms = BLUETOOTH_GATT_PERMISSION_READ |
366                 BLUETOOTH_GATT_PERMISSION_WRITE;
367         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_FIRST_CREATED_UUID);
368         ret = add_new_characteristic(char_uuid, perms, props,
369                                         &otp_object_first_created_obj_path);
370         if (ret != BLUETOOTH_ERROR_NONE)
371                 goto fail;
372
373         /* Characteristic Object Last-Modified */
374         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
375                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
376         perms = BLUETOOTH_GATT_PERMISSION_READ |
377                 BLUETOOTH_GATT_PERMISSION_WRITE;
378         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_LAST_MODIFIED_UUID);
379         ret = add_new_characteristic(char_uuid, perms, props,
380                                 &otp_object_last_modified_obj_path);
381         if (ret != BLUETOOTH_ERROR_NONE)
382                 goto fail;
383
384         /* Object ID is mandatory for mutiple object server */
385         if (mutiple_obj_support) {
386                 /* Characteristic Object ID */
387                 props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
388                 perms = BLUETOOTH_GATT_PERMISSION_READ;
389                 char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_ID_UUID);
390                 ret = add_new_characteristic(char_uuid, perms, props,
391                                                 &otp_object_id_obj_path);
392                 if (ret != BLUETOOTH_ERROR_NONE)
393                         goto fail;
394         }
395
396         /* Characteristic Object Properties */
397         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
398         perms = BLUETOOTH_GATT_PERMISSION_READ;
399         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_PROP_UUID);
400         ret = add_new_characteristic(char_uuid, perms, props,
401                                         &otp_object_prop_obj_path);
402         if (ret != BLUETOOTH_ERROR_NONE)
403                 goto fail;
404
405         /* Characteristic OACP */
406         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
407                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
408         perms = BLUETOOTH_GATT_PERMISSION_WRITE;
409         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OACP_UUID);
410         ret = add_new_characteristic(char_uuid, perms, props,
411                                                 &otp_oacp_obj_path);
412         if (ret != BLUETOOTH_ERROR_NONE)
413                 goto fail;
414
415         /* CCCD for OACP */
416         desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
417         perms = BLUETOOTH_GATT_PERMISSION_READ |
418                 BLUETOOTH_GATT_PERMISSION_WRITE;
419         ret = bluetooth_gatt_add_descriptor(otp_oacp_obj_path, desc_uuid,
420                                                 perms, &otp_oacp_desc_obj_path);
421         if (ret != BLUETOOTH_ERROR_NONE) {
422                 BT_ERR("Failed to add new char descriptor %d", ret);
423                 goto fail;
424         }
425
426         /* OLCP Characteristics is not required
427          * for single object server
428          */
429         if (mutiple_obj_support) {
430                 /* Characteristic OLCP */
431                 props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
432                         BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
433                 perms = BLUETOOTH_GATT_PERMISSION_WRITE;
434                 char_uuid = _otp_convert_uuid_to_uuid128(OTP_OLCP_UUID);
435                 ret = add_new_characteristic(char_uuid, perms, props,
436                                                         &otp_olcp_obj_path);
437                 if (ret != BLUETOOTH_ERROR_NONE)
438                         goto fail;
439
440                 /* CCCD for OLCP */
441                 desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
442                 perms = BLUETOOTH_GATT_PERMISSION_READ |
443                         BLUETOOTH_GATT_PERMISSION_WRITE;
444                 ret = bluetooth_gatt_add_descriptor(otp_olcp_obj_path, desc_uuid,
445                                                         perms, &otp_olcp_desc_obj_path);
446                 if (ret != BLUETOOTH_ERROR_NONE) {
447                         BT_ERR("Failed to add new char descriptor %d", ret);
448                         goto fail;
449                 }
450         }
451
452         /* Register service */
453         ret = bluetooth_gatt_register_service(otp_obj_path);
454         if (ret != BLUETOOTH_ERROR_NONE) {
455                 BT_ERR("Failed to register service %d", ret);
456                 goto fail;
457         }
458
459         /* Register Application */
460         ret = bluetooth_gatt_register_application();
461         if (ret != BLUETOOTH_ERROR_NONE) {
462                 BT_ERR("Failed to register application %d", ret);
463                 goto fail;
464         }
465
466         BT_DBG("-");
467         return ret;
468
469 fail:
470         delete_all_characterisitc();
471         return ret;
472 }
473
474 int _bt_otp_set_advertising_data(void)
475 {
476         int ret;
477         BT_DBG("");
478
479         /* OTP UUID */
480         guint8 data[4]  = {0x03, 0x02, 0x25, 0x18};
481         bluetooth_advertising_data_t adv;
482
483         BT_DBG("%x %x %x %x", data[0], data[1], data[2], data[3]);
484         memcpy(adv.data, data, sizeof(data));
485         ret = bluetooth_set_advertising_data(adv_handle, &adv, sizeof(data));
486         if (ret != BLUETOOTH_ERROR_NONE) {
487                 BT_ERR("Failed to set ADV data %d", ret);
488                 return ret;
489         }
490
491         ret = bluetooth_set_advertising(adv_handle, TRUE);
492         if (ret != BLUETOOTH_ERROR_NONE) {
493                 BT_ERR("Failed to set ADV %d", ret);
494                 return ret;
495         }
496
497         return 0;
498 }
499
500 void _bt_otp_start_write_on_fd()
501 {
502         char buf[BT_L2CAP_BUFFER_LEN];
503         int written;
504         int read;
505         int len;
506         FILE *fp;
507         char file_path[BT_FILE_PATH_MAX_LEN] = {0, };
508         int length;
509
510         if (!selected_object) {
511                 BT_DBG("Object not selected");
512                 goto fail;
513         }
514
515         snprintf(file_path, sizeof(file_path), "%s%s",
516                                         directory, selected_object->name);
517         BT_DBG("file_path = [%s]", file_path);
518
519         fp = fopen(file_path, "r");
520         if (!fp) {
521                 BT_DBG("fopen() failed : %s", strerror(errno));
522                 goto fail;
523         }
524
525         BT_DBG("length [%d]", oacp_read->length);
526         length = oacp_read->length;
527
528         while (length > 0) {
529                 if (length < BT_L2CAP_BUFFER_LEN)
530                         len = length;
531                 else
532                         len = BT_L2CAP_BUFFER_LEN;
533
534                 read = fread(buf, 1, len, fp);
535                 written = write(oacp_read->fd, buf, len);
536                 length -= written;
537
538                 BT_DBG("read [%d], written [%d], rem_len [%d]",
539                                                 read, written, length);
540         }
541
542         fclose(fp);
543 fail:
544         g_free(oacp_read->remote_address);
545         g_free(oacp_read);
546         oacp_read = NULL;
547 }
548
549 static void _bt_otp_method(GDBusConnection *connection,
550                 const gchar *sender,
551                 const gchar *object_path,
552                 const gchar *interface_name,
553                 const gchar *method_name,
554                 GVariant *parameters,
555                 GDBusMethodInvocation *invocation,
556                 gpointer user_data)
557 {
558         BT_DBG("+");
559         int status = BLUETOOTH_ERROR_NONE;
560
561         BT_DBG("Method[%s] Object Path[%s] Interface Name[%s]",
562                         method_name, object_path, interface_name);
563
564         if (g_strcmp0(method_name, "enable") == 0) {
565                 GDir *dir = NULL;
566                 GError *error = NULL;
567                 const gchar *filename = NULL;
568                 char absolute_path[ABSOLUTE_PATH_MAX_LENGTH];
569                 GSList *list = NULL, *l = NULL;
570                 struct stat st;
571                 struct object_metadata *object = NULL;
572
573                 g_variant_get(parameters, "(s)", &directory);
574                 BT_DBG("Directory = [%s]", directory);
575
576                 dir = g_dir_open(directory, 0, &error);
577                 if (!dir) {
578                         BT_ERR("Failed to open directory: %s", error->message);
579                         g_error_free(error);
580                         status = BLUETOOTH_ERROR_INVALID_DIRECTORY;
581                         goto fail;
582                 }
583
584                 while ((filename = g_dir_read_name(dir))) {
585                         list = g_slist_append(list, (gpointer) filename);
586                 }
587
588                 g_dir_close(dir);
589
590                 if (!list) {
591                         BT_DBG("No object found in given directory");
592                         status = BLUETOOTH_ERROR_NO_OBJECTS_FOUND;
593                         goto fail;
594                 }
595
596                 if (g_slist_length(list) > 1)
597                         mutiple_obj_support = true;
598
599                 for (l = list; l != NULL; l = l->next) {
600                         if (!l->data) continue;
601                         snprintf(absolute_path, sizeof(absolute_path), "%s%s", directory,
602                                                         (char *)l->data);
603
604                         BT_INFO("filename: %s, absoulte_path: %s",
605                                         (char *)l->data, absolute_path);
606
607                         if (stat(absolute_path, &st) == -1) {
608                                 BT_INFO("stat failed: (%d)\n", errno);
609                                 continue;
610                         }
611
612                         object = g_new0(struct object_metadata, 1);
613
614                         object->name = g_strdup((const gchar *)l->data);
615                         object->type = _otp_convert_uuid_to_uuid128(UNSUPPORTED_OBJECT_TYPE_UUID);
616                         object->first_created = st.st_ctime;
617                         object->last_modified = st.st_ctime;
618                         object->curr_size = (uint32_t) st.st_size;
619                         object->alloc_size = (uint32_t) st.st_size;
620                         object->id = object_id;
621                         object->props = OBJECT_READ;
622
623                         otp_object_list = g_slist_append(otp_object_list,
624                                                                 object);
625
626                         object_id++;
627                 }
628
629                 BT_DBG("preparing");
630                 if (_bt_otp_prepare_ots() != BLUETOOTH_ERROR_NONE) {
631                         BT_ERR("Fail to prepare OTP Proxy");
632                         status = BLUETOOTH_ERROR_INTERNAL;
633                         goto fail;
634                 }
635
636                 /* If single object is supported, make that as
637                  * selected object and update the metadata for the same.
638                  */
639                 if (!mutiple_obj_support) {
640                         BT_INFO("Server supports single object");
641                         selected_object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
642                         if (selected_object)
643                                 update_obj_metadata_charc_value(selected_object);
644                 }
645
646                 BT_DBG("advertsing");
647                 if (_bt_otp_set_advertising_data() != BLUETOOTH_ERROR_NONE) {
648                         BT_ERR("Fail to set advertising data");
649                         status = BLUETOOTH_ERROR_INTERNAL;
650                         goto fail;
651                 }
652 fail:
653                 g_dbus_method_invocation_return_value(invocation,
654                                                 g_variant_new("(i)", status));
655
656         } else if (g_strcmp0(method_name, "disable") == 0) {
657                 g_dbus_method_invocation_return_value(invocation,
658                                                 g_variant_new("(i)", status));
659                 _bt_otp_exit();
660
661         } else if (g_strcmp0(method_name, "NewConnection") == 0) {
662                 int index;
663                 GDBusMessage *msg;
664                 GUnixFDList *fd_list;
665                 char *dev_path;
666                 char address[BT_ADDRESS_STRING_SIZE] = { 0 };
667                 int fd;
668
669                 g_variant_get(parameters, "(oh)", &dev_path, &index);
670
671                 msg = g_dbus_method_invocation_get_message(invocation);
672                 fd_list = g_dbus_message_get_unix_fd_list(msg);
673                 if (fd_list == NULL) {
674                         BT_ERR("fd_list is NULL");
675                         return;
676                 }
677
678                 fd = g_unix_fd_list_get(fd_list, index, NULL);
679                 if (fd == -1) {
680                         BT_ERR("Invalid fd return");
681                         return;
682                 }
683
684                 _bt_convert_device_path_to_address(dev_path, address);
685
686                 BT_INFO("OTC Connected fd: %d, address %s", fd, address);
687                 if (oacp_read) {
688                         oacp_read->fd = fd;
689                         otc_connection_status = TRUE;
690
691                         if (oacp_read->opcode == OACP_READ)
692                                 _bt_otp_start_write_on_fd();
693                 }
694                 g_dbus_method_invocation_return_value(invocation, NULL);
695         }
696         BT_DBG("-");
697 }
698
699 static const GDBusInterfaceVTable otp_method_table = {
700         _bt_otp_method,
701         NULL,
702         NULL,
703 };
704
705 static void _bt_otp_on_bus_acquired(GDBusConnection *connection,
706                                 const gchar *name, gpointer user_data)
707 {
708         guint object_id;
709         GError *error = NULL;
710
711         BT_DBG("+");
712
713         g_conn = connection;
714
715         object_id = g_dbus_connection_register_object(connection,
716                                                 BT_OTP_OBJECT_PATH,
717                                                 otp_node_info->interfaces[0],
718                                                 &otp_method_table,
719                                                 NULL, NULL, &error);
720         if (object_id == 0) {
721                 BT_ERR("Failed to register method table: %s", error->message);
722                 g_error_free(error);
723                 g_dbus_node_info_unref(otp_node_info);
724         }
725
726         BT_DBG("-");
727 }
728
729 static void _bt_otp_on_name_acquired(GDBusConnection *connection,
730                                         const gchar     *name,
731                                         gpointer user_data)
732 {
733         BT_DBG("");
734 }
735
736 static void _bt_otp_on_name_lost(GDBusConnection *connection,
737                                 const gchar     *name,
738                                 gpointer user_data)
739 {
740         BT_DBG("");
741         g_object_unref(g_conn);
742         g_conn = NULL;
743         g_dbus_node_info_unref(otp_node_info);
744         g_bus_unown_name(g_owner_id);
745 }
746
747 int _bt_otp_register_interface(void)
748 {
749         BT_DBG("+");
750         GError *error = NULL;
751         guint owner_id;
752
753         otp_node_info = g_dbus_node_info_new_for_xml(otp_introspection_xml, &error);
754         if (!otp_node_info) {
755                 BT_ERR("Failed to install: %s", error->message);
756                 return BLUETOOTH_ERROR_INTERNAL;
757         }
758
759         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
760                                 BT_OTP_SERVICE_NAME,
761                                 G_BUS_NAME_OWNER_FLAGS_NONE,
762                                 _bt_otp_on_bus_acquired,
763                                 _bt_otp_on_name_acquired,
764                                 _bt_otp_on_name_lost,
765                                 NULL, NULL);
766         g_owner_id = owner_id;
767         BT_DBG("owner_id is [%d]\n", owner_id);
768
769         BT_DBG("-");
770         return BLUETOOTH_ERROR_NONE;
771 }
772
773 void _bt_otp_unregister_interface(void)
774 {
775         BT_DBG("+");
776
777         g_object_unref(g_conn);
778         g_conn = NULL;
779         g_dbus_node_info_unref(otp_node_info);
780         g_bus_unown_name(g_owner_id);
781
782         BT_DBG("-");
783         return;
784 }
785
786 void _bt_convert_device_path_to_address(const char *device_path,
787                                                 char *device_address)
788 {
789         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
790         char *dev_addr;
791
792         dev_addr = strstr(device_path, "dev_");
793         if (dev_addr != NULL) {
794                 char *pos = NULL;
795                 dev_addr += 4;
796                 g_strlcpy(address, dev_addr, sizeof(address));
797
798                 while ((pos = strchr(address, '_')) != NULL)
799                         *pos = ':';
800
801                 g_strlcpy(device_address, address, BT_ADDRESS_STRING_SIZE);
802         }
803 }
804
805 static char *__bt_extract_device_path(GVariantIter *iter, char *address)
806 {
807         char *object_path = NULL;
808         char device_address[BT_ADDRESS_STRING_SIZE] = { 0 };
809
810         /* Parse the signature: oa{sa{sv}}} */
811         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path,
812                         NULL)) {
813                 if (!object_path) {
814                         BT_ERR("Unable to get object path");
815                         return NULL;
816                 }
817                 _bt_convert_device_path_to_address(object_path, device_address);
818                 if (g_strcmp0(address, device_address) == 0)
819                         return g_strdup(object_path);
820
821         }
822
823         BT_ERR("Unable to get object path");
824         return NULL;
825 }
826
827 char *_bt_otp_get_device_object_path(char *address)
828 {
829         GError *err = NULL;
830         GDBusProxy *proxy = NULL;
831         GVariant *result = NULL;
832         GVariantIter *iter = NULL;
833         char *object_path = NULL;
834
835         proxy =  g_dbus_proxy_new_sync(conn,
836                         G_DBUS_PROXY_FLAGS_NONE, NULL,
837                         BT_BLUEZ_NAME,
838                         BT_MANAGER_PATH,
839                         BT_MANAGER_INTERFACE,
840                         NULL, &err);
841
842         if (!proxy) {
843                 BT_ERR("Unable to create proxy: %s", err->message);
844                 goto fail;
845         }
846
847         result = g_dbus_proxy_call_sync(proxy, "GetManagedObjects", NULL,
848                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
849         if (!result) {
850                 if (err != NULL)
851                         BT_ERR("Fail to get GetManagedObjects (Error: %s)", err->message);
852                 else
853                         BT_ERR("Fail to get GetManagedObjects");
854
855                 goto fail;
856         }
857
858         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
859         object_path = __bt_extract_device_path(iter, address);
860
861         g_variant_unref(result);
862         g_variant_iter_free(iter);
863
864 fail:
865         if (err)
866                 g_clear_error(&err);
867
868         if (proxy)
869                 g_object_unref(proxy);
870
871         return object_path;
872 }
873
874 int _bt_otp_open_otc_and_listen(char *address)
875 {
876         char *object_path;
877         GDBusProxy *device_proxy = NULL;
878         GVariant *result = NULL;
879         GError *error = NULL;
880         int ret = BLUETOOTH_ERROR_NONE;
881
882         object_path = _bt_otp_get_device_object_path(address);
883         if (object_path == NULL) {
884                 ret = BLUETOOTH_ERROR_NOT_PAIRED;
885                 goto fail;
886         }
887
888         device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
889                                         NULL, BT_BLUEZ_NAME, object_path,
890                                         BT_DEVICE_INTERFACE,  NULL, NULL);
891         if (device_proxy == NULL) {
892                 ret = BLUETOOTH_ERROR_INTERNAL;
893                 goto fail;
894         }
895
896
897         result = g_dbus_proxy_call_sync(device_proxy, "ListenOtc",
898                                 NULL,
899                                 G_DBUS_CALL_FLAGS_NONE,
900                                 -1,
901                                 NULL,
902                                 &error);
903         if (result == NULL) {
904                 if (error != NULL) {
905                         BT_ERR("Error occured in Proxy call [%s]\n", error->message);
906                         g_error_free(error);
907                 }
908                 ret = BLUETOOTH_ERROR_INTERNAL;
909         }
910 fail:
911         if (object_path)
912                 g_free(object_path);
913         if (result)
914                 g_variant_unref(result);
915         if (device_proxy)
916                 g_object_unref(device_proxy);
917         return ret;
918 }
919
920 static bool __bt_oacp_create_timeout_cb(gpointer user_data)
921 {
922         if (oacp_create) {
923                 g_free(oacp_create->uuid);
924                 g_free(oacp_create);
925                 oacp_create = NULL;
926         }
927         return TRUE;
928 }
929
930 int _bt_otp_oacp_write_cb(char *value, int len, int offset,
931                                                         char *remote_addr, struct indicate_info *info)
932 {
933         int ret = OACP_SUCCESS;
934         int app_err = BLUETOOTH_ERROR_NONE;
935         int opcode = value[0];
936         uint32_t object_offset, length, object_size;
937         char *uuid;
938
939         BT_INFO("OACP Opcode 0x%d", opcode);
940
941         if (!otp_object_list) {
942                 ret = OACP_INVALID_OBJ;
943                 goto fail;
944         }
945
946         switch (opcode) {
947         case OACP_CREATE:
948                 BT_INFO("OACP_CREATE");
949                 object_size = (uint32_t)(value[4] & 0xFF) << 24 |
950                                 (uint32_t)(value[3] & 0xFF) << 16 |
951                                 (uint32_t)(value[2] & 0xFF) << 8  |
952                                 (uint32_t)(value[1] & 0xFF);
953
954                 uuid = g_strndup(value + 5, len - 5);
955                 BT_INFO("Size = %lu, UUID = %s", object_size, uuid);
956
957                 if (oacp_create) {
958                         /* Create operation already going on. */
959                         ret = OACP_OPERATION_FAILED;
960                         goto fail;
961                 }
962                 oacp_create = g_malloc0(sizeof(struct oacp_create_operation));
963                 oacp_create->size = object_size;
964                 oacp_create->uuid = g_strdup(uuid);
965                 if (timeout_id > 0)
966                         g_source_remove(timeout_id);
967                 timeout_id = g_timeout_add(BT_OACP_CREATE_MAX_TIMEOUT,
968                         (GSourceFunc)__bt_oacp_create_timeout_cb, NULL);
969                 g_free(uuid);
970                 ret = OACP_SUCCESS;
971                 break;
972         case OACP_DELETE:
973                 ret = OACP_OPCODE_NOT_SUPPORTED;
974                 break;
975         case OACP_CALC_CHECKSUM:
976                 ret = OACP_OPCODE_NOT_SUPPORTED;
977                 break;
978         case OACP_EXECUTE:
979                 ret = OACP_OPCODE_NOT_SUPPORTED;
980                 break;
981         case OACP_READ:
982                 object_offset = (uint32_t)(value[4] & 0xFF) << 24 |
983                                 (uint32_t)(value[3] & 0xFF) << 16 |
984                                 (uint32_t)(value[2] & 0xFF) << 8  |
985                                 (uint32_t)(value[1] & 0xFF);
986                 length = (uint32_t)(value[8] & 0xFF) << 24 |
987                         (uint32_t)(value[7] & 0xFF) << 16 |
988                         (uint32_t)(value[6] & 0xFF) << 8  |
989                         (uint32_t)(value[5] & 0xFF);
990
991                 BT_INFO("Offset = %lu, Length = %lu", object_offset, length);
992
993                 if (oacp_read && otc_connection_status) {
994                         /* Read operation already going on. */
995                         ret = OACP_OBJECT_LOCKED;
996                         goto fail;
997                 }
998                 oacp_read = g_malloc0(sizeof(struct oacp_operation));
999                 oacp_read->offset = object_offset;
1000                 oacp_read->length = length;
1001                 oacp_read->remote_address = g_strdup(remote_addr);
1002                 oacp_read->opcode = OACP_READ;
1003
1004                 app_err = _bt_otp_open_otc_and_listen(remote_addr);
1005                 if (app_err != BLUETOOTH_ERROR_NONE) {
1006                         ret = OACP_OPERATION_FAILED;
1007                         g_free(oacp_read->remote_address);
1008                         g_free(oacp_read);
1009                         oacp_read = NULL;
1010                         goto fail;
1011                 }
1012                 ret = OACP_SUCCESS;
1013                 break;
1014         case OACP_WRITE:
1015                 ret = OACP_OPCODE_NOT_SUPPORTED;
1016                 break;
1017         case OACP_ABORT:
1018                 ret = OACP_OPCODE_NOT_SUPPORTED;
1019                 break;
1020         default:
1021                 ret = OACP_OPCODE_NOT_SUPPORTED;
1022                 break;
1023         }
1024 fail:
1025         info->resp_opcode = OACP_RESPONSE;
1026         info->req_opcode = opcode;
1027         info->result_code = ret;
1028         info->resp_param = NULL;
1029         return app_err;
1030 }
1031
1032 void convert_to_hex(struct object_metadata *object, char *type, char *value)
1033 {
1034         struct tm fc_tm;
1035
1036         BT_DBG("type : %s", type);
1037
1038         memset(value, 0, 8);
1039
1040         if (!g_strcmp0(type, "size")) {
1041
1042                 value[3] = (object->curr_size >> 24) & 0xFF;
1043                 value[2] = (object->curr_size >> 16) & 0xFF;
1044                 value[1] = (object->curr_size >> 8) & 0xFF;
1045                 value[0] = object->curr_size & 0xFF;
1046
1047                 value[7] = (object->alloc_size >> 24) & 0xFF;
1048                 value[6] = (object->alloc_size >> 16) & 0xFF;
1049                 value[5] = (object->alloc_size >> 8) & 0xFF;
1050                 value[4] = object->alloc_size & 0xFF;
1051
1052         } else if (!g_strcmp0(type, "date")) {
1053
1054                 localtime_r(&(object->first_created), &fc_tm);
1055
1056                 value[1] = ((fc_tm.tm_year+1900) >> 8) & 0xFF;
1057                 value[0] = (fc_tm.tm_year+1900) & 0xFF;
1058                 value[2] = (fc_tm.tm_mon+1) & 0xFF;
1059                 value[3] = fc_tm.tm_mday & 0xFF;
1060                 value[4] = fc_tm.tm_hour & 0xFF;
1061                 value[5] = fc_tm.tm_min & 0xFF;
1062                 value[6] = fc_tm.tm_sec & 0xFF;
1063
1064         } else if (!g_strcmp0(type, "id")) {
1065
1066                 value[5] = (object->id >> 48) & 0xFF;
1067                 value[4] = (object->id >> 32) & 0xFF;
1068                 value[3] = (object->id >> 24) & 0xFF;
1069                 value[2] = (object->id >> 16) & 0xFF;
1070                 value[1] = (object->id >> 8) & 0xFF;
1071                 value[0] = object->id & 0xFF;
1072
1073         } else if (!g_strcmp0(type, "props")) {
1074                 value[3] = (object->props >> 24) & 0xFF;
1075                 value[2] = (object->props >> 16) & 0xFF;
1076                 value[1] = (object->props >> 8) & 0xFF;
1077                 value[0] = object->props & 0xFF;
1078         }
1079 }
1080
1081 void update_obj_metadata_charc_value(struct object_metadata *object)
1082 {
1083         /* Value can be of maximum eight bytes */
1084         char value[8];
1085
1086         _bt_otp_set_char_value(otp_object_name_obj_path, object->name,
1087                                                         strlen(object->name));
1088         _bt_otp_set_char_value(otp_object_type_obj_path, object->type,
1089                                                         strlen(object->type));
1090
1091         convert_to_hex(object, "size", value);
1092         _bt_otp_set_char_value(otp_object_size_obj_path, value, 8);
1093
1094         convert_to_hex(object, "date", value);
1095         _bt_otp_set_char_value(otp_object_first_created_obj_path, value, 7);
1096         _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, 7);
1097
1098         /* Object ID is optonal for single object server */
1099         if (mutiple_obj_support) {
1100                 convert_to_hex(object, "id", value);
1101                 _bt_otp_set_char_value(otp_object_id_obj_path, value, 6);
1102         }
1103
1104         convert_to_hex(object, "props", value);
1105         _bt_otp_set_char_value(otp_object_prop_obj_path, value, 4);
1106 }
1107
1108 struct object_metadata *_bt_otp_client_find_object(GSList *list, uint64_t id, guint *index)
1109 {
1110         GSList *l;
1111         struct object_metadata *info;
1112
1113         for (l = list; l; l = g_slist_next(l)) {
1114                 (*index)++;
1115                 info = l->data;
1116
1117                 if (info && (info->id == id))
1118                         return info;
1119         }
1120         return NULL;
1121 }
1122
1123 int _bt_otp_olcp_write_cb(char *value, int len, int offset,
1124                                         struct indicate_info *info)
1125 {
1126         int ret = OLCP_SUCCESS;
1127         int opcode = value[0];
1128         struct object_metadata *object;
1129         uint64_t object_id;
1130         guint index = 0;
1131
1132         BT_INFO("OLCP Opcode 0x%d", opcode);
1133
1134         if (!otp_object_list) {
1135                 ret = OLCP_NO_OBJ;
1136                 goto fail;
1137         }
1138
1139         switch (opcode) {
1140         case OLCP_FIRST:
1141                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
1142                 if (!object) {
1143                         ret = OLCP_OUT_OF_BOUNDS;
1144                         goto fail;
1145                 }
1146                 update_obj_metadata_charc_value(object);
1147                 selected_object = object;
1148                 obj_curr_index = 0;
1149                 break;
1150         case OLCP_LAST:
1151                 len = g_slist_length(otp_object_list);
1152                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, len-1);
1153                 if (!object) {
1154                         ret = OLCP_OUT_OF_BOUNDS;
1155                         goto fail;
1156                 }
1157                 update_obj_metadata_charc_value(object);
1158                 selected_object = object;
1159                 obj_curr_index = len-1;
1160                 break;
1161         case OLCP_PREVIOUS:
1162                 if (obj_curr_index == 0) {
1163                         ret = OLCP_OUT_OF_BOUNDS;
1164                         goto fail;
1165                 }
1166                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, obj_curr_index-1);
1167                 if (!object) {
1168                         ret = OLCP_OUT_OF_BOUNDS;
1169                         goto fail;
1170                 }
1171                 update_obj_metadata_charc_value(object);
1172                 selected_object = object;
1173                 obj_curr_index -= 1;
1174                 break;
1175         case OLCP_NEXT:
1176                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, obj_curr_index+1);
1177                 if (!object) {
1178                         ret = OLCP_OUT_OF_BOUNDS;
1179                         goto fail;
1180                 }
1181                 update_obj_metadata_charc_value(object);
1182                 selected_object = object;
1183                 obj_curr_index += 1;
1184                 break;
1185         case OLCP_GOTO:
1186                 object_id = (uint64_t)(value[6] & 0xFF) << 40 |
1187                                 (uint64_t)(value[5] & 0xFF) << 32 |
1188                                 (uint64_t)(value[4] & 0xFF) << 24 |
1189                                 (uint64_t)(value[3] & 0xFF) << 16 |
1190                                 (uint64_t)(value[2] & 0xFF) << 8  |
1191                                 (uint64_t)(value[1] & 0xFF);
1192                 BT_INFO("Object ID [%llu]", object_id);
1193                 if (selected_object && selected_object->id == object_id)
1194                         goto fail;
1195
1196                 object = _bt_otp_client_find_object(otp_object_list, object_id, &index);
1197                 if (!object) {
1198                         ret = OLCP_OJECT_ID_NOT_FOUND;
1199                         goto fail;
1200                 }
1201                 update_obj_metadata_charc_value(object);
1202                 selected_object = object;
1203                 obj_curr_index = index - 1;
1204                 break;
1205         case OLCP_ORDER:
1206         case OLCP_REQ_NO_OBJ:
1207         case OLCP_CLEAR_MARKING:
1208         default:
1209                 ret = OLCP_OPCODE_NOT_SUPPORTED;
1210                 break;
1211         }
1212 fail:
1213         info->resp_opcode = OLCP_RESPONSE;
1214         info->req_opcode = opcode;
1215         info->result_code = ret;
1216         info->resp_param = NULL;
1217         return BLUETOOTH_ERROR_NONE;
1218 }
1219
1220 int _bt_otp_obj_name_cb(char *value, int len)
1221 {
1222         int ret = BLUETOOTH_ERROR_NONE;
1223
1224         struct object_metadata *object = NULL;
1225         struct stat st;
1226         char *file_path;
1227         char *filename;
1228         int length;
1229         FILE *fp = NULL;
1230
1231         filename = g_strndup(value, len);
1232         length = len + strlen(BT_OTP_BASE_DIR_PATH) + 1;
1233         file_path = malloc(length);
1234
1235         snprintf(file_path, length, "%s%s",
1236                         BT_OTP_BASE_DIR_PATH, filename);
1237         BT_DBG("file_path = [%s]", file_path);
1238
1239         fp = fopen(file_path, "a");
1240         if (!fp) {
1241                 BT_DBG("fopen() failed : %s", strerror(errno));
1242                 ret = BLUETOOTH_ERROR_INTERNAL;
1243                 goto fail;
1244         }
1245
1246         if (stat(file_path, &st) == -1) {
1247                 BT_INFO("stat failed: (%d)\n", errno);
1248                 ret = BLUETOOTH_ERROR_INTERNAL;
1249                 goto fail;
1250         }
1251
1252         object = g_new0(struct object_metadata, 1);
1253
1254         object->name = g_strdup(filename);
1255         object->type = _otp_convert_uuid_to_uuid128(oacp_create->uuid);
1256         object->first_created = st.st_ctime;
1257         object->last_modified = st.st_ctime;
1258         object->curr_size = (uint32_t)st.st_size;
1259         object->alloc_size = oacp_create->size;
1260         object->id = object_id;
1261         object->props = OBJECT_READ | OBJECT_WRITE;
1262
1263         otp_object_list = g_slist_append(otp_object_list,
1264                                                 object);
1265
1266         update_obj_metadata_charc_value(object);
1267         selected_object = object;
1268         obj_curr_index = g_slist_length(otp_object_list) - 1;
1269         object_id++;
1270 fail:
1271         if (fp)
1272                 fclose(fp);
1273         g_free(filename);
1274         free(file_path);
1275         g_free(oacp_create->uuid);
1276         g_free(oacp_create);
1277         oacp_create = NULL;
1278
1279         return ret;
1280 }
1281
1282 static struct otp_char_info *otp_get_char_value(const char *path)
1283 {
1284         GSList *tmp = NULL;
1285
1286         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
1287                 if (tmp->data) {
1288                         struct otp_char_info *char_info = tmp->data;
1289                         if (!g_strcmp0(char_info->char_path, path))
1290                                 return char_info;
1291                 }
1292         }
1293
1294         return NULL;
1295 }
1296
1297 int _bt_otp_read_cb(const char *obj_path, char **value, int *len)
1298 {
1299         struct otp_char_info *info = NULL;
1300
1301         if (!obj_path) {
1302                 BT_ERR("Wrong Obj path");
1303                 return BLUETOOTH_ERROR_INTERNAL;
1304         }
1305
1306         if (g_strcmp0(obj_path, otp_feature_obj_path)) {
1307                 if (!selected_object) {
1308                         return BLUETOOTH_ERROR_OBJECT_NOT_SELECTED;
1309                 }
1310         }
1311
1312         info = otp_get_char_value(obj_path);
1313         if (info) {
1314                 if (info->char_value == NULL || info->value_length == 0)
1315                         return BLUETOOTH_ERROR_INTERNAL;
1316
1317                 *len = info->value_length;
1318                 *value = (char *)malloc(sizeof(char)*(*len));
1319                 memcpy(*value, info->char_value, *len);
1320
1321                 return BLUETOOTH_ERROR_NONE;
1322         } else {
1323                 return BLUETOOTH_ERROR_INTERNAL;
1324         }
1325 }
1326
1327 static void _otp_convert_address_to_hex(bluetooth_device_address_t *addr_hex,
1328                                                         const char *addr_str)
1329 {
1330         int i = 0;
1331         unsigned int addr[BLUETOOTH_ADDRESS_LENGTH] = { 0, };
1332
1333         if (addr_str == NULL || addr_str[0] == '\0')
1334                 return;
1335
1336         i = sscanf(addr_str, "%X:%X:%X:%X:%X:%X", &addr[0], &addr[1],
1337                                 &addr[2], &addr[3], &addr[4], &addr[5]);
1338         if (i != BLUETOOTH_ADDRESS_LENGTH)
1339                 BT_ERR("Invalid format string - [%s]", addr_str);
1340
1341         for (i = 0; i < BLUETOOTH_ADDRESS_LENGTH; i++)
1342                 addr_hex->addr[i] = (unsigned char)addr[i];
1343 }
1344
1345 static void _bt_otp_send_indication(const char *obj_path,
1346                                 struct indicate_info *info,
1347                                 bluetooth_device_address_t *remote_address)
1348 {
1349         int ret = BLUETOOTH_ERROR_NONE;
1350         char value[7] = {0x00};
1351
1352         BT_DBG("");
1353
1354         value[0] = info->resp_opcode & 0xFF;
1355         value[1] = info->req_opcode & 0xFF;
1356         value[2] = info->result_code & 0xFF;
1357         if (info->resp_param) {
1358                 value[6] = (info->resp_param[3] >> 24) & 0xFF;
1359                 value[5] = (info->resp_param[4] >> 16) & 0xFF;
1360                 value[4] = (info->resp_param[5] >> 8) & 0xFF;
1361                 value[3] = info->resp_param[6] & 0xFF;
1362         }
1363
1364         BT_DBG("Opcode: %d", value[1]);
1365
1366         /* Store the status value */
1367         _bt_otp_set_char_value(obj_path, value, 7);
1368
1369         /* Send indication */
1370         ret = bluetooth_gatt_server_set_notification(obj_path, remote_address);
1371         if (ret != BLUETOOTH_ERROR_NONE) {
1372                 BT_ERR("_bt_otp_send_control_point_indication failed");
1373                 return;
1374         }
1375         ret = bluetooth_gatt_update_characteristic(obj_path, value, 7);
1376         if (ret != BLUETOOTH_ERROR_NONE) {
1377                 BT_ERR("_bt_otp_send_control_point_indication failed");
1378                 return;
1379         }
1380 }
1381
1382 void _bt_otp_gatt_char_property_changed_event(GVariant *msg,
1383                                 const char *path)
1384 {
1385         int result = BLUETOOTH_ERROR_NONE;
1386         GVariantIter value_iter;
1387         const char *property = NULL;
1388         const char *char_path = NULL;
1389         const char *svc_handle = NULL;
1390         GVariant *var = NULL;
1391         GVariant *val = NULL;
1392         g_variant_iter_init(&value_iter, msg);
1393
1394         while ((g_variant_iter_loop(&value_iter, "{sv}", &property, &var))) {
1395
1396                 if (property == NULL) {
1397                         BT_ERR("Property NULL");
1398                         return;
1399                 }
1400
1401                 if (!g_strcmp0(property, "WriteValue")) {
1402                         int len = 0;
1403                         BT_INFO("WriteValue");
1404                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1405
1406                         if (var) {
1407                                 bluetooth_device_address_t addr_hex = { {0,} };
1408                                 gchar *addr = NULL;
1409                                 guint8 req_id = 1;
1410                                 guint16 offset = 0;
1411                                 char *value = NULL;
1412                                 struct indicate_info info;
1413                                 g_variant_get(var, "(&s&s&syq@ay)",
1414                                                 &char_path, &svc_handle,
1415                                                 &addr, &req_id, &offset, &val);
1416
1417                                 len = g_variant_get_size(val);
1418
1419                                 BT_DBG("Len = %d, BT_ADDR = %s", len, addr);
1420
1421                                 value = (char *) g_variant_get_data(val);
1422                                 _otp_convert_address_to_hex(&addr_hex, addr);
1423
1424                                 if (len != 0) {
1425                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1426                                                 result = _bt_otp_oacp_write_cb(value, len, offset, addr, &info);
1427                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1428                                                 result = _bt_otp_olcp_write_cb(value, len, offset, &info);
1429                                         } else if (!g_strcmp0(char_path, otp_object_name_obj_path)) {
1430                                                 if (oacp_create) {
1431                                                         /* OACP_CREATE is ongoing */
1432                                                         result = _bt_otp_obj_name_cb(value, len);
1433                                                 } else {
1434                                                         /* Dont permit writting object name except while creating object.
1435                                                          * As this is directly pointing local objects.
1436                                                          */
1437                                                         result = BLUETOOTH_ERROR_WRITE_REQUEST_REJECTED;
1438                                                 }
1439                                         } else if (!g_strcmp0(char_path, otp_object_first_created_obj_path)) {
1440                                                 _bt_otp_set_char_value(otp_object_first_created_obj_path, value, len);
1441                                         } else if (!g_strcmp0(char_path, otp_object_last_modified_obj_path)) {
1442                                                 _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, len);
1443                                         } else {
1444                                                 BT_ERR("Wrong Object Path %s", char_path);
1445                                                 result = BLUETOOTH_ERROR_INTERNAL;
1446                                         }
1447                                         bluetooth_gatt_send_response(req_id,
1448                                         BLUETOOTH_GATT_ATT_REQUEST_TYPE_WRITE,
1449                                                         result, 0, NULL, 0);
1450
1451                                         /* Send indication for CPs */
1452                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1453                                                 if (OACP_indicate) {
1454                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1455                                                 }
1456                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1457                                                 if (OLCP_indicate) {
1458                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1459                                                 }
1460                                         }
1461                                 } else {
1462                                         BT_ERR("Array Len 0");
1463                                 }
1464                         } else {
1465                                 BT_ERR("var==NULL");
1466                         }
1467                 } else if (!g_strcmp0(property, "ReadValue")) {
1468                         gchar *addr = NULL;
1469                         guint8 req_id = 1;
1470                         guint16 offset = 0;
1471                         char *value = NULL;
1472                         int len = 0;
1473                         result = BLUETOOTH_ERROR_NONE;
1474
1475                         BT_INFO("ReadValue");
1476                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1477
1478                         g_variant_get(var, "(&s&s&syq)", &char_path,
1479                                         &svc_handle, &addr, &req_id, &offset);
1480
1481                         result = _bt_otp_read_cb(char_path, &value, &len);
1482
1483                         if (result != BLUETOOTH_ERROR_NONE) {
1484                                 BT_ERR("ReadValue failed %s", char_path);
1485                                 bluetooth_gatt_send_response(req_id,
1486                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1487                                                 result, offset, NULL, 0);
1488                         } else {
1489                                 bluetooth_gatt_send_response(req_id,
1490                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1491                                                 result, offset, value, len);
1492                                 if (value)
1493                                         g_free(value);
1494                         }
1495                 } else if (!g_strcmp0(property, "NotificationStateChanged")) {
1496                         gboolean indicate = FALSE;
1497
1498                         g_variant_get(var, "(&s&sb)", &char_path,
1499                                                 &svc_handle, &indicate);
1500
1501                         BT_INFO("%s : [%s]", property,
1502                                 indicate ? "StartNotify" : "StopNotify");
1503                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1504
1505                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1506                                 OACP_indicate = indicate;
1507                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1508                                 OLCP_indicate = indicate;
1509                         }
1510                 }
1511         }
1512         return;
1513 }
1514
1515 void _bt_otp_property_event_filter(GDBusConnection *connection,
1516                                         const gchar *sender_name,
1517                                         const gchar *object_path,
1518                                         const gchar *interface_name,
1519                                         const gchar *signal_name,
1520                                         GVariant *parameters,
1521                                         gpointer user_data)
1522 {
1523         GVariant *value;
1524
1525         if (signal_name == NULL) {
1526                 BT_ERR("Wrong Signal");
1527                 return;
1528         }
1529
1530         if (g_strcmp0(signal_name, PROPERTIES_CHANGED) == 0) {
1531
1532                 g_variant_get(parameters, "(@a{sv}@as)", &value, NULL);
1533                 _bt_otp_gatt_char_property_changed_event(value, object_path);
1534         }
1535 }
1536
1537 void _bt_otp_adapter_event_filter(GDBusConnection *connection,
1538                                         const gchar *sender_name,
1539                                         const gchar *object_path,
1540                                         const gchar *interface_name,
1541                                         const gchar *signal_name,
1542                                         GVariant *parameters,
1543                                         gpointer user_data)
1544 {
1545         if (signal_name == NULL) {
1546                 BT_ERR("Wrong Signal");
1547                 return;
1548         }
1549
1550         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
1551
1552         if (g_strcmp0(interface_name, BT_OTP_INTERFACE_NAME) == 0) {
1553                 if (strcasecmp(signal_name, BLE_DISABLED) == 0) {
1554                         _bt_otp_exit();
1555                 }
1556         }
1557 }
1558
1559 void _bt_otc_disconnected_cb(GDBusConnection *connection,
1560                                         const gchar *sender_name,
1561                                         const gchar *object_path,
1562                                         const gchar *interface_name,
1563                                         const gchar *signal_name,
1564                                         GVariant *parameters,
1565                                         gpointer user_data)
1566 {
1567         if (signal_name == NULL) {
1568                 BT_ERR("Wrong Signal");
1569                 return;
1570         }
1571
1572         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
1573
1574         if (g_strcmp0(interface_name, BT_DEVICE_INTERFACE) == 0) {
1575                 if (strcasecmp(signal_name, OTC_DISCONNECTED) == 0) {
1576                         BT_DBG("OTC Channel Disconnected dev_path[%s]",
1577                                                                                         object_path);
1578                         otc_connection_status = FALSE;
1579                         if (oacp_read) {
1580                                 g_free(oacp_read->remote_address);
1581                                 g_free(oacp_read);
1582                         }
1583                 }
1584         }
1585 }
1586
1587 int _bt_otp_init_event_receiver()
1588 {
1589         BT_DBG("+");
1590         GError *error = NULL;
1591
1592         if (conn == NULL) {
1593                 conn =  g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
1594                 if (error != NULL) {
1595                         BT_ERR("ERROR: Can't get on system bus [%s]",
1596                                                         error->message);
1597                         g_clear_error(&error);
1598                 }
1599         }
1600
1601         property_sub_id = g_dbus_connection_signal_subscribe(conn,
1602                                 NULL,
1603                                 BT_OTP_INTERFACE_NAME,
1604                                 PROPERTIES_CHANGED,
1605                                 BT_OTP_OBJECT_PATH, NULL, 0,
1606                                 _bt_otp_property_event_filter,
1607                                 NULL, NULL);
1608
1609         adapter_sub_id = g_dbus_connection_signal_subscribe(conn,
1610                                 NULL,
1611                                 BT_OTP_INTERFACE_NAME,
1612                                 BLE_DISABLED,
1613                                 BT_OTP_OBJECT_PATH, NULL, 0,
1614                                 _bt_otp_adapter_event_filter,
1615                                 NULL, NULL);
1616
1617         device_sub_id = g_dbus_connection_signal_subscribe(conn,
1618                                         NULL, BT_DEVICE_INTERFACE,
1619                                         OTC_DISCONNECTED, NULL, NULL, 0,
1620                                         _bt_otc_disconnected_cb,
1621                                         NULL, NULL);
1622
1623         BT_DBG("-");
1624         return 0;
1625 }
1626
1627 void _bt_otp_deinit_event_receiver(void)
1628 {
1629         BT_DBG("+");
1630
1631         g_dbus_connection_signal_unsubscribe(conn, property_sub_id);
1632         g_dbus_connection_signal_unsubscribe(conn, adapter_sub_id);
1633         g_dbus_connection_signal_unsubscribe(conn, device_sub_id);
1634         conn = NULL;
1635
1636         BT_DBG("-");
1637 }
1638
1639 static void _bt_otp_sig_handler(int sig)
1640 {
1641         BT_DBG("+");
1642         switch (sig) {
1643         case SIGTERM:
1644                 BT_DBG("caught signal - sigterm\n");
1645                 break;
1646         case SIGINT:
1647                 BT_DBG("caught signal - sigint\n");
1648                 break;
1649         case SIGKILL:
1650                 BT_DBG("caught signal - sigkill\n");
1651                 break;
1652         default:
1653                 BT_DBG("caught signal %d and ignored\n", sig);
1654                 break;
1655         }
1656         BT_DBG("-");
1657 }
1658
1659 /* OTP Service Main loop */
1660 int main(void)
1661 {
1662         struct sigaction sa;
1663         BT_ERR("Starting the bt-otp daemon");
1664
1665         memset(&sa, 0, sizeof(sa));
1666         sa.sa_handler = _bt_otp_sig_handler;
1667         sa.sa_flags = SA_SIGINFO;
1668         sigaction(SIGINT, &sa, NULL);
1669         sigaction(SIGTERM, &sa, NULL);
1670         sigaction(SIGKILL, &sa, NULL);
1671
1672         if (_bt_otp_register_interface() != BLUETOOTH_ERROR_NONE) {
1673                 BT_ERR("Fail to register otp service");
1674                 return -4;
1675         }
1676
1677         if (_bt_otp_init_event_receiver() != BLUETOOTH_ERROR_NONE) {
1678                 BT_ERR("Fail to init event reciever");
1679                 return -5;
1680         }
1681
1682         main_loop = g_main_loop_new(NULL, FALSE);
1683
1684         g_main_loop_run(main_loop);
1685
1686         BT_DBG("g_main_loop_quit called!");
1687
1688         if (main_loop != NULL) {
1689                 g_main_loop_unref(main_loop);
1690         }
1691
1692         return 0;
1693 }