[GATT Client] Delivery ATT error code to higher layer
[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 #include <dlfcn.h>
31 #include <arpa/inet.h>
32
33 #include "bt-otpserver.h"
34 #include "bluetooth-api.h"
35
36
37 #undef LOG_TAG
38 #define LOG_TAG "BLUETOOTH_OTP"
39
40 #define BT_INFO(fmt, arg...) SLOGI(fmt, ##arg)
41 #define BT_ERR(fmt, arg...) SLOGE(fmt, ##arg)
42 #define BT_DBG(fmt, arg...) SLOGD(fmt, ##arg)
43
44 /* OTP object paths */
45 char *otp_obj_path = NULL;
46 char *otp_feature_obj_path = NULL;
47 char *otp_object_name_obj_path = NULL;
48 char *otp_object_type_obj_path = NULL;
49 char *otp_object_size_obj_path = NULL;
50 char *otp_object_first_created_obj_path = NULL;
51 char *otp_object_last_modified_obj_path = NULL;
52 char *otp_object_id_obj_path = NULL;
53 char *otp_object_prop_obj_path = NULL;
54 char *otp_oacp_obj_path = NULL;
55 char *otp_olcp_obj_path = NULL;
56 char *otp_oacp_desc_obj_path = NULL;
57 char *otp_olcp_desc_obj_path = NULL;
58
59 static GMainLoop *main_loop;
60 GDBusNodeInfo *otp_node_info = NULL;
61 static GDBusConnection *conn;
62 static GDBusConnection *g_conn;
63
64 static int property_sub_id = -1;
65 static int adapter_sub_id = -1;
66 static int device_sub_id = -1;
67 static guint g_owner_id = 0;
68 static guint server_watch_id = 0;
69
70 struct otp_char_info {
71         gchar *char_path;
72         gchar *char_value;
73         int value_length;
74 };
75
76 struct indicate_info {
77         uint8_t resp_opcode;
78         uint8_t req_opcode;
79         uint8_t result_code;
80         uint8_t *resp_param;
81 };
82
83 /* Object metadata */
84 struct object_metadata {
85         gchar *name;
86         gchar *type;
87         uint32_t curr_size;
88         uint32_t alloc_size;
89         time_t first_created;
90         time_t last_modified;
91         uint64_t id;
92         uint32_t props;
93 };
94
95 struct oacp_operation {
96         char *remote_address;
97         uint32_t offset;
98         uint32_t length;
99         uint8_t opcode;
100         uint32_t length_sofar;
101         uint8_t mode;
102         int fd;
103         FILE *fp;
104 };
105
106 static struct object_metadata *selected_object = NULL;
107 static uint64_t object_id = OBJECT_START_ID;
108 static GSList *otp_object_list = NULL;
109 static GSList *otp_char_list = NULL;
110 static guint curr_obj_index;
111 static int adv_handle = 0;
112 static gboolean OACP_indicate = FALSE;
113 static gboolean OLCP_indicate = FALSE;
114 char *directory = NULL;
115 gboolean mutiple_obj_support = false;
116 static gboolean otc_connection_status = FALSE;
117 struct oacp_operation *oacp_op = NULL;
118 unsigned int timeout_id;
119 unsigned int oacp_create_timeout_id;
120 uint64_t curr_obj_id, prev_obj_id;
121
122 static const gchar otp_introspection_xml[] =
123 "<node name='/'>"
124 "       <interface name='org.projectx.otp_service'>"
125 "               <method name='enable'>"
126 "                       <arg type='s' name='directory'/>"
127 "                       <arg type='i' name='status' direction='out'/>"
128 "               </method>"
129 "               <method name='disable'>"
130 "                       <arg type='i' name='status' direction='out'/>"
131 "               </method>"
132 "     <method name='NewConnection'>"
133 "          <arg type='o' name='object' direction='in'/>"
134 "          <arg type='h' name='fd' direction='in'/>"
135 "     </method>"
136 "       </interface>"
137 "</node>";
138
139 void _bt_otp_deinit_event_receiver(void);
140 void _bt_otp_unregister_interface(void);
141 void update_obj_metadata_charc_value(struct object_metadata *object);
142 void _bt_convert_device_path_to_address(const char *device_path,
143                                                 char *device_address);
144 int _bt_otp_open_otc_and_listen(char *address, char *method);
145 void _bt_otp_delete_empty_file();
146 struct object_metadata *_bt_otp_client_find_object(GSList *list,
147                                                                         uint64_t id, guint *index);
148
149 static void delete_all_objects(void)
150 {
151         GSList *tmp = NULL;
152         for (tmp = otp_object_list; tmp != NULL; tmp = tmp->next) {
153                 if (tmp->data) {
154                         struct object_metadata *obj_info = tmp->data;
155                         if (obj_info->name)
156                                 g_free(obj_info->name);
157                         if (obj_info->type)
158                                 g_free(obj_info->type);
159                         otp_object_list = g_slist_delete_link(otp_object_list, tmp->data);
160                 }
161         }
162         g_slist_free(otp_object_list);
163         otp_object_list = NULL;
164 }
165
166 static void delete_all_characterisitc(void)
167 {
168         GSList *tmp = NULL;
169         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
170                 if (tmp->data) {
171                         struct otp_char_info *char_info = tmp->data;
172                         if (char_info->char_path)
173                                 g_free(char_info->char_path);
174                         if (char_info->char_value)
175                                 g_free(char_info->char_value);
176                         otp_char_list = g_slist_delete_link(otp_char_list, tmp->data);
177                 }
178         }
179         g_slist_free(otp_char_list);
180         otp_char_list = NULL;
181 }
182
183 void _bt_otp_exit(void)
184 {
185         int ret;
186         BT_DBG("");
187
188         if (otp_char_list)
189                 delete_all_characterisitc();
190
191         if (otp_object_list)
192                 delete_all_objects();
193
194         ret = bluetooth_gatt_deinit();
195         if (ret != BLUETOOTH_ERROR_NONE)
196                 BT_ERR("Failed to Deinit GATT %d", ret);
197
198         _bt_otp_deinit_event_receiver();
199
200         _bt_otp_unregister_interface();
201
202         /* TODO: Advertising is not getting stopped by this API.
203          * This is because OTP_SERVER_DEINIT dbus call is blocking
204          * BT_SET_ADVERTISING_DATA dbus call. But now advertisment
205          * is stopped because of terminated process logic.
206          */
207         ret = bluetooth_set_advertising(adv_handle, FALSE);
208         if (ret != BLUETOOTH_ERROR_NONE)
209                 BT_ERR("Failed to stop ADV %d", ret);
210
211         if (main_loop != NULL) {
212                 g_main_loop_quit(main_loop);
213         }
214 }
215
216 static void _bt_otp_set_char_value(const char *obj_path,
217                                 const char *value, int value_length)
218 {
219         GSList *tmp = NULL;
220
221         if (!value)
222                 return;
223         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
224                 if (tmp->data) {
225                         struct otp_char_info *char_info = tmp->data;
226                         if (!g_strcmp0(char_info->char_path, obj_path)) {
227                                 char_info->char_value = g_try_realloc(char_info->char_value, value_length);
228                                 if (char_info->char_value) {
229                                         memcpy(char_info->char_value, value, value_length);
230                                         char_info->value_length = value_length;
231                                 }
232                                 return;
233                         }
234                 }
235         }
236         return;
237 }
238
239 int add_new_characteristic(const char *char_uuid, bt_gatt_permission_t perms,
240                 bt_gatt_characteristic_property_t props, char **obj_path)
241 {
242         int ret = BLUETOOTH_ERROR_NONE;
243         struct otp_char_info *char_info = NULL;
244
245         ret = bluetooth_gatt_add_new_characteristic(otp_obj_path,
246                                         char_uuid, perms, props, obj_path);
247         if (ret != BLUETOOTH_ERROR_NONE) {
248                 BT_ERR("Failed to add new char %d", ret);
249                 return ret;
250         }
251
252         char_info = g_new0(struct otp_char_info, 1);
253         char_info->char_path = g_strdup(*obj_path);
254         otp_char_list = g_slist_append(otp_char_list, char_info);
255
256         return ret;
257 }
258
259 static char *_otp_convert_uuid_to_uuid128(const char *uuid)
260 {
261         int len;
262         char *uuid128;
263
264         len = strlen(uuid);
265
266         switch (len) {
267         case 4:
268                 /* UUID 16bits */
269                 uuid128 = g_strdup_printf("0000%s-0000-1000-8000-00805f9b34fb",
270                                                                         uuid);
271                 break;
272
273         case 8:
274                 /* UUID 32bits */
275                 uuid128 = g_strdup_printf("%s-0000-1000-8000-00805f9b34fb",
276                                                                         uuid);
277                 break;
278
279         case 36:
280                 /* UUID 128bits */
281                 uuid128 = strdup(uuid);
282                 break;
283
284         default:
285                 return NULL;
286         }
287
288         return uuid128;
289 }
290
291 int _bt_otp_prepare_ots(void)
292 {
293         BT_DBG("+");
294         int ret = BLUETOOTH_ERROR_NONE;
295         char *service_uuid;
296         char *char_uuid;
297         char *desc_uuid;
298         bt_gatt_characteristic_property_t props;
299         bt_gatt_permission_t perms;
300         char supp_feat[OTP_FEATURE_LENGTH] = { 0x3B, 0x00, 0x00, 0x00,
301                                                 0x01, 0x00, 0x00, 0x00 };
302
303         ret = bluetooth_gatt_init();
304         if (ret != BLUETOOTH_ERROR_NONE) {
305                 BT_ERR("Failed to Init GATT %d", ret);
306                 goto fail;
307         }
308
309         service_uuid = _otp_convert_uuid_to_uuid128(OTP_UUID);
310         ret = bluetooth_gatt_add_service(service_uuid, &otp_obj_path);
311         if (ret != BLUETOOTH_ERROR_NONE) {
312                 BT_ERR("Failed to add service %d", ret);
313                 goto fail;
314         }
315
316         /* Characteristic OTP Feature */
317         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
318         perms = BLUETOOTH_GATT_PERMISSION_READ;
319         char_uuid = _otp_convert_uuid_to_uuid128(OTP_FEATURE_UUID);
320         ret = add_new_characteristic(char_uuid, perms, props,
321                                                 &otp_feature_obj_path);
322         if (ret != BLUETOOTH_ERROR_NONE)
323                 goto fail;
324
325         ret = bluetooth_gatt_set_characteristic_value(otp_feature_obj_path,
326                                                 supp_feat, OTP_FEATURE_LENGTH);
327         if (ret != BLUETOOTH_ERROR_NONE) {
328                 BT_ERR("Failed to set char value %d", ret);
329                 return ret;
330         }
331
332         _bt_otp_set_char_value(otp_feature_obj_path, supp_feat,
333                                                 OTP_FEATURE_LENGTH);
334
335         /* Characteristic Object Name */
336         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
337                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
338         perms = BLUETOOTH_GATT_PERMISSION_READ |
339                 BLUETOOTH_GATT_PERMISSION_WRITE;
340         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_NAME_UUID);
341         ret = add_new_characteristic(char_uuid, perms, props,
342                                         &otp_object_name_obj_path);
343         if (ret != BLUETOOTH_ERROR_NONE)
344                 goto fail;
345
346         /* Characteristic Object Type */
347         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
348         perms = BLUETOOTH_GATT_PERMISSION_READ;
349         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_TYPE_UUID);
350         ret = add_new_characteristic(char_uuid, perms, props,
351                                         &otp_object_type_obj_path);
352         if (ret != BLUETOOTH_ERROR_NONE)
353                 goto fail;
354
355         /* Characteristic Object Size */
356         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
357         perms = BLUETOOTH_GATT_PERMISSION_READ;
358         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_SIZE_UUID);
359         ret = add_new_characteristic(char_uuid, perms, props,
360                                         &otp_object_size_obj_path);
361         if (ret != BLUETOOTH_ERROR_NONE)
362                 goto fail;
363
364         /* Characteristic Object First-Created */
365         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
366                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
367         perms = BLUETOOTH_GATT_PERMISSION_READ |
368                 BLUETOOTH_GATT_PERMISSION_WRITE;
369         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_FIRST_CREATED_UUID);
370         ret = add_new_characteristic(char_uuid, perms, props,
371                                         &otp_object_first_created_obj_path);
372         if (ret != BLUETOOTH_ERROR_NONE)
373                 goto fail;
374
375         /* Characteristic Object Last-Modified */
376         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
377                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
378         perms = BLUETOOTH_GATT_PERMISSION_READ |
379                 BLUETOOTH_GATT_PERMISSION_WRITE;
380         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_LAST_MODIFIED_UUID);
381         ret = add_new_characteristic(char_uuid, perms, props,
382                                 &otp_object_last_modified_obj_path);
383         if (ret != BLUETOOTH_ERROR_NONE)
384                 goto fail;
385
386         /* Object ID is mandatory for mutiple object server */
387         if (mutiple_obj_support) {
388                 /* Characteristic Object ID */
389                 props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ;
390                 perms = BLUETOOTH_GATT_PERMISSION_READ;
391                 char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_ID_UUID);
392                 ret = add_new_characteristic(char_uuid, perms, props,
393                                                 &otp_object_id_obj_path);
394                 if (ret != BLUETOOTH_ERROR_NONE)
395                         goto fail;
396         }
397
398         /* Characteristic Object Properties */
399         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_READ |
400                         BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE;
401         perms = BLUETOOTH_GATT_PERMISSION_READ |
402                         BLUETOOTH_GATT_PERMISSION_WRITE;
403         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_PROP_UUID);
404         ret = add_new_characteristic(char_uuid, perms, props,
405                                         &otp_object_prop_obj_path);
406         if (ret != BLUETOOTH_ERROR_NONE)
407                 goto fail;
408
409         /* Characteristic OACP */
410         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
411                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
412         perms = BLUETOOTH_GATT_PERMISSION_WRITE;
413         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OACP_UUID);
414         ret = add_new_characteristic(char_uuid, perms, props,
415                                                 &otp_oacp_obj_path);
416         if (ret != BLUETOOTH_ERROR_NONE)
417                 goto fail;
418
419         /* CCCD for OACP */
420         desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
421         perms = BLUETOOTH_GATT_PERMISSION_READ |
422                 BLUETOOTH_GATT_PERMISSION_WRITE;
423         ret = bluetooth_gatt_add_descriptor(otp_oacp_obj_path, desc_uuid,
424                                                 perms, &otp_oacp_desc_obj_path);
425         if (ret != BLUETOOTH_ERROR_NONE) {
426                 BT_ERR("Failed to add new char descriptor %d", ret);
427                 goto fail;
428         }
429
430         /* OLCP Characteristics is not required
431          * for single object server
432          */
433         if (mutiple_obj_support) {
434                 /* Characteristic OLCP */
435                 props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
436                         BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
437                 perms = BLUETOOTH_GATT_PERMISSION_WRITE;
438                 char_uuid = _otp_convert_uuid_to_uuid128(OTP_OLCP_UUID);
439                 ret = add_new_characteristic(char_uuid, perms, props,
440                                                         &otp_olcp_obj_path);
441                 if (ret != BLUETOOTH_ERROR_NONE)
442                         goto fail;
443
444                 /* CCCD for OLCP */
445                 desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
446                 perms = BLUETOOTH_GATT_PERMISSION_READ |
447                         BLUETOOTH_GATT_PERMISSION_WRITE;
448                 ret = bluetooth_gatt_add_descriptor(otp_olcp_obj_path, desc_uuid,
449                                                         perms, &otp_olcp_desc_obj_path);
450                 if (ret != BLUETOOTH_ERROR_NONE) {
451                         BT_ERR("Failed to add new char descriptor %d", ret);
452                         goto fail;
453                 }
454         }
455
456         /* Register service */
457         ret = bluetooth_gatt_register_service(otp_obj_path);
458         if (ret != BLUETOOTH_ERROR_NONE) {
459                 BT_ERR("Failed to register service %d", ret);
460                 goto fail;
461         }
462
463         /* Register Application */
464         ret = bluetooth_gatt_register_application();
465         if (ret != BLUETOOTH_ERROR_NONE) {
466                 BT_ERR("Failed to register application %d", ret);
467                 goto fail;
468         }
469
470         BT_DBG("-");
471         return ret;
472
473 fail:
474         delete_all_characterisitc();
475         return ret;
476 }
477
478 int _bt_otp_set_advertising_data(void)
479 {
480         int ret;
481         BT_DBG("");
482
483         /* OTP UUID */
484         guint8 data[4]  = {0x03, 0x02, 0x25, 0x18};
485         bluetooth_advertising_data_t adv;
486
487         BT_DBG("%x %x %x %x", data[0], data[1], data[2], data[3]);
488         memcpy(adv.data, data, sizeof(data));
489         ret = bluetooth_set_advertising_data(adv_handle, &adv, sizeof(data));
490         if (ret != BLUETOOTH_ERROR_NONE) {
491                 BT_ERR("Failed to set ADV data %d", ret);
492                 return ret;
493         }
494
495         ret = bluetooth_set_advertising(adv_handle, TRUE);
496         if (ret != BLUETOOTH_ERROR_NONE) {
497                 BT_ERR("Failed to set ADV %d", ret);
498                 return ret;
499         }
500
501         return 0;
502 }
503
504 void _bt_otp_start_write_on_fd()
505 {
506         char buf[BT_L2CAP_BUFFER_LEN];
507         int written;
508         int read;
509         int len;
510         FILE *fp;
511         char file_path[BT_FILE_PATH_MAX_LEN] = {0, };
512         int length;
513
514         snprintf(file_path, sizeof(file_path), "%s%s",
515                                         directory, selected_object->name);
516         BT_DBG("file_path = [%s]", file_path);
517
518         fp = fopen(file_path, "r");
519         if (!fp) {
520                 BT_DBG("fopen() failed : %s", strerror(errno));
521                 return;
522         }
523
524         BT_DBG("length [%d]", oacp_op->length);
525         length = oacp_op->length;
526
527         while (length > 0) {
528                 if (length < BT_L2CAP_BUFFER_LEN)
529                         len = length;
530                 else
531                         len = BT_L2CAP_BUFFER_LEN;
532
533                 read = fread(buf, 1, len, fp);
534                 written = write(oacp_op->fd, buf, len);
535
536                 if (written < 0)
537                         goto fail;
538
539                 length -= written;
540
541                 BT_DBG("read [%d], written [%d], rem_len [%d]",
542                                                 read, written, length);
543         }
544 fail:
545         fclose(fp);
546 }
547
548
549 static bool __bt_otc_connection_timeout_cb(gpointer user_data)
550 {
551         int err = BLUETOOTH_ERROR_NONE;
552         char *remote_addr = oacp_op->remote_address;
553
554         err = _bt_otp_open_otc_and_listen(remote_addr, "DisconnectOtc");
555         if (err != BLUETOOTH_ERROR_NONE)
556                 BT_ERR("Disconnect OTC failed");
557
558         return TRUE;
559 }
560
561 static gboolean __server_data_received_cb(GIOChannel *chan, GIOCondition cond,
562                                                                 gpointer data)
563 {
564         char *remote_addr = oacp_op->remote_address;
565         GIOStatus status = G_IO_STATUS_NORMAL;
566         GError *err = NULL;
567         char *buffer = NULL;
568         gsize len = 0;
569         int written;
570         int fd;
571
572         BT_DBG("");
573
574         fd = g_io_channel_unix_get_fd(chan);
575         if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) {
576                 otc_connection_status = FALSE;
577                 BT_ERR("OTC disconnected: %d", fd);
578                 close(fd);
579                 g_source_remove(server_watch_id);
580                 return FALSE;
581         }
582
583         buffer = g_malloc0(BT_L2CAP_BUFFER_LEN + 1);
584
585         status = g_io_channel_read_chars(chan, buffer,
586                                                         BT_L2CAP_BUFFER_LEN,
587                                                         &len, &err);
588         if (status != G_IO_STATUS_NORMAL) {
589                 BT_ERR("IO Channel read is failed with %d", status);
590
591                 g_free(buffer);
592                 if (err) {
593                         otc_connection_status = FALSE;
594                         BT_ERR("IO Channel read error [%s]", err->message);
595                         if (status == G_IO_STATUS_ERROR) {
596                                 BT_ERR("cond : %d", cond);
597                                 g_error_free(err);
598                                 close(fd);
599                                 g_source_remove(server_watch_id);
600                                 return FALSE;
601                         }
602                         g_error_free(err);
603                 }
604                 return TRUE;
605         }
606
607         BT_DBG("Received data length %d, remote_addr = %s", len, remote_addr);
608
609         if (!oacp_op->fp) {
610                 char file_path[BT_FILE_PATH_MAX_LEN] = {0, };
611                 FILE *fp = NULL;
612
613                 if (!selected_object) {
614                         BT_DBG("Object not selected");
615                         goto fail;
616                 }
617
618                 snprintf(file_path, sizeof(file_path), "%s%s",
619                                                 directory, selected_object->name);
620
621                 BT_DBG("file_path = [%s]", file_path);
622                 fp = fopen(file_path, "w");
623                 if (!fp) {
624                         BT_DBG("fopen() failed : %s", strerror(errno));
625                         goto fail;
626                 }
627                 oacp_op->fp = fp;
628         }
629
630         if (oacp_op->length_sofar <= oacp_op->length) {
631                 written = fwrite(buffer, 1, len, oacp_op->fp);
632                 oacp_op->length_sofar += written;
633                 BT_DBG("written [%d], length_sofar [%lu], received_buff_len [%d], size [%lu]",
634                                         written, oacp_op->length_sofar, len, oacp_op->length);
635         }
636
637         if (timeout_id > 0) {
638                 g_source_remove(timeout_id);
639                 timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
640                         (GSourceFunc)__bt_otc_connection_timeout_cb, NULL);
641         }
642 fail:
643         g_free(buffer);
644         return TRUE;
645 }
646
647 static void _bt_otp_start_read_on_fd()
648 {
649         GIOChannel *data_io;
650         data_io = g_io_channel_unix_new(oacp_op->fd);
651
652         g_io_channel_set_encoding(data_io, NULL, NULL);
653         g_io_channel_set_flags(data_io, G_IO_FLAG_NONBLOCK, NULL);
654
655         server_watch_id = g_io_add_watch(data_io,
656                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
657                 __server_data_received_cb, NULL);
658
659         if (timeout_id > 0)
660                         g_source_remove(timeout_id);
661
662         timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
663                 (GSourceFunc)__bt_otc_connection_timeout_cb, NULL);
664 }
665
666 static void _bt_otp_method(GDBusConnection *connection,
667                 const gchar *sender,
668                 const gchar *object_path,
669                 const gchar *interface_name,
670                 const gchar *method_name,
671                 GVariant *parameters,
672                 GDBusMethodInvocation *invocation,
673                 gpointer user_data)
674 {
675         BT_DBG("+");
676         int status = BLUETOOTH_ERROR_NONE;
677
678         BT_DBG("Method[%s] Object Path[%s] Interface Name[%s]",
679                         method_name, object_path, interface_name);
680
681         if (g_strcmp0(method_name, "enable") == 0) {
682                 GDir *dir = NULL;
683                 GError *error = NULL;
684                 const gchar *filename = NULL;
685                 char absolute_path[BT_FILE_PATH_MAX_LEN];
686                 GSList *list = NULL, *l = NULL;
687                 struct stat st;
688                 struct object_metadata *object = NULL;
689
690                 g_variant_get(parameters, "(s)", &directory);
691                 BT_DBG("Directory = [%s]", directory);
692
693                 dir = g_dir_open(directory, 0, &error);
694                 if (!dir) {
695                         BT_ERR("Failed to open directory: %s", error->message);
696                         g_error_free(error);
697                         status = BLUETOOTH_ERROR_INVALID_DIRECTORY;
698                         goto fail;
699                 }
700
701                 while ((filename = g_dir_read_name(dir))) {
702                         list = g_slist_append(list, (gpointer) filename);
703                 }
704
705                 g_dir_close(dir);
706
707                 if (!list) {
708                         BT_DBG("No object found in given directory");
709                         status = BLUETOOTH_ERROR_NO_OBJECTS_FOUND;
710                         goto fail;
711                 }
712
713                 if (g_slist_length(list) > 1)
714                         mutiple_obj_support = true;
715
716                 for (l = list; l != NULL; l = l->next) {
717                         if (!l->data) continue;
718                         snprintf(absolute_path, sizeof(absolute_path), "%s%s", directory,
719                                                         (char *)l->data);
720
721                         BT_INFO("filename: %s, absoulte_path: %s",
722                                         (char *)l->data, absolute_path);
723
724                         if (stat(absolute_path, &st) == -1) {
725                                 BT_INFO("stat failed: (%d)\n", errno);
726                                 continue;
727                         }
728
729                         object = g_new0(struct object_metadata, 1);
730
731                         object->name = g_strdup((const gchar *)l->data);
732                         object->type = g_strdup(UNSUPPORTED_OBJECT_TYPE_UUID);
733                         object->first_created = st.st_ctime;
734                         object->last_modified = st.st_ctime;
735                         object->curr_size = (uint32_t) st.st_size;
736                         object->alloc_size = (uint32_t) st.st_size;
737                         object->id = object_id;
738                         object->props = OBJECT_READ | OBJECT_WRITE |
739                                         OBJECT_EXECUTE | OBJECT_DELETE;
740
741                         otp_object_list = g_slist_append(otp_object_list,
742                                                                 object);
743
744                         object_id++;
745                 }
746
747                 BT_DBG("preparing");
748                 if (_bt_otp_prepare_ots() != BLUETOOTH_ERROR_NONE) {
749                         BT_ERR("Fail to prepare OTP Proxy");
750                         status = BLUETOOTH_ERROR_INTERNAL;
751                         goto fail;
752                 }
753
754                 /* If single object is supported, make that as
755                  * selected object and update the metadata for the same.
756                  */
757                 if (!mutiple_obj_support) {
758                         BT_INFO("Server supports single object");
759                         selected_object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
760                         if (selected_object)
761                                 update_obj_metadata_charc_value(selected_object);
762                 }
763
764                 BT_DBG("advertsing");
765                 if (_bt_otp_set_advertising_data() != BLUETOOTH_ERROR_NONE) {
766                         BT_ERR("Fail to set advertising data");
767                         status = BLUETOOTH_ERROR_INTERNAL;
768                         goto fail;
769                 }
770 fail:
771                 g_dbus_method_invocation_return_value(invocation,
772                                                 g_variant_new("(i)", status));
773
774         } else if (g_strcmp0(method_name, "disable") == 0) {
775                 g_dbus_method_invocation_return_value(invocation,
776                                                 g_variant_new("(i)", status));
777                 _bt_otp_exit();
778
779         } else if (g_strcmp0(method_name, "NewConnection") == 0) {
780                 int index;
781                 GDBusMessage *msg;
782                 GUnixFDList *fd_list;
783                 char *dev_path;
784                 char address[BT_ADDRESS_STRING_SIZE] = { 0 };
785                 int fd;
786
787                 g_variant_get(parameters, "(oh)", &dev_path, &index);
788
789                 msg = g_dbus_method_invocation_get_message(invocation);
790                 fd_list = g_dbus_message_get_unix_fd_list(msg);
791                 if (fd_list == NULL) {
792                         BT_ERR("fd_list is NULL");
793                         return;
794                 }
795
796                 fd = g_unix_fd_list_get(fd_list, index, NULL);
797                 if (fd == -1) {
798                         BT_ERR("Invalid fd return");
799                         return;
800                 }
801
802                 _bt_convert_device_path_to_address(dev_path, address);
803
804                 BT_INFO("OTC Connected fd: %d, address %s", fd, address);
805                 otc_connection_status = TRUE;
806                 if (oacp_op) {
807                         oacp_op->fd = fd;
808
809                         if (oacp_op->opcode == OACP_READ)
810                                 _bt_otp_start_write_on_fd();
811                         else if (oacp_op->opcode == OACP_WRITE)
812                                 _bt_otp_start_read_on_fd();
813                 }
814                 g_dbus_method_invocation_return_value(invocation, NULL);
815         }
816         BT_DBG("-");
817 }
818
819 static const GDBusInterfaceVTable otp_method_table = {
820         _bt_otp_method,
821         NULL,
822         NULL,
823 };
824
825 static void _bt_otp_on_bus_acquired(GDBusConnection *connection,
826                                 const gchar *name, gpointer user_data)
827 {
828         guint object_id;
829         GError *error = NULL;
830
831         BT_DBG("+");
832
833         g_conn = connection;
834
835         object_id = g_dbus_connection_register_object(connection,
836                                                 BT_OTP_OBJECT_PATH,
837                                                 otp_node_info->interfaces[0],
838                                                 &otp_method_table,
839                                                 NULL, NULL, &error);
840         if (object_id == 0) {
841                 BT_ERR("Failed to register method table: %s", error->message);
842                 g_error_free(error);
843                 g_dbus_node_info_unref(otp_node_info);
844         }
845
846         BT_DBG("-");
847 }
848
849 static void _bt_otp_on_name_acquired(GDBusConnection *connection,
850                                         const gchar     *name,
851                                         gpointer user_data)
852 {
853         BT_DBG("");
854 }
855
856 static void _bt_otp_on_name_lost(GDBusConnection *connection,
857                                 const gchar     *name,
858                                 gpointer user_data)
859 {
860         BT_DBG("");
861         g_object_unref(g_conn);
862         g_conn = NULL;
863         g_dbus_node_info_unref(otp_node_info);
864         g_bus_unown_name(g_owner_id);
865 }
866
867 int _bt_otp_register_interface(void)
868 {
869         BT_DBG("+");
870         GError *error = NULL;
871         guint owner_id;
872
873         otp_node_info = g_dbus_node_info_new_for_xml(otp_introspection_xml, &error);
874         if (!otp_node_info) {
875                 BT_ERR("Failed to install: %s", error->message);
876                 return BLUETOOTH_ERROR_INTERNAL;
877         }
878
879         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
880                                 BT_OTP_SERVICE_NAME,
881                                 G_BUS_NAME_OWNER_FLAGS_NONE,
882                                 _bt_otp_on_bus_acquired,
883                                 _bt_otp_on_name_acquired,
884                                 _bt_otp_on_name_lost,
885                                 NULL, NULL);
886         g_owner_id = owner_id;
887         BT_DBG("owner_id is [%d]\n", owner_id);
888
889         BT_DBG("-");
890         return BLUETOOTH_ERROR_NONE;
891 }
892
893 void _bt_otp_unregister_interface(void)
894 {
895         BT_DBG("+");
896
897         g_object_unref(g_conn);
898         g_conn = NULL;
899         g_dbus_node_info_unref(otp_node_info);
900         g_bus_unown_name(g_owner_id);
901
902         BT_DBG("-");
903         return;
904 }
905
906 void _bt_convert_device_path_to_address(const char *device_path,
907                                                 char *device_address)
908 {
909         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
910         char *dev_addr;
911
912         dev_addr = strstr(device_path, "dev_");
913         if (dev_addr != NULL) {
914                 char *pos = NULL;
915                 dev_addr += 4;
916                 g_strlcpy(address, dev_addr, sizeof(address));
917
918                 while ((pos = strchr(address, '_')) != NULL)
919                         *pos = ':';
920
921                 g_strlcpy(device_address, address, BT_ADDRESS_STRING_SIZE);
922         }
923 }
924
925 static char *__bt_extract_device_path(GVariantIter *iter, char *address)
926 {
927         char *object_path = NULL;
928         char device_address[BT_ADDRESS_STRING_SIZE] = { 0 };
929
930         /* Parse the signature: oa{sa{sv}}} */
931         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path,
932                         NULL)) {
933                 if (!object_path) {
934                         BT_ERR("Unable to get object path");
935                         return NULL;
936                 }
937                 _bt_convert_device_path_to_address(object_path, device_address);
938                 if (g_strcmp0(address, device_address) == 0)
939                         return g_strdup(object_path);
940
941         }
942
943         BT_ERR("Unable to get object path");
944         return NULL;
945 }
946
947 char *_bt_otp_get_device_object_path(char *address)
948 {
949         GError *err = NULL;
950         GDBusProxy *proxy = NULL;
951         GVariant *result = NULL;
952         GVariantIter *iter = NULL;
953         char *object_path = NULL;
954
955         proxy =  g_dbus_proxy_new_sync(conn,
956                         G_DBUS_PROXY_FLAGS_NONE, NULL,
957                         BT_BLUEZ_NAME,
958                         BT_MANAGER_PATH,
959                         BT_MANAGER_INTERFACE,
960                         NULL, &err);
961
962         if (!proxy) {
963                 BT_ERR("Unable to create proxy: %s", err->message);
964                 goto fail;
965         }
966
967         result = g_dbus_proxy_call_sync(proxy, "GetManagedObjects", NULL,
968                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
969         if (!result) {
970                 if (err != NULL)
971                         BT_ERR("Fail to get GetManagedObjects (Error: %s)", err->message);
972                 else
973                         BT_ERR("Fail to get GetManagedObjects");
974
975                 goto fail;
976         }
977
978         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
979         object_path = __bt_extract_device_path(iter, address);
980
981         g_variant_unref(result);
982         g_variant_iter_free(iter);
983
984 fail:
985         if (err)
986                 g_clear_error(&err);
987
988         if (proxy)
989                 g_object_unref(proxy);
990
991         return object_path;
992 }
993
994 int _bt_otp_open_otc_and_listen(char *address, char *method)
995 {
996         char *object_path;
997         GDBusProxy *device_proxy = NULL;
998         GVariant *result = NULL;
999         GError *error = NULL;
1000         int ret = BLUETOOTH_ERROR_NONE;
1001
1002         if (method == NULL)
1003                 return BLUETOOTH_ERROR_INTERNAL;
1004
1005         if (g_strcmp0(method, "ListenOtc") &&
1006                         g_strcmp0(method, "DisconnectOtc"))
1007                 return BLUETOOTH_ERROR_INTERNAL;
1008
1009         object_path = _bt_otp_get_device_object_path(address);
1010         if (object_path == NULL) {
1011                 ret = BLUETOOTH_ERROR_NOT_PAIRED;
1012                 goto fail;
1013         }
1014
1015         device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
1016                                         NULL, BT_BLUEZ_NAME, object_path,
1017                                         BT_DEVICE_INTERFACE,  NULL, NULL);
1018         if (device_proxy == NULL) {
1019                 ret = BLUETOOTH_ERROR_INTERNAL;
1020                 goto fail;
1021         }
1022
1023
1024         result = g_dbus_proxy_call_sync(device_proxy, method,
1025                                 NULL,
1026                                 G_DBUS_CALL_FLAGS_NONE,
1027                                 -1,
1028                                 NULL,
1029                                 &error);
1030         if (result == NULL) {
1031                 if (error != NULL) {
1032                         BT_ERR("Error occured in Proxy call [%s]\n", error->message);
1033                         g_error_free(error);
1034                 }
1035                 ret = BLUETOOTH_ERROR_INTERNAL;
1036         }
1037 fail:
1038         if (object_path)
1039                 g_free(object_path);
1040         if (result)
1041                 g_variant_unref(result);
1042         if (device_proxy)
1043                 g_object_unref(device_proxy);
1044         return ret;
1045 }
1046
1047 static bool __bt_oacp_create_timeout_cb(gpointer user_data)
1048 {
1049         /* Delete the EMPTY object */
1050         _bt_otp_delete_empty_file();
1051         return TRUE;
1052 }
1053
1054 static void _bt_otp_free_oacp_op()
1055 {
1056         if (timeout_id > 0) {
1057                 g_source_remove(timeout_id);
1058                 timeout_id = 0;
1059         }
1060
1061         if (oacp_op) {
1062                 g_free(oacp_op->remote_address);
1063                 if (oacp_op->fp)
1064                         fclose(oacp_op->fp);
1065                 g_free(oacp_op);
1066                 oacp_op = NULL;
1067         }
1068 }
1069
1070 int _bt_otp_send_launch_request(char *absolute_path)
1071 {
1072         void *handle;
1073         char *error;
1074         int ret;
1075
1076         /* check ARCH 64 or 32*/
1077         if (!access(FILEPATH_ARCH_64, 0)) {
1078                 BT_INFO("plugin loading for ARCH 64");
1079                 handle = dlopen(HEADED_PLUGIN_FILEPATH64, RTLD_NOW);
1080         } else {
1081                 BT_INFO("plugin loading for ARCH 32");
1082                 handle = dlopen(HEADED_PLUGIN_FILEPATH, RTLD_NOW);
1083         }
1084
1085         if (!handle) {
1086                 BT_ERR("Can not load plugin %s", dlerror());
1087                 return BLUETOOTH_ERROR_INTERNAL;
1088         }
1089
1090         dlerror();      /* Clear any existing error */
1091
1092         int (*fun)(char *) = (int (*)(char *))dlsym(handle,
1093                                         "bt_app_control_send_launch_request");
1094
1095         if ((error = dlerror()) != NULL)  {
1096                 BT_ERR("Can not load symbol : %s", dlerror());
1097                 dlclose(handle);
1098                 return BLUETOOTH_ERROR_INTERNAL;
1099         }
1100
1101         ret = fun(absolute_path);
1102         dlclose(handle);
1103
1104         return ret;
1105 }
1106
1107 char *_bt_otp_uuid_convert_hex_to_string(char *value, uint32_t length)
1108 {
1109         char *uuid = NULL;
1110         unsigned int   data0;
1111         unsigned short data1;
1112         unsigned short data2;
1113         unsigned short data3;
1114         unsigned int   data4;
1115         unsigned short data5;
1116         size_t n;
1117
1118         uuid = (char *) g_malloc0(2 * length * sizeof(char));
1119         n = 2 * length + 1;
1120
1121         switch (length) {
1122         case 2:
1123                 memcpy(&data1, &value[0], 2);
1124                 snprintf(uuid, n, "%.4x", ntohs(data1));
1125                 break;
1126         case 4:
1127                 memcpy(&data0, &value[0], 4);
1128                 snprintf(uuid, n, "%.8x", ntohl(data0));
1129                 break;
1130         case 16:
1131                 memcpy(&data0, &value[0], 4);
1132                 memcpy(&data1, &value[4], 2);
1133                 memcpy(&data2, &value[6], 2);
1134                 memcpy(&data3, &value[8], 2);
1135                 memcpy(&data4, &value[10], 4);
1136                 memcpy(&data5, &value[14], 2);
1137
1138                 snprintf(uuid, n + 4, "%.8x-%.4x-%.4x-%.4x-%.8x%.4x",
1139                                         ntohl(data0), ntohs(data1),
1140                                         ntohs(data2), ntohs(data3),
1141                                         ntohl(data4), ntohs(data5));
1142                 break;
1143         default:
1144                 g_free(uuid);
1145                 return NULL;
1146         }
1147
1148         return uuid;
1149 }
1150
1151 int _bt_otp_create_empty_file(uint32_t size, char *uuid)
1152 {
1153         int ret = BLUETOOTH_ERROR_NONE;
1154         struct object_metadata *object = NULL;
1155         struct stat st;
1156         char absolute_file_path[BT_FILE_PATH_MAX_LEN] = {0, };
1157         FILE *fp = NULL;
1158
1159         snprintf(absolute_file_path, sizeof(absolute_file_path),
1160                                                 "%s%s", directory, BT_OTP_EMPTY_FILENAME);
1161         BT_DBG("file_path = [%s]", absolute_file_path);
1162
1163         fp = fopen(absolute_file_path, "a");
1164         if (!fp) {
1165                 BT_DBG("fopen() failed : %s", strerror(errno));
1166                 ret = BLUETOOTH_ERROR_INTERNAL;
1167                 goto fail;
1168         }
1169
1170         if (stat(absolute_file_path, &st) == -1) {
1171                 BT_INFO("stat failed: (%d)\n", errno);
1172                 ret = BLUETOOTH_ERROR_INTERNAL;
1173                 goto fail;
1174         }
1175
1176         /* Store current object id.
1177          * Incase of OACP Create fail, need to restore
1178          * it back.
1179          */
1180         prev_obj_id = selected_object->id;
1181
1182         object = g_new0(struct object_metadata, 1);
1183
1184         object->name = g_strdup(BT_OTP_EMPTY_FILENAME);
1185         object->type = g_strdup(uuid);
1186         object->first_created = st.st_ctime;
1187         object->last_modified = st.st_ctime;
1188         object->curr_size = (uint32_t)st.st_size;
1189         object->alloc_size = size;
1190         object->id = object_id;
1191         object->props = OBJECT_READ | OBJECT_WRITE;
1192
1193         otp_object_list = g_slist_append(otp_object_list,
1194                                                 object);
1195
1196         update_obj_metadata_charc_value(object);
1197         selected_object = object;
1198         curr_obj_index = g_slist_length(otp_object_list) - 1;
1199         curr_obj_id = selected_object->id;
1200         object_id++;
1201 fail:
1202         if (fp)
1203                 fclose(fp);
1204         free(uuid);
1205         return ret;
1206 }
1207
1208 void _bt_otp_delete_empty_file()
1209 {
1210         struct object_metadata *object = NULL;
1211         guint index = 0;
1212         char absolute_file_path[BT_FILE_PATH_MAX_LEN] = {0, };
1213
1214         object = _bt_otp_client_find_object(otp_object_list, curr_obj_id, &index);
1215         if (!object)
1216                 return;
1217
1218         otp_object_list = g_slist_remove(otp_object_list, object);
1219
1220         snprintf(absolute_file_path, sizeof(absolute_file_path),
1221                                                 "%s%s", directory, object->name);
1222
1223         if (remove(absolute_file_path) != 0) {
1224                 BT_DBG("Error: unable to delete the file");
1225         }
1226
1227         index = 0;
1228         object = _bt_otp_client_find_object(otp_object_list, prev_obj_id, &index);
1229         update_obj_metadata_charc_value(object);
1230         selected_object = object;
1231         curr_obj_index = index;
1232         object_id--;
1233 }
1234
1235 int _bt_otp_oacp_write_cb(char *value, int len, int offset,
1236                                                         char *remote_addr, struct indicate_info *info)
1237 {
1238         int ret = OACP_SUCCESS;
1239         int err = BLUETOOTH_ERROR_NONE;
1240         int opcode = value[0];
1241         uint32_t object_offset, length, object_size;
1242         uint8_t mode = 0;
1243         char *uuid;
1244         char absolute_file_path[BT_FILE_PATH_MAX_LEN] = {0, };
1245
1246         BT_INFO("OACP Opcode 0x%d", opcode);
1247
1248         if (!selected_object) {
1249                 BT_DBG("Object not selected");
1250                 ret = OACP_INVALID_OBJ;
1251                 goto fail;
1252         }
1253
1254         switch (opcode) {
1255         case OACP_CREATE:
1256                 BT_INFO("OACP_CREATE");
1257                 if (len < 7) {
1258                         BT_DBG("Error: invalid param");
1259                         ret = OACP_INVALID_PARAM;
1260                         goto fail;
1261                 }
1262                 /* UUIDs can be 2/4/16 bytes long.
1263                  * So based on remaining len, determine uuid len.
1264                  */
1265                 length = len - 5;
1266
1267                 uuid = _bt_otp_uuid_convert_hex_to_string(value + 1, length);
1268                 object_size = (uint32_t)(value[length + 4] & 0xFF) << 24 |
1269                                 (uint32_t)(value[length + 3] & 0xFF) << 16 |
1270                                 (uint32_t)(value[length + 2] & 0xFF) << 8  |
1271                                 (uint32_t)(value[length + 1] & 0xFF);
1272
1273                 BT_INFO("Size = %u, UUID = %s", object_size, uuid);
1274
1275                 err = _bt_otp_create_empty_file(object_size, uuid);
1276                 if (err != BLUETOOTH_ERROR_NONE) {
1277                         BT_ERR("Failed to create empty file");
1278                         ret = OACP_OPERATION_FAILED;
1279                         goto fail;
1280                 }
1281
1282                 if (oacp_create_timeout_id > 0)
1283                         g_source_remove(oacp_create_timeout_id);
1284                 oacp_create_timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
1285                         (GSourceFunc)__bt_oacp_create_timeout_cb, NULL);
1286                 break;
1287         case OACP_DELETE:
1288                 if (!(selected_object->props & OBJECT_DELETE)) {
1289                         ret = OACP_PROCEDURE_NOT_SUPPORTED;
1290                         goto fail;
1291                 }
1292                 snprintf(absolute_file_path, sizeof(absolute_file_path),
1293                                                 "%s%s", directory, selected_object->name);
1294
1295                 BT_DBG("absolute_file_path = [%s]", absolute_file_path);
1296
1297                 if (remove(absolute_file_path) != 0) {
1298                         BT_DBG("Error: unable to delete the file");
1299                         ret = OACP_OPERATION_FAILED;
1300                         goto fail;
1301                 }
1302
1303                 BT_DBG("File deleted successfully");
1304                 selected_object = NULL;
1305                 break;
1306         case OACP_CALC_CHECKSUM:
1307                 ret = OACP_OPCODE_NOT_SUPPORTED;
1308                 break;
1309         case OACP_EXECUTE:
1310                 if (!(selected_object->props & OBJECT_EXECUTE)) {
1311                         ret = OACP_PROCEDURE_NOT_SUPPORTED;
1312                         goto fail;
1313                 }
1314                 snprintf(absolute_file_path, sizeof(absolute_file_path),
1315                                         "file://%s%s", directory, selected_object->name);
1316
1317                 BT_DBG("absolute_file_path = [%s]", absolute_file_path);
1318
1319                 err = _bt_otp_send_launch_request(absolute_file_path);
1320                 if (err != BLUETOOTH_ERROR_NONE) {
1321                         BT_DBG("Error: unable to launch the file");
1322                         ret = OACP_OPERATION_FAILED;
1323                         goto fail;
1324                 }
1325
1326                 BT_DBG("Successfully launched the file");
1327                 break;
1328         case OACP_READ:
1329         case OACP_WRITE:
1330                 if (opcode == OACP_WRITE &&
1331                                 !(selected_object->props & OBJECT_WRITE)) {
1332                         ret = OACP_PROCEDURE_NOT_SUPPORTED;
1333                         goto fail;
1334                 }
1335
1336                 if (opcode == OACP_READ &&
1337                                 !(selected_object->props & OBJECT_READ)) {
1338                         ret = OACP_PROCEDURE_NOT_SUPPORTED;
1339                         goto fail;
1340                 }
1341
1342                 object_offset = (uint32_t)(value[4] & 0xFF) << 24 |
1343                                 (uint32_t)(value[3] & 0xFF) << 16 |
1344                                 (uint32_t)(value[2] & 0xFF) << 8  |
1345                                 (uint32_t)(value[1] & 0xFF);
1346                 length = (uint32_t)(value[8] & 0xFF) << 24 |
1347                         (uint32_t)(value[7] & 0xFF) << 16 |
1348                         (uint32_t)(value[6] & 0xFF) << 8  |
1349                         (uint32_t)(value[5] & 0xFF);
1350
1351                 if (opcode == OACP_WRITE)
1352                         mode = (uint8_t)value[9] & 0xFF;
1353
1354                 BT_INFO("Offset = %lu, Length = %lu", object_offset, length, mode);
1355
1356                 if (oacp_op) {
1357                         if (otc_connection_status) {
1358                                 /* Read/Write operation already going on. */
1359                                 ret = OACP_OBJECT_LOCKED;
1360                                 goto fail;
1361                         }
1362                         _bt_otp_free_oacp_op();
1363                 }
1364
1365                 oacp_op = g_malloc0(sizeof(struct oacp_operation));
1366                 oacp_op->offset = object_offset;
1367                 oacp_op->length = length;
1368                 oacp_op->remote_address = g_strdup(remote_addr);
1369                 oacp_op->mode = mode;
1370                 oacp_op->opcode = opcode;
1371                 oacp_op->length_sofar = 0;
1372                 oacp_op->fp = NULL;
1373
1374                 err = _bt_otp_open_otc_and_listen(remote_addr, "ListenOtc");
1375                 if (err != BLUETOOTH_ERROR_NONE) {
1376                         ret = OACP_CHANNEL_UNAVAILABLE;
1377                         _bt_otp_free_oacp_op();
1378                         goto fail;
1379                 }
1380                 break;
1381         case OACP_ABORT:
1382                 ret = OACP_OPCODE_NOT_SUPPORTED;
1383                 break;
1384         default:
1385                 ret = OACP_OPCODE_NOT_SUPPORTED;
1386                 break;
1387         }
1388 fail:
1389         info->resp_opcode = OACP_RESPONSE;
1390         info->req_opcode = opcode;
1391         info->result_code = ret;
1392         info->resp_param = NULL;
1393         return BLUETOOTH_ERROR_NONE;
1394 }
1395
1396 int _bt_otp_uuid_convert_string_to_hex(char *uuid, char *value)
1397 {
1398         int len, uuid_len;
1399         uint32_t data0, data4;
1400         uint16_t data1, data2, data3, data5;
1401
1402         if (!uuid) {
1403                 BT_ERR("Object Type UUID NULL");
1404                 return 0;
1405         }
1406
1407         len = strlen(uuid);
1408
1409         switch (len) {
1410         case 4:
1411                 /* UUID 16bits */
1412                 sscanf(uuid, "%04hx", &data1);
1413                 data1 = htons(data1);
1414                 memcpy(value, &data1, 2);
1415                 uuid_len = 2;
1416                 break;
1417
1418         case 8:
1419                 /* UUID 32bits */
1420                 sscanf(uuid, "%08x", &data0);
1421                 data0 = htonl(data0);
1422                 memcpy(value, &data0, 4);
1423                 uuid_len = 4;
1424                 break;
1425
1426         case 36:
1427                 /* UUID 128bits */
1428                 sscanf(uuid, "%08x-%04hx-%04hx-%04hx-%08x%04hx",
1429                         &data0, &data1, &data2,
1430                         &data3, &data4, &data5);
1431
1432                 data0 = htonl(data0);
1433                 data1 = htons(data1);
1434                 data2 = htons(data2);
1435                 data3 = htons(data3);
1436                 data4 = htonl(data4);
1437                 data5 = htons(data5);
1438
1439                 memcpy(value, &data0, 4);
1440                 memcpy(value+4, &data1, 2);
1441                 memcpy(value+6, &data2, 2);
1442                 memcpy(value+8, &data3, 2);
1443                 memcpy(value+10, &data4, 4);
1444                 memcpy(value+14, &data5, 2);
1445                 uuid_len = 16;
1446                 break;
1447
1448         default:
1449                 uuid_len = 0;
1450         }
1451
1452         return uuid_len;
1453 }
1454
1455 void convert_to_hex(struct object_metadata *object, char *metadata, char *value)
1456 {
1457         struct tm fc_tm;
1458
1459         BT_DBG("Metadata : %s", metadata);
1460
1461         memset(value, 0, 16);
1462
1463         if (!g_strcmp0(metadata, "size")) {
1464
1465                 value[3] = (object->curr_size >> 24) & 0xFF;
1466                 value[2] = (object->curr_size >> 16) & 0xFF;
1467                 value[1] = (object->curr_size >> 8) & 0xFF;
1468                 value[0] = object->curr_size & 0xFF;
1469
1470                 value[7] = (object->alloc_size >> 24) & 0xFF;
1471                 value[6] = (object->alloc_size >> 16) & 0xFF;
1472                 value[5] = (object->alloc_size >> 8) & 0xFF;
1473                 value[4] = object->alloc_size & 0xFF;
1474
1475         } else if (!g_strcmp0(metadata, "date")) {
1476
1477                 localtime_r(&(object->first_created), &fc_tm);
1478
1479                 value[1] = ((fc_tm.tm_year+1900) >> 8) & 0xFF;
1480                 value[0] = (fc_tm.tm_year+1900) & 0xFF;
1481                 value[2] = (fc_tm.tm_mon+1) & 0xFF;
1482                 value[3] = fc_tm.tm_mday & 0xFF;
1483                 value[4] = fc_tm.tm_hour & 0xFF;
1484                 value[5] = fc_tm.tm_min & 0xFF;
1485                 value[6] = fc_tm.tm_sec & 0xFF;
1486
1487         } else if (!g_strcmp0(metadata, "id")) {
1488
1489                 value[5] = (object->id >> 48) & 0xFF;
1490                 value[4] = (object->id >> 32) & 0xFF;
1491                 value[3] = (object->id >> 24) & 0xFF;
1492                 value[2] = (object->id >> 16) & 0xFF;
1493                 value[1] = (object->id >> 8) & 0xFF;
1494                 value[0] = object->id & 0xFF;
1495
1496         } else if (!g_strcmp0(metadata, "props")) {
1497                 value[3] = (object->props >> 24) & 0xFF;
1498                 value[2] = (object->props >> 16) & 0xFF;
1499                 value[1] = (object->props >> 8) & 0xFF;
1500                 value[0] = object->props & 0xFF;
1501         }
1502 }
1503
1504 void update_obj_metadata_charc_value(struct object_metadata *object)
1505 {
1506         /* Value can be of maximum 16 bytes */
1507         char value[16];
1508         int uuid_len;
1509
1510         _bt_otp_set_char_value(otp_object_name_obj_path, object->name,
1511                                                         strlen(object->name));
1512
1513         uuid_len = _bt_otp_uuid_convert_string_to_hex(object->type, value);
1514         _bt_otp_set_char_value(otp_object_type_obj_path, value, uuid_len);
1515
1516         convert_to_hex(object, "size", value);
1517         _bt_otp_set_char_value(otp_object_size_obj_path, value, 8);
1518
1519         convert_to_hex(object, "date", value);
1520         _bt_otp_set_char_value(otp_object_first_created_obj_path, value, 7);
1521         _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, 7);
1522
1523         /* Object ID is optonal for single object server */
1524         if (mutiple_obj_support) {
1525                 convert_to_hex(object, "id", value);
1526                 _bt_otp_set_char_value(otp_object_id_obj_path, value, 6);
1527         }
1528
1529         convert_to_hex(object, "props", value);
1530         _bt_otp_set_char_value(otp_object_prop_obj_path, value, 4);
1531 }
1532
1533 struct object_metadata *_bt_otp_client_find_object(GSList *list, uint64_t id, guint *index)
1534 {
1535         GSList *l;
1536         struct object_metadata *info;
1537
1538         for (l = list; l; l = g_slist_next(l)) {
1539                 (*index)++;
1540                 info = l->data;
1541
1542                 if (info && (info->id == id))
1543                         return info;
1544         }
1545         return NULL;
1546 }
1547
1548 int _bt_otp_olcp_write_cb(char *value, int len, int offset,
1549                                         struct indicate_info *info)
1550 {
1551         int ret = OLCP_SUCCESS;
1552         int opcode = value[0];
1553         struct object_metadata *object;
1554         uint64_t object_id;
1555         guint index = 0;
1556
1557         BT_INFO("OLCP Opcode 0x%d", opcode);
1558
1559         if (!otp_object_list) {
1560                 ret = OLCP_NO_OBJ;
1561                 goto fail;
1562         }
1563
1564         switch (opcode) {
1565         case OLCP_FIRST:
1566                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
1567                 if (!object) {
1568                         ret = OLCP_OUT_OF_BOUNDS;
1569                         goto fail;
1570                 }
1571                 update_obj_metadata_charc_value(object);
1572                 selected_object = object;
1573                 curr_obj_index = 0;
1574                 break;
1575         case OLCP_LAST:
1576                 len = g_slist_length(otp_object_list);
1577                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, len-1);
1578                 if (!object) {
1579                         ret = OLCP_OUT_OF_BOUNDS;
1580                         goto fail;
1581                 }
1582                 update_obj_metadata_charc_value(object);
1583                 selected_object = object;
1584                 curr_obj_index = len-1;
1585                 break;
1586         case OLCP_PREVIOUS:
1587                 if (curr_obj_index == 0) {
1588                         ret = OLCP_OUT_OF_BOUNDS;
1589                         goto fail;
1590                 }
1591                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index-1);
1592                 if (!object) {
1593                         ret = OLCP_OUT_OF_BOUNDS;
1594                         goto fail;
1595                 }
1596                 update_obj_metadata_charc_value(object);
1597                 selected_object = object;
1598                 curr_obj_index -= 1;
1599                 break;
1600         case OLCP_NEXT:
1601                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index+1);
1602                 if (!object) {
1603                         ret = OLCP_OUT_OF_BOUNDS;
1604                         goto fail;
1605                 }
1606                 update_obj_metadata_charc_value(object);
1607                 selected_object = object;
1608                 curr_obj_index += 1;
1609                 break;
1610         case OLCP_GOTO:
1611                 object_id = (uint64_t)(value[6] & 0xFF) << 40 |
1612                                 (uint64_t)(value[5] & 0xFF) << 32 |
1613                                 (uint64_t)(value[4] & 0xFF) << 24 |
1614                                 (uint64_t)(value[3] & 0xFF) << 16 |
1615                                 (uint64_t)(value[2] & 0xFF) << 8  |
1616                                 (uint64_t)(value[1] & 0xFF);
1617                 BT_INFO("Object ID [%llu]", object_id);
1618                 if (selected_object && selected_object->id == object_id)
1619                         goto fail;
1620
1621                 object = _bt_otp_client_find_object(otp_object_list, object_id, &index);
1622                 if (!object) {
1623                         ret = OLCP_OJECT_ID_NOT_FOUND;
1624                         goto fail;
1625                 }
1626                 update_obj_metadata_charc_value(object);
1627                 selected_object = object;
1628                 curr_obj_index = index - 1;
1629                 break;
1630         case OLCP_ORDER:
1631         case OLCP_REQ_NO_OBJ:
1632         case OLCP_CLEAR_MARKING:
1633         default:
1634                 ret = OLCP_OPCODE_NOT_SUPPORTED;
1635                 break;
1636         }
1637 fail:
1638         info->resp_opcode = OLCP_RESPONSE;
1639         info->req_opcode = opcode;
1640         info->result_code = ret;
1641         info->resp_param = NULL;
1642         return BLUETOOTH_ERROR_NONE;
1643 }
1644
1645 int _bt_otp_obj_name_write_cb(char *value, int len)
1646 {
1647         struct object_metadata *object;
1648         char *filename;
1649         char new_abs_filepath[BT_FILE_PATH_MAX_LEN] = {0, };
1650         char old_abs_filepath[BT_FILE_PATH_MAX_LEN] = {0, };
1651         int ret = BLUETOOTH_ERROR_NONE;
1652
1653         object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index);
1654         if (!object)
1655                 return BLUETOOTH_ATT_ERROR_WRITE_REQUEST_REJECTED       ;
1656
1657         filename = g_strndup(value, len);
1658         snprintf(new_abs_filepath, strlen(new_abs_filepath), "%s%s",
1659                         directory, filename);
1660
1661         snprintf(old_abs_filepath, strlen(old_abs_filepath), "%s%s",
1662                         directory, object->name);
1663
1664         if (rename(old_abs_filepath, new_abs_filepath)) {
1665                 ret = BLUETOOTH_ATT_ERROR_OBJECT_NAME_EXISTS;
1666                 goto fail;
1667         }
1668
1669         memcpy(object->name, value, len);
1670         _bt_otp_set_char_value(otp_object_name_obj_path, value, len);
1671
1672         if (oacp_create_timeout_id > 0)
1673                 g_source_remove(oacp_create_timeout_id);
1674
1675 fail:
1676         g_free(filename);
1677         return ret;
1678 }
1679
1680 int _bt_otp_obj_first_created_write_cb(char *value, int len)
1681 {
1682         struct object_metadata *object;
1683         struct tm tm = {0};
1684         uint16_t year;
1685
1686         object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index);
1687         if (!object)
1688                 return BLUETOOTH_ATT_ERROR_WRITE_REQUEST_REJECTED;
1689
1690         year = (uint16_t)(value[1] & 0xFF) << 8 |
1691                         (uint16_t)(value[0] & 0xFF);
1692         tm.tm_year = year-1900;
1693         tm.tm_mon = value[2] & 0xFF;
1694         tm.tm_mon = tm.tm_mon-1;
1695         tm.tm_mday = value[3] & 0xFF;
1696         tm.tm_hour = value[4] & 0xFF;
1697         tm.tm_min = value[5] & 0xFF;
1698         tm.tm_sec = value[6] & 0xFF;
1699
1700         object->first_created = mktime(&tm);
1701         _bt_otp_set_char_value(otp_object_first_created_obj_path, value, len);
1702
1703         return BLUETOOTH_ERROR_NONE;
1704 }
1705
1706 int _bt_otp_obj_last_modified_write_cb(char *value, int len)
1707 {
1708         struct object_metadata *object;
1709         struct tm tm = {0};
1710         uint16_t year;
1711
1712         object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index);
1713         if (!object)
1714                 return BLUETOOTH_ATT_ERROR_WRITE_REQUEST_REJECTED;
1715
1716         year = (uint16_t)(value[1] & 0xFF) << 8 |
1717                         (uint16_t)(value[0] & 0xFF);
1718         tm.tm_year = year-1900;
1719         tm.tm_mon = value[2] & 0xFF;
1720         tm.tm_mon = tm.tm_mon-1;
1721         tm.tm_mday = value[3] & 0xFF;
1722         tm.tm_hour = value[4] & 0xFF;
1723         tm.tm_min = value[5] & 0xFF;
1724         tm.tm_sec = value[6] & 0xFF;
1725
1726         object->last_modified = mktime(&tm);
1727         _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, len);
1728
1729         return BLUETOOTH_ERROR_NONE;
1730 }
1731
1732 int _bt_otp_obj_props_write_cb(char *value, int len)
1733 {
1734         struct object_metadata *object;
1735         uint32_t props;
1736
1737         /* Any attempt to write RFU bits is error */
1738         if (value[1] || value[2] || value[3])
1739                 return BLUETOOTH_ATT_ERROR_WRITE_REQUEST_REJECTED;
1740
1741         object = (struct object_metadata *) g_slist_nth_data(otp_object_list, curr_obj_index);
1742         if (!object)
1743                 return BLUETOOTH_ATT_ERROR_WRITE_REQUEST_REJECTED;
1744
1745         props = (uint32_t)(value[3] & 0xFF) << 24       |
1746                         (uint32_t)(value[2] & 0xFF) << 16       |
1747                         (uint32_t)(value[1] & 0xFF) << 8        |
1748                         (uint32_t)(value[0] & 0xFF);
1749
1750         object->props = props;
1751         _bt_otp_set_char_value(otp_object_prop_obj_path, value, len);
1752
1753         return BLUETOOTH_ERROR_NONE;
1754 }
1755
1756 static struct otp_char_info *otp_get_char_value(const char *path)
1757 {
1758         GSList *tmp = NULL;
1759
1760         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
1761                 if (tmp->data) {
1762                         struct otp_char_info *char_info = tmp->data;
1763                         if (!g_strcmp0(char_info->char_path, path))
1764                                 return char_info;
1765                 }
1766         }
1767
1768         return NULL;
1769 }
1770
1771 int _bt_otp_read_cb(const char *obj_path, char **value, int *len)
1772 {
1773         struct otp_char_info *info = NULL;
1774
1775         if (!obj_path) {
1776                 BT_ERR("Wrong Obj path");
1777                 return BLUETOOTH_ERROR_INTERNAL;
1778         }
1779
1780         if (g_strcmp0(obj_path, otp_feature_obj_path)) {
1781                 if (!selected_object) {
1782                         return BLUETOOTH_ATT_ERROR_OBJECT_NOT_SELECTED;
1783                 }
1784         }
1785
1786         info = otp_get_char_value(obj_path);
1787         if (info) {
1788                 if (info->char_value == NULL || info->value_length == 0)
1789                         return BLUETOOTH_ERROR_INTERNAL;
1790
1791                 *len = info->value_length;
1792                 *value = (char *)malloc(sizeof(char)*(*len));
1793                 memcpy(*value, info->char_value, *len);
1794
1795                 return BLUETOOTH_ERROR_NONE;
1796         } else {
1797                 return BLUETOOTH_ERROR_INTERNAL;
1798         }
1799 }
1800
1801 static void _otp_convert_address_to_hex(bluetooth_device_address_t *addr_hex,
1802                                                         const char *addr_str)
1803 {
1804         int i = 0;
1805         unsigned int addr[BLUETOOTH_ADDRESS_LENGTH] = { 0, };
1806
1807         if (addr_str == NULL || addr_str[0] == '\0')
1808                 return;
1809
1810         i = sscanf(addr_str, "%X:%X:%X:%X:%X:%X", &addr[0], &addr[1],
1811                                 &addr[2], &addr[3], &addr[4], &addr[5]);
1812         if (i != BLUETOOTH_ADDRESS_LENGTH)
1813                 BT_ERR("Invalid format string - [%s]", addr_str);
1814
1815         for (i = 0; i < BLUETOOTH_ADDRESS_LENGTH; i++)
1816                 addr_hex->addr[i] = (unsigned char)addr[i];
1817 }
1818
1819 static void _bt_otp_send_indication(const char *obj_path,
1820                                 struct indicate_info *info,
1821                                 bluetooth_device_address_t *remote_address)
1822 {
1823         int ret = BLUETOOTH_ERROR_NONE;
1824         char value[7] = {0x00};
1825         int length = OTP_INDICATION_LEN_WITHOUT_RESP;
1826
1827         BT_DBG("");
1828
1829         value[0] = info->resp_opcode & 0xFF;
1830         value[1] = info->req_opcode & 0xFF;
1831         value[2] = info->result_code & 0xFF;
1832         if (info->resp_param) {
1833                 value[6] = info->resp_param[3] & 0xFF;
1834                 value[5] = info->resp_param[4] & 0xFF;
1835                 value[4] = info->resp_param[5] & 0xFF;
1836                 value[3] = info->resp_param[6] & 0xFF;
1837                 length = OTP_INDICATION_LEN_WITH_RESP;
1838         }
1839
1840         BT_DBG("Opcode: %d", value[1]);
1841
1842         /* Store the status value */
1843         _bt_otp_set_char_value(obj_path, value, length);
1844
1845         /* Send indication */
1846         ret = bluetooth_gatt_server_set_notification(obj_path, remote_address);
1847         if (ret != BLUETOOTH_ERROR_NONE) {
1848                 BT_ERR("_bt_otp_send_control_point_indication failed");
1849                 return;
1850         }
1851         ret = bluetooth_gatt_update_characteristic(obj_path, value, length);
1852         if (ret != BLUETOOTH_ERROR_NONE) {
1853                 BT_ERR("_bt_otp_send_control_point_indication failed");
1854                 return;
1855         }
1856 }
1857
1858 void _bt_otp_gatt_char_property_changed_event(GVariant *msg,
1859                                 const char *path)
1860 {
1861         int result = BLUETOOTH_ERROR_NONE;
1862         GVariantIter value_iter;
1863         const char *property = NULL;
1864         const char *char_path = NULL;
1865         const char *svc_handle = NULL;
1866         GVariant *var = NULL;
1867         GVariant *val = NULL;
1868         g_variant_iter_init(&value_iter, msg);
1869
1870         while ((g_variant_iter_loop(&value_iter, "{sv}", &property, &var))) {
1871
1872                 if (property == NULL) {
1873                         BT_ERR("Property NULL");
1874                         return;
1875                 }
1876
1877                 if (!g_strcmp0(property, "WriteValue")) {
1878                         int len = 0;
1879                         BT_INFO("WriteValue");
1880                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1881
1882                         if (var) {
1883                                 bluetooth_device_address_t addr_hex = { {0,} };
1884                                 gchar *addr = NULL;
1885                                 guint8 req_id = 1;
1886                                 guint16 offset = 0;
1887                                 char *value = NULL;
1888                                 struct indicate_info info;
1889
1890                                 g_variant_get(var, "(&s&s&syq@ay)",
1891                                                 &char_path, &svc_handle,
1892                                                 &addr, &req_id, &offset, &val);
1893
1894                                 len = g_variant_get_size(val);
1895
1896                                 BT_DBG("Len = %d, BT_ADDR = %s", len, addr);
1897
1898                                 value = (char *) g_variant_get_data(val);
1899                                 _otp_convert_address_to_hex(&addr_hex, addr);
1900
1901                                 if (len != 0) {
1902                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1903                                                 if (!OACP_indicate)
1904                                                         result = BLUETOOTH_ATT_ERROR_CCCD_IMPROPERLY_CONFIGURED;
1905                                                 else
1906                                                         result = _bt_otp_oacp_write_cb(value, len, offset, addr, &info);
1907                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1908                                                 if (!OLCP_indicate)
1909                                                         result = BLUETOOTH_ATT_ERROR_CCCD_IMPROPERLY_CONFIGURED;
1910                                                 else
1911                                                         result = _bt_otp_olcp_write_cb(value, len, offset, &info);
1912                                         } else if (!g_strcmp0(char_path, otp_object_name_obj_path)) {
1913                                                 result = _bt_otp_obj_name_write_cb(value, len);
1914                                         } else if (!g_strcmp0(char_path, otp_object_first_created_obj_path)) {
1915                                                 result = _bt_otp_obj_first_created_write_cb(value, len);
1916                                         } else if (!g_strcmp0(char_path, otp_object_last_modified_obj_path)) {
1917                                                 result = _bt_otp_obj_last_modified_write_cb(value, len);
1918                                         } else if (!g_strcmp0(char_path, otp_object_prop_obj_path)) {
1919                                                 result = _bt_otp_obj_props_write_cb(value, len);
1920                                         } else {
1921                                                 BT_ERR("Wrong Object Path %s", char_path);
1922                                                 result = BLUETOOTH_ERROR_INTERNAL;
1923                                         }
1924                                         bluetooth_gatt_send_response(req_id,
1925                                         BLUETOOTH_GATT_ATT_REQUEST_TYPE_WRITE,
1926                                                         result, 0, NULL, 0);
1927
1928                                         /* Send indication for CPs */
1929                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1930                                                 if (OACP_indicate) {
1931                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1932                                                 }
1933                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1934                                                 if (OLCP_indicate) {
1935                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1936                                                 }
1937                                         }
1938                                 } else {
1939                                         BT_ERR("Array Len 0");
1940                                 }
1941                         } else {
1942                                 BT_ERR("var==NULL");
1943                         }
1944                 } else if (!g_strcmp0(property, "ReadValue")) {
1945                         gchar *addr = NULL;
1946                         guint8 req_id = 1;
1947                         guint16 offset = 0;
1948                         char *value = NULL;
1949                         int len = 0;
1950                         result = BLUETOOTH_ERROR_NONE;
1951
1952                         BT_INFO("ReadValue");
1953                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1954
1955                         g_variant_get(var, "(&s&s&syq)", &char_path,
1956                                         &svc_handle, &addr, &req_id, &offset);
1957
1958                         result = _bt_otp_read_cb(char_path, &value, &len);
1959
1960                         if (result != BLUETOOTH_ERROR_NONE) {
1961                                 BT_ERR("ReadValue failed %s", char_path);
1962                                 bluetooth_gatt_send_response(req_id,
1963                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1964                                                 result, offset, NULL, 0);
1965                         } else {
1966                                 bluetooth_gatt_send_response(req_id,
1967                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1968                                                 result, offset, value, len);
1969                                 if (value)
1970                                         g_free(value);
1971                         }
1972                 } else if (!g_strcmp0(property, "NotificationStateChanged")) {
1973                         gboolean indicate = FALSE;
1974
1975                         g_variant_get(var, "(&s&sb)", &char_path,
1976                                                 &svc_handle, &indicate);
1977
1978                         BT_INFO("%s : [%s]", property,
1979                                 indicate ? "StartNotify" : "StopNotify");
1980                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1981
1982                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1983                                 OACP_indicate = indicate;
1984                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1985                                 OLCP_indicate = indicate;
1986                         }
1987                 }
1988         }
1989         return;
1990 }
1991
1992 void _bt_otp_property_event_filter(GDBusConnection *connection,
1993                                         const gchar *sender_name,
1994                                         const gchar *object_path,
1995                                         const gchar *interface_name,
1996                                         const gchar *signal_name,
1997                                         GVariant *parameters,
1998                                         gpointer user_data)
1999 {
2000         GVariant *value;
2001
2002         if (signal_name == NULL) {
2003                 BT_ERR("Wrong Signal");
2004                 return;
2005         }
2006
2007         if (g_strcmp0(signal_name, PROPERTIES_CHANGED) == 0) {
2008
2009                 g_variant_get(parameters, "(@a{sv}@as)", &value, NULL);
2010                 _bt_otp_gatt_char_property_changed_event(value, object_path);
2011         }
2012 }
2013
2014 void _bt_otp_adapter_event_filter(GDBusConnection *connection,
2015                                         const gchar *sender_name,
2016                                         const gchar *object_path,
2017                                         const gchar *interface_name,
2018                                         const gchar *signal_name,
2019                                         GVariant *parameters,
2020                                         gpointer user_data)
2021 {
2022         if (signal_name == NULL) {
2023                 BT_ERR("Wrong Signal");
2024                 return;
2025         }
2026
2027         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
2028
2029         if (g_strcmp0(interface_name, BT_OTP_INTERFACE_NAME) == 0) {
2030                 if (strcasecmp(signal_name, BLE_DISABLED) == 0) {
2031                         _bt_otp_exit();
2032                 }
2033         }
2034 }
2035
2036 void _bt_otc_disconnected_cb(GDBusConnection *connection,
2037                                         const gchar *sender_name,
2038                                         const gchar *object_path,
2039                                         const gchar *interface_name,
2040                                         const gchar *signal_name,
2041                                         GVariant *parameters,
2042                                         gpointer user_data)
2043 {
2044         if (signal_name == NULL) {
2045                 BT_ERR("Wrong Signal");
2046                 return;
2047         }
2048
2049         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
2050
2051         if (g_strcmp0(interface_name, BT_DEVICE_INTERFACE) == 0) {
2052                 if (strcasecmp(signal_name, OTC_DISCONNECTED) == 0) {
2053                         BT_DBG("OTC Channel Disconnected dev_path[%s]",
2054                                                                 object_path);
2055                         otc_connection_status = FALSE;
2056                         _bt_otp_free_oacp_op();
2057                 }
2058         }
2059 }
2060
2061 int _bt_otp_init_event_receiver()
2062 {
2063         BT_DBG("+");
2064         GError *error = NULL;
2065
2066         if (conn == NULL) {
2067                 conn =  g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
2068                 if (error != NULL) {
2069                         BT_ERR("ERROR: Can't get on system bus [%s]",
2070                                                         error->message);
2071                         g_clear_error(&error);
2072                 }
2073         }
2074
2075         property_sub_id = g_dbus_connection_signal_subscribe(conn,
2076                                 NULL,
2077                                 BT_OTP_INTERFACE_NAME,
2078                                 PROPERTIES_CHANGED,
2079                                 BT_OTP_OBJECT_PATH, NULL, 0,
2080                                 _bt_otp_property_event_filter,
2081                                 NULL, NULL);
2082
2083         adapter_sub_id = g_dbus_connection_signal_subscribe(conn,
2084                                 NULL,
2085                                 BT_OTP_INTERFACE_NAME,
2086                                 BLE_DISABLED,
2087                                 BT_OTP_OBJECT_PATH, NULL, 0,
2088                                 _bt_otp_adapter_event_filter,
2089                                 NULL, NULL);
2090
2091         device_sub_id = g_dbus_connection_signal_subscribe(conn,
2092                                         NULL, BT_DEVICE_INTERFACE,
2093                                         OTC_DISCONNECTED, NULL, NULL, 0,
2094                                         _bt_otc_disconnected_cb,
2095                                         NULL, NULL);
2096
2097         BT_DBG("-");
2098         return 0;
2099 }
2100
2101 void _bt_otp_deinit_event_receiver(void)
2102 {
2103         BT_DBG("+");
2104
2105         g_dbus_connection_signal_unsubscribe(conn, property_sub_id);
2106         g_dbus_connection_signal_unsubscribe(conn, adapter_sub_id);
2107         g_dbus_connection_signal_unsubscribe(conn, device_sub_id);
2108         conn = NULL;
2109
2110         BT_DBG("-");
2111 }
2112
2113 static void _bt_otp_sig_handler(int sig)
2114 {
2115         BT_DBG("+");
2116         switch (sig) {
2117         case SIGTERM:
2118                 BT_DBG("caught signal - sigterm\n");
2119                 break;
2120         case SIGINT:
2121                 BT_DBG("caught signal - sigint\n");
2122                 break;
2123         case SIGKILL:
2124                 BT_DBG("caught signal - sigkill\n");
2125                 break;
2126         default:
2127                 BT_DBG("caught signal %d and ignored\n", sig);
2128                 break;
2129         }
2130         BT_DBG("-");
2131 }
2132
2133 /* OTP Service Main loop */
2134 int main(void)
2135 {
2136         struct sigaction sa;
2137         BT_ERR("Starting the bt-otp daemon");
2138
2139         memset(&sa, 0, sizeof(sa));
2140         sa.sa_handler = _bt_otp_sig_handler;
2141         sa.sa_flags = SA_SIGINFO;
2142         sigaction(SIGINT, &sa, NULL);
2143         sigaction(SIGTERM, &sa, NULL);
2144         sigaction(SIGKILL, &sa, NULL);
2145
2146         if (_bt_otp_register_interface() != BLUETOOTH_ERROR_NONE) {
2147                 BT_ERR("Fail to register otp service");
2148                 return -4;
2149         }
2150
2151         if (_bt_otp_init_event_receiver() != BLUETOOTH_ERROR_NONE) {
2152                 BT_ERR("Fail to init event reciever");
2153                 return -5;
2154         }
2155
2156         main_loop = g_main_loop_new(NULL, FALSE);
2157
2158         g_main_loop_run(main_loop);
2159
2160         BT_DBG("g_main_loop_quit called!");
2161
2162         if (main_loop != NULL) {
2163                 g_main_loop_unref(main_loop);
2164         }
2165
2166         return 0;
2167 }