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