7693b129740b1ff10c0c64f66564a87768f2fa92
[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 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                 g_dir_close(dir);
706
707                 if (!list) {
708                         BT_DBG("No object found in given directory");
709                         status = BLUETOOTH_ERROR_NO_OBJECTS_FOUND;
710                         goto fail;
711                 }
712
713                 if (g_slist_length(list) > 1)
714                         mutiple_obj_support = true;
715
716                 for (l = list; l != NULL; l = l->next) {
717                         if (!l->data) continue;
718                         snprintf(absolute_path, BT_FILE_PATH_MAX_LEN, "%s%s", directory,
719                                                         (char *)l->data);
720
721                         BT_INFO("filename: %s, absoulte_path: %s",
722                                         (char *)l->data, absolute_path);
723
724                         if (stat(absolute_path, &st) == -1) {
725                                 BT_INFO("stat failed: (%d)\n", errno);
726                                 continue;
727                         }
728
729                         object = g_new0(struct object_metadata, 1);
730
731                         object->name = g_strdup((const gchar *)l->data);
732                         object->type = g_strdup(UNSUPPORTED_OBJECT_TYPE_UUID);
733                         object->first_created = st.st_ctime;
734                         object->last_modified = st.st_ctime;
735                         object->curr_size = (uint32_t) st.st_size;
736                         object->alloc_size = (uint32_t) st.st_size;
737                         object->id = object_id;
738                         object->props = OBJECT_READ | OBJECT_WRITE |
739                                         OBJECT_EXECUTE | OBJECT_DELETE;
740
741                         otp_object_list = g_slist_append(otp_object_list,
742                                                                 object);
743
744                         object_id++;
745                 }
746
747                 BT_DBG("preparing");
748                 if (_bt_otp_prepare_ots() != BLUETOOTH_ERROR_NONE) {
749                         BT_ERR("Fail to prepare OTP Proxy");
750                         status = BLUETOOTH_ERROR_INTERNAL;
751                         goto fail;
752                 }
753
754                 /* If single object is supported, make that as
755                  * selected object and update the metadata for the same.
756                  */
757                 if (!mutiple_obj_support) {
758                         BT_INFO("Server supports single object");
759                         selected_object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
760                         if (selected_object)
761                                 update_obj_metadata_charc_value(selected_object);
762                 }
763
764                 BT_DBG("advertsing");
765                 if (_bt_otp_set_advertising_data() != BLUETOOTH_ERROR_NONE) {
766                         BT_ERR("Fail to set advertising data");
767                         status = BLUETOOTH_ERROR_INTERNAL;
768                         goto fail;
769                 }
770 fail:
771                 g_dbus_method_invocation_return_value(invocation,
772                                                 g_variant_new("(i)", status));
773
774         } else if (g_strcmp0(method_name, "disable") == 0) {
775                 g_dbus_method_invocation_return_value(invocation,
776                                                 g_variant_new("(i)", status));
777                 _bt_otp_exit();
778
779         } else if (g_strcmp0(method_name, "NewConnection") == 0) {
780                 int index;
781                 GDBusMessage *msg;
782                 GUnixFDList *fd_list;
783                 char *dev_path;
784                 char address[BT_ADDRESS_STRING_SIZE] = { 0 };
785                 int fd;
786
787                 g_variant_get(parameters, "(oh)", &dev_path, &index);
788
789                 msg = g_dbus_method_invocation_get_message(invocation);
790                 fd_list = g_dbus_message_get_unix_fd_list(msg);
791                 if (fd_list == NULL) {
792                         BT_ERR("fd_list is NULL");
793                         return;
794                 }
795
796                 fd = g_unix_fd_list_get(fd_list, index, NULL);
797                 if (fd == -1) {
798                         BT_ERR("Invalid fd return");
799                         return;
800                 }
801
802                 _bt_convert_device_path_to_address(dev_path, address);
803
804                 BT_INFO("OTC Connected fd: %d, address %s", fd, address);
805                 otc_connection_status = TRUE;
806                 if (oacp_op) {
807                         oacp_op->fd = fd;
808
809                         if (oacp_op->opcode == OACP_READ)
810                                 _bt_otp_start_write_on_fd();
811                         else if (oacp_op->opcode == OACP_WRITE)
812                                 _bt_otp_start_read_on_fd();
813                 }
814                 g_dbus_method_invocation_return_value(invocation, NULL);
815         }
816         BT_DBG("-");
817 }
818
819 static const GDBusInterfaceVTable otp_method_table = {
820         _bt_otp_method,
821         NULL,
822         NULL,
823 };
824
825 static void _bt_otp_on_bus_acquired(GDBusConnection *connection,
826                                 const gchar *name, gpointer user_data)
827 {
828         guint object_id;
829         GError *error = NULL;
830
831         BT_DBG("+");
832
833         g_conn = connection;
834
835         object_id = g_dbus_connection_register_object(connection,
836                                                 BT_OTP_OBJECT_PATH,
837                                                 otp_node_info->interfaces[0],
838                                                 &otp_method_table,
839                                                 NULL, NULL, &error);
840         if (object_id == 0) {
841                 BT_ERR("Failed to register method table: %s", error->message);
842                 g_error_free(error);
843                 g_dbus_node_info_unref(otp_node_info);
844         }
845
846         BT_DBG("-");
847 }
848
849 static void _bt_otp_on_name_acquired(GDBusConnection *connection,
850                                         const gchar     *name,
851                                         gpointer user_data)
852 {
853         BT_DBG("");
854 }
855
856 static void _bt_otp_on_name_lost(GDBusConnection *connection,
857                                 const gchar     *name,
858                                 gpointer user_data)
859 {
860         BT_DBG("");
861         g_object_unref(g_conn);
862         g_conn = NULL;
863         g_dbus_node_info_unref(otp_node_info);
864         g_bus_unown_name(g_owner_id);
865 }
866
867 int _bt_otp_register_interface(void)
868 {
869         BT_DBG("+");
870         GError *error = NULL;
871         guint owner_id;
872
873         otp_node_info = g_dbus_node_info_new_for_xml(otp_introspection_xml, &error);
874         if (!otp_node_info) {
875                 BT_ERR("Failed to install: %s", error->message);
876                 return BLUETOOTH_ERROR_INTERNAL;
877         }
878
879         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
880                                 BT_OTP_SERVICE_NAME,
881                                 G_BUS_NAME_OWNER_FLAGS_NONE,
882                                 _bt_otp_on_bus_acquired,
883                                 _bt_otp_on_name_acquired,
884                                 _bt_otp_on_name_lost,
885                                 NULL, NULL);
886         g_owner_id = owner_id;
887         BT_DBG("owner_id is [%d]\n", owner_id);
888
889         BT_DBG("-");
890         return BLUETOOTH_ERROR_NONE;
891 }
892
893 void _bt_otp_unregister_interface(void)
894 {
895         BT_DBG("+");
896
897         g_object_unref(g_conn);
898         g_conn = NULL;
899         g_dbus_node_info_unref(otp_node_info);
900         g_bus_unown_name(g_owner_id);
901
902         BT_DBG("-");
903         return;
904 }
905
906 void _bt_convert_device_path_to_address(const char *device_path,
907                                                 char *device_address)
908 {
909         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
910         char *dev_addr;
911
912         dev_addr = strstr(device_path, "dev_");
913         if (dev_addr != NULL) {
914                 char *pos = NULL;
915                 dev_addr += 4;
916                 g_strlcpy(address, dev_addr, sizeof(address));
917
918                 while ((pos = strchr(address, '_')) != NULL)
919                         *pos = ':';
920
921                 g_strlcpy(device_address, address, BT_ADDRESS_STRING_SIZE);
922         }
923 }
924
925 static char *__bt_extract_device_path(GVariantIter *iter, char *address)
926 {
927         char *object_path = NULL;
928         char device_address[BT_ADDRESS_STRING_SIZE] = { 0 };
929
930         /* Parse the signature: oa{sa{sv}}} */
931         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path,
932                         NULL)) {
933                 if (!object_path) {
934                         BT_ERR("Unable to get object path");
935                         return NULL;
936                 }
937                 _bt_convert_device_path_to_address(object_path, device_address);
938                 if (g_strcmp0(address, device_address) == 0)
939                         return g_strdup(object_path);
940
941         }
942
943         BT_ERR("Unable to get object path");
944         return NULL;
945 }
946
947 char *_bt_otp_get_device_object_path(char *address)
948 {
949         GError *err = NULL;
950         GDBusProxy *proxy = NULL;
951         GVariant *result = NULL;
952         GVariantIter *iter = NULL;
953         char *object_path = NULL;
954
955         proxy =  g_dbus_proxy_new_sync(conn,
956                         G_DBUS_PROXY_FLAGS_NONE, NULL,
957                         BT_BLUEZ_NAME,
958                         BT_MANAGER_PATH,
959                         BT_MANAGER_INTERFACE,
960                         NULL, &err);
961
962         if (!proxy) {
963                 BT_ERR("Unable to create proxy: %s", err->message);
964                 goto fail;
965         }
966
967         result = g_dbus_proxy_call_sync(proxy, "GetManagedObjects", NULL,
968                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
969         if (!result) {
970                 if (err != NULL)
971                         BT_ERR("Fail to get GetManagedObjects (Error: %s)", err->message);
972                 else
973                         BT_ERR("Fail to get GetManagedObjects");
974
975                 goto fail;
976         }
977
978         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
979         object_path = __bt_extract_device_path(iter, address);
980
981         g_variant_unref(result);
982         g_variant_iter_free(iter);
983
984 fail:
985         if (err)
986                 g_clear_error(&err);
987
988         if (proxy)
989                 g_object_unref(proxy);
990
991         return object_path;
992 }
993
994 int _bt_otp_open_otc_and_listen(char *address, char *method)
995 {
996         char *object_path;
997         GDBusProxy *device_proxy = NULL;
998         GVariant *result = NULL;
999         GError *error = NULL;
1000         int ret = BLUETOOTH_ERROR_NONE;
1001
1002         if (method == NULL)
1003                 return BLUETOOTH_ERROR_INTERNAL;
1004
1005         if (g_strcmp0(method, "ListenOtc") &&
1006                         g_strcmp0(method, "DisconnectOtc"))
1007                 return BLUETOOTH_ERROR_INTERNAL;
1008
1009         object_path = _bt_otp_get_device_object_path(address);
1010         if (object_path == NULL) {
1011                 ret = BLUETOOTH_ERROR_NOT_PAIRED;
1012                 goto fail;
1013         }
1014
1015         device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
1016                                         NULL, BT_BLUEZ_NAME, object_path,
1017                                         BT_DEVICE_INTERFACE,  NULL, NULL);
1018         if (device_proxy == NULL) {
1019                 ret = BLUETOOTH_ERROR_INTERNAL;
1020                 goto fail;
1021         }
1022
1023
1024         result = g_dbus_proxy_call_sync(device_proxy, method,
1025                                 NULL,
1026                                 G_DBUS_CALL_FLAGS_NONE,
1027                                 -1,
1028                                 NULL,
1029                                 &error);
1030         if (result == NULL) {
1031                 if (error != NULL) {
1032                         BT_ERR("Error occured in Proxy call [%s]\n", error->message);
1033                         g_error_free(error);
1034                 }
1035                 ret = BLUETOOTH_ERROR_INTERNAL;
1036         }
1037 fail:
1038         if (object_path)
1039                 g_free(object_path);
1040         if (result)
1041                 g_variant_unref(result);
1042         if (device_proxy)
1043                 g_object_unref(device_proxy);
1044         return ret;
1045 }
1046
1047 static bool __bt_oacp_create_timeout_cb(gpointer user_data)
1048 {
1049         /* Delete the EMPTY object */
1050         BT_INFO("+");
1051         _bt_otp_restore_old_object();
1052         return FALSE;
1053 }
1054
1055 static void _bt_otp_free_oacp_op()
1056 {
1057         if (timeout_id > 0) {
1058                 g_source_remove(timeout_id);
1059                 timeout_id = 0;
1060         }
1061
1062         if (oacp_op) {
1063                 g_free(oacp_op->remote_address);
1064                 if (oacp_op->fp)
1065                         fclose(oacp_op->fp);
1066                 g_free(oacp_op);
1067                 oacp_op = NULL;
1068         }
1069 }
1070
1071 int _bt_otp_send_launch_request(char *absolute_path)
1072 {
1073         void *handle;
1074         char *error;
1075         int ret;
1076
1077         /* check ARCH 64 or 32*/
1078         if (!access(FILEPATH_ARCH_64, 0)) {
1079                 BT_INFO("plugin loading for ARCH 64");
1080                 handle = dlopen(HEADED_PLUGIN_FILEPATH64, RTLD_NOW);
1081         } else {
1082                 BT_INFO("plugin loading for ARCH 32");
1083                 handle = dlopen(HEADED_PLUGIN_FILEPATH, RTLD_NOW);
1084         }
1085
1086         if (!handle) {
1087                 BT_ERR("Can not load plugin %s", dlerror());
1088                 return BLUETOOTH_ERROR_INTERNAL;
1089         }
1090
1091         dlerror();      /* Clear any existing error */
1092
1093         int (*fun)(char *) = (int (*)(char *))dlsym(handle,
1094                                         "bt_app_control_send_launch_request");
1095
1096         if ((error = dlerror()) != NULL)  {
1097                 BT_ERR("Can not load symbol : %s", dlerror());
1098                 dlclose(handle);
1099                 return BLUETOOTH_ERROR_INTERNAL;
1100         }
1101
1102         ret = fun(absolute_path);
1103         dlclose(handle);
1104
1105         return ret;
1106 }
1107
1108 char *_bt_otp_uuid_convert_hex_to_string(char *value, uint32_t length)
1109 {
1110         char *uuid = NULL;
1111         unsigned int   data0;
1112         unsigned short data1;
1113         unsigned short data2;
1114         unsigned short data3;
1115         unsigned int   data4;
1116         unsigned short data5;
1117         size_t n;
1118
1119         uuid = (char *) g_malloc0(2 * length * sizeof(char));
1120         n = 2 * length + 1;
1121
1122         switch (length) {
1123         case 2:
1124                 memcpy(&data1, &value[0], 2);
1125                 snprintf(uuid, n, "%.4x", ntohs(data1));
1126                 break;
1127         case 4:
1128                 memcpy(&data0, &value[0], 4);
1129                 snprintf(uuid, n, "%.8x", ntohl(data0));
1130                 break;
1131         case 16:
1132                 memcpy(&data0, &value[0], 4);
1133                 memcpy(&data1, &value[4], 2);
1134                 memcpy(&data2, &value[6], 2);
1135                 memcpy(&data3, &value[8], 2);
1136                 memcpy(&data4, &value[10], 4);
1137                 memcpy(&data5, &value[14], 2);
1138
1139                 snprintf(uuid, n + 4, "%.8x-%.4x-%.4x-%.4x-%.8x%.4x",
1140                                         ntohl(data0), ntohs(data1),
1141                                         ntohs(data2), ntohs(data3),
1142                                         ntohl(data4), ntohs(data5));
1143                 break;
1144         default:
1145                 g_free(uuid);
1146                 return NULL;
1147         }
1148
1149         return uuid;
1150 }
1151
1152 void _bt_otp_create_new_object(uint32_t size, char *uuid)
1153 {
1154         struct object_metadata *object = NULL;
1155
1156         /* Store current object id.
1157          * Incase of OACP Create fail, need to restore
1158          * it back.
1159          */
1160         prev_obj_id = selected_object->id;
1161
1162         object = g_new0(struct object_metadata, 1);
1163
1164         object->name = NULL;
1165         object->type = g_strdup(uuid);
1166         object->first_created = 0;
1167         object->last_modified = 0;
1168         object->curr_size = 0;
1169         object->alloc_size = size;
1170         object->id = object_id;
1171         object->props = OBJECT_READ | OBJECT_WRITE |
1172                                         OBJECT_EXECUTE | OBJECT_DELETE;
1173
1174         otp_object_list = g_slist_append(otp_object_list,
1175                                                 object);
1176
1177         update_obj_metadata_charc_value(object);
1178         selected_object = object;
1179         curr_obj_index = g_slist_length(otp_object_list) - 1;
1180         curr_obj_id = selected_object->id;
1181         object_id++;
1182
1183         free(uuid);
1184 }
1185
1186 void _bt_otp_restore_old_object()
1187 {
1188         struct object_metadata *object = NULL;
1189         guint index = 0;
1190
1191         object = _bt_otp_client_find_object(otp_object_list, curr_obj_id, &index);
1192         if (!object)
1193                 return;
1194
1195         otp_object_list = g_slist_remove(otp_object_list, object);
1196
1197         index = 0;
1198         object = _bt_otp_client_find_object(otp_object_list, prev_obj_id, &index);
1199         oacp_create = FALSE;
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, uint16_t offset)
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         info = otp_get_char_value(obj_path);
1795         if (info) {
1796                 if (oacp_create && !g_strcmp0(obj_path, otp_object_name_obj_path)) {
1797                         /* char_value is NULL, value_length is zero */
1798                         *value = NULL;
1799                         *len = 0;
1800                         return BLUETOOTH_ATT_ERROR_NONE;
1801                 }
1802
1803                 if (info->char_value == NULL || info->value_length == 0)
1804                         return BLUETOOTH_ATT_ERROR_INTERNAL;
1805
1806                 if (offset > info->value_length)
1807                         return BLUETOOTH_ATT_ERROR_INVALID_OFFSET;
1808
1809                 *len = info->value_length - offset;
1810                 *value = (char *)malloc(sizeof(char)*(*len));
1811                 memcpy(*value, info->char_value, *len);
1812
1813                 return BLUETOOTH_ATT_ERROR_NONE;
1814         } else {
1815                 return BLUETOOTH_ATT_ERROR_INTERNAL;
1816         }
1817 }
1818
1819 static void _otp_convert_address_to_hex(bluetooth_device_address_t *addr_hex,
1820                                                         const char *addr_str)
1821 {
1822         int i = 0;
1823         unsigned int addr[BLUETOOTH_ADDRESS_LENGTH] = { 0, };
1824
1825         if (addr_str == NULL || addr_str[0] == '\0')
1826                 return;
1827
1828         i = sscanf(addr_str, "%X:%X:%X:%X:%X:%X", &addr[0], &addr[1],
1829                                 &addr[2], &addr[3], &addr[4], &addr[5]);
1830         if (i != BLUETOOTH_ADDRESS_LENGTH)
1831                 BT_ERR("Invalid format string - [%s]", addr_str);
1832
1833         for (i = 0; i < BLUETOOTH_ADDRESS_LENGTH; i++)
1834                 addr_hex->addr[i] = (unsigned char)addr[i];
1835 }
1836
1837 static void _bt_otp_send_indication(const char *obj_path,
1838                                 struct indicate_info *info,
1839                                 bluetooth_device_address_t *remote_address)
1840 {
1841         int ret = BLUETOOTH_ERROR_NONE;
1842         char value[7] = {0x00};
1843         int length = OTP_INDICATION_LEN_WITHOUT_RESP;
1844
1845         BT_DBG("");
1846
1847         value[0] = info->resp_opcode & 0xFF;
1848         value[1] = info->req_opcode & 0xFF;
1849         value[2] = info->result_code & 0xFF;
1850         if (info->resp_param) {
1851                 value[6] = info->resp_param[3] & 0xFF;
1852                 value[5] = info->resp_param[4] & 0xFF;
1853                 value[4] = info->resp_param[5] & 0xFF;
1854                 value[3] = info->resp_param[6] & 0xFF;
1855                 length = OTP_INDICATION_LEN_WITH_RESP;
1856         }
1857
1858         BT_DBG("Opcode: %d", value[1]);
1859
1860         /* Store the status value */
1861         _bt_otp_set_char_value(obj_path, value, length);
1862
1863         /* Send indication */
1864         ret = bluetooth_gatt_server_set_notification(obj_path, remote_address);
1865         if (ret != BLUETOOTH_ERROR_NONE) {
1866                 BT_ERR("_bt_otp_send_control_point_indication failed");
1867                 return;
1868         }
1869         ret = bluetooth_gatt_update_characteristic(obj_path, value, length);
1870         if (ret != BLUETOOTH_ERROR_NONE) {
1871                 BT_ERR("_bt_otp_send_control_point_indication failed");
1872                 return;
1873         }
1874 }
1875
1876 void _bt_otp_gatt_char_property_changed_event(GVariant *msg,
1877                                 const char *path)
1878 {
1879         int result = BLUETOOTH_ERROR_NONE;
1880         GVariantIter value_iter;
1881         const char *property = NULL;
1882         const char *char_path = NULL;
1883         const char *svc_handle = NULL;
1884         GVariant *var = NULL;
1885         GVariant *val = NULL;
1886         g_variant_iter_init(&value_iter, msg);
1887
1888         while ((g_variant_iter_loop(&value_iter, "{sv}", &property, &var))) {
1889
1890                 if (property == NULL) {
1891                         BT_ERR("Property NULL");
1892                         return;
1893                 }
1894
1895                 if (!g_strcmp0(property, "WriteValue")) {
1896                         int len = 0;
1897                         BT_INFO("WriteValue");
1898                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1899
1900                         if (var) {
1901                                 bluetooth_device_address_t addr_hex = { {0,} };
1902                                 gchar *addr = NULL;
1903                                 guint8 req_id = 1;
1904                                 guint16 offset = 0;
1905                                 char *value = NULL;
1906                                 struct indicate_info info;
1907
1908                                 g_variant_get(var, "(&s&s&syq@ay)",
1909                                                 &char_path, &svc_handle,
1910                                                 &addr, &req_id, &offset, &val);
1911
1912                                 len = g_variant_get_size(val);
1913
1914                                 BT_DBG("Len = %d, BT_ADDR = %s", len, addr);
1915
1916                                 value = (char *) g_variant_get_data(val);
1917                                 _otp_convert_address_to_hex(&addr_hex, addr);
1918
1919                                 if (len != 0) {
1920                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1921                                                 if (!OACP_indicate)
1922                                                         result = BLUETOOTH_ATT_ERROR_CCCD_IMPROPERLY_CONFIGURED;
1923                                                 else
1924                                                         result = _bt_otp_oacp_write_cb(value, len, offset, addr, &info);
1925                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1926                                                 if (!OLCP_indicate)
1927                                                         result = BLUETOOTH_ATT_ERROR_CCCD_IMPROPERLY_CONFIGURED;
1928                                                 else
1929                                                         result = _bt_otp_olcp_write_cb(value, len, offset, &info);
1930                                         } else if (!g_strcmp0(char_path, otp_object_name_obj_path)) {
1931                                                 result = _bt_otp_obj_name_write_cb(value, len);
1932                                         } else if (!g_strcmp0(char_path, otp_object_first_created_obj_path)) {
1933                                                 result = _bt_otp_obj_first_created_write_cb(value, len);
1934                                         } else if (!g_strcmp0(char_path, otp_object_last_modified_obj_path)) {
1935                                                 result = _bt_otp_obj_last_modified_write_cb(value, len);
1936                                         } else if (!g_strcmp0(char_path, otp_object_prop_obj_path)) {
1937                                                 result = _bt_otp_obj_props_write_cb(value, len);
1938                                         } else {
1939                                                 BT_ERR("Wrong Object Path %s", char_path);
1940                                                 result = BLUETOOTH_ERROR_INTERNAL;
1941                                         }
1942                                         bluetooth_gatt_send_response(req_id,
1943                                         BLUETOOTH_GATT_ATT_REQUEST_TYPE_WRITE,
1944                                                         result, 0, NULL, 0);
1945
1946                                         /* Send indication for CPs */
1947                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1948                                                 if (OACP_indicate)
1949                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1950                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1951                                                 if (OLCP_indicate)
1952                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
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, offset);
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         return;
2005 }
2006
2007 void _bt_otp_property_event_filter(GDBusConnection *connection,
2008                                         const gchar *sender_name,
2009                                         const gchar *object_path,
2010                                         const gchar *interface_name,
2011                                         const gchar *signal_name,
2012                                         GVariant *parameters,
2013                                         gpointer user_data)
2014 {
2015         GVariant *value;
2016
2017         if (signal_name == NULL) {
2018                 BT_ERR("Wrong Signal");
2019                 return;
2020         }
2021
2022         if (g_strcmp0(signal_name, PROPERTIES_CHANGED) == 0) {
2023
2024                 g_variant_get(parameters, "(@a{sv}@as)", &value, NULL);
2025                 _bt_otp_gatt_char_property_changed_event(value, object_path);
2026         }
2027 }
2028
2029 void _bt_otp_adapter_event_filter(GDBusConnection *connection,
2030                                         const gchar *sender_name,
2031                                         const gchar *object_path,
2032                                         const gchar *interface_name,
2033                                         const gchar *signal_name,
2034                                         GVariant *parameters,
2035                                         gpointer user_data)
2036 {
2037         if (signal_name == NULL) {
2038                 BT_ERR("Wrong Signal");
2039                 return;
2040         }
2041
2042         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
2043
2044         if (g_strcmp0(interface_name, BT_OTP_INTERFACE_NAME) == 0) {
2045                 if (strcasecmp(signal_name, BLE_DISABLED) == 0)
2046                         _bt_otp_exit();
2047         }
2048 }
2049
2050 void _bt_otc_disconnected_cb(GDBusConnection *connection,
2051                                         const gchar *sender_name,
2052                                         const gchar *object_path,
2053                                         const gchar *interface_name,
2054                                         const gchar *signal_name,
2055                                         GVariant *parameters,
2056                                         gpointer user_data)
2057 {
2058         if (signal_name == NULL) {
2059                 BT_ERR("Wrong Signal");
2060                 return;
2061         }
2062
2063         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
2064
2065         if (g_strcmp0(interface_name, BT_DEVICE_INTERFACE) == 0) {
2066                 if (strcasecmp(signal_name, OTC_DISCONNECTED) == 0) {
2067                         BT_DBG("OTC Channel Disconnected dev_path[%s]",
2068                                                                 object_path);
2069                         otc_connection_status = FALSE;
2070                         _bt_otp_free_oacp_op();
2071                 }
2072         }
2073 }
2074
2075 void _bt_otp_device_property_event_filter(GDBusConnection *connection,
2076                                         const gchar *sender_name,
2077                                         const gchar *object_path,
2078                                         const gchar *interface_name,
2079                                         const gchar *signal_name,
2080                                         GVariant *parameters,
2081                                         gpointer user_data)
2082 {
2083         char *interfacename = NULL;
2084         GVariant *val = NULL;
2085
2086         g_variant_get(parameters, "(&s@a{sv}@as)", &interfacename, &val, NULL);
2087
2088         if (strcasecmp(interfacename, BT_DEVICE_INTERFACE) == 0) {
2089                 GVariantIter value_iter;
2090                 GVariant *val1;
2091                 char *property = NULL;
2092
2093                 g_variant_iter_init(&value_iter, val);
2094                 while ((g_variant_iter_loop(&value_iter, "{sv}", &property, &val1))) {
2095                         if (strcasecmp(property, "GattConnected") == 0) {
2096                                 gboolean gatt_connected = FALSE;
2097                                 char *address = NULL;
2098
2099                                 g_variant_get(val1, "b", &gatt_connected);
2100
2101                                 address = g_malloc0(BT_ADDRESS_STRING_SIZE);
2102
2103                                 _bt_convert_device_path_to_address(object_path, address);
2104
2105                                 BT_DBG("gatt_connected: %d", gatt_connected);
2106                                 BT_DBG("address: %s", address);
2107                                 if (!gatt_connected) {
2108                                         if (oacp_create)
2109                                                 _bt_otp_restore_old_object();
2110
2111                                         if (oacp_create_timeout_id > 0)
2112                                                 g_source_remove(oacp_create_timeout_id);
2113                                 }
2114                                 g_free(address);
2115                         }
2116                 }
2117         }
2118 }
2119
2120 int _bt_otp_init_event_receiver()
2121 {
2122         BT_DBG("+");
2123         GError *error = NULL;
2124
2125         if (conn == NULL) {
2126                 conn =  g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
2127                 if (error != NULL) {
2128                         BT_ERR("ERROR: Can't get on system bus [%s]",
2129                                                         error->message);
2130                         g_clear_error(&error);
2131                 }
2132         }
2133
2134         property_sub_id = g_dbus_connection_signal_subscribe(conn,
2135                                 NULL,
2136                                 BT_OTP_INTERFACE_NAME,
2137                                 PROPERTIES_CHANGED,
2138                                 BT_OTP_OBJECT_PATH, NULL, 0,
2139                                 _bt_otp_property_event_filter,
2140                                 NULL, NULL);
2141
2142         adapter_sub_id = g_dbus_connection_signal_subscribe(conn,
2143                                 NULL,
2144                                 BT_OTP_INTERFACE_NAME,
2145                                 BLE_DISABLED,
2146                                 BT_OTP_OBJECT_PATH, NULL, 0,
2147                                 _bt_otp_adapter_event_filter,
2148                                 NULL, NULL);
2149
2150         device_sub_id = g_dbus_connection_signal_subscribe(conn,
2151                                         NULL, BT_DEVICE_INTERFACE,
2152                                         OTC_DISCONNECTED, NULL, NULL, 0,
2153                                         _bt_otc_disconnected_cb,
2154                                         NULL, NULL);
2155
2156         device_property_sub_id = g_dbus_connection_signal_subscribe(conn,
2157                                 NULL, BT_PROPERTIES_INTERFACE,
2158                                 PROPERTIES_CHANGED, NULL, NULL, 0,
2159                                 _bt_otp_device_property_event_filter,
2160                                 NULL, NULL);
2161
2162         BT_DBG("-");
2163         return 0;
2164 }
2165
2166 void _bt_otp_deinit_event_receiver(void)
2167 {
2168         BT_DBG("+");
2169
2170         g_dbus_connection_signal_unsubscribe(conn, property_sub_id);
2171         g_dbus_connection_signal_unsubscribe(conn, adapter_sub_id);
2172         g_dbus_connection_signal_unsubscribe(conn, device_sub_id);
2173         g_dbus_connection_signal_unsubscribe(conn, device_property_sub_id);
2174         conn = NULL;
2175
2176         BT_DBG("-");
2177 }
2178
2179 static void _bt_otp_sig_handler(int sig)
2180 {
2181         BT_DBG("+");
2182         switch (sig) {
2183         case SIGTERM:
2184                 BT_DBG("caught signal - sigterm\n");
2185                 break;
2186         case SIGINT:
2187                 BT_DBG("caught signal - sigint\n");
2188                 break;
2189         case SIGKILL:
2190                 BT_DBG("caught signal - sigkill\n");
2191                 break;
2192         default:
2193                 BT_DBG("caught signal %d and ignored\n", sig);
2194                 break;
2195         }
2196         BT_DBG("-");
2197 }
2198
2199 /* OTP Service Main loop */
2200 int main(void)
2201 {
2202         struct sigaction sa;
2203         BT_ERR("Starting the bt-otp daemon");
2204
2205         memset(&sa, 0, sizeof(sa));
2206         sa.sa_handler = _bt_otp_sig_handler;
2207         sa.sa_flags = SA_SIGINFO;
2208         sigaction(SIGINT, &sa, NULL);
2209         sigaction(SIGTERM, &sa, NULL);
2210         sigaction(SIGKILL, &sa, NULL);
2211
2212         if (_bt_otp_register_interface() != BLUETOOTH_ERROR_NONE) {
2213                 BT_ERR("Fail to register otp service");
2214                 return -4;
2215         }
2216
2217         if (_bt_otp_init_event_receiver() != BLUETOOTH_ERROR_NONE) {
2218                 BT_ERR("Fail to init event reciever");
2219                 return -5;
2220         }
2221
2222         main_loop = g_main_loop_new(NULL, FALSE);
2223
2224         g_main_loop_run(main_loop);
2225
2226         BT_DBG("g_main_loop_quit called!");
2227
2228         if (main_loop != NULL)
2229                 g_main_loop_unref(main_loop);
2230
2231         return 0;
2232 }