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