5361c71ac3c554e3352f62eebf9c432b477dc72e
[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
32 #include "bt-otpserver.h"
33 #include "bluetooth-api.h"
34
35
36 #undef LOG_TAG
37 #define LOG_TAG "BLUETOOTH_OTP"
38
39 #define BT_INFO(fmt, arg...) SLOGI(fmt, ##arg)
40 #define BT_ERR(fmt, arg...) SLOGE(fmt, ##arg)
41 #define BT_DBG(fmt, arg...) SLOGD(fmt, ##arg)
42
43 /* OTP object paths */
44 char *otp_obj_path = NULL;
45 char *otp_feature_obj_path = NULL;
46 char *otp_object_name_obj_path = NULL;
47 char *otp_object_type_obj_path = NULL;
48 char *otp_object_size_obj_path = NULL;
49 char *otp_object_first_created_obj_path = NULL;
50 char *otp_object_last_modified_obj_path = NULL;
51 char *otp_object_id_obj_path = NULL;
52 char *otp_object_prop_obj_path = NULL;
53 char *otp_oacp_obj_path = NULL;
54 char *otp_olcp_obj_path = NULL;
55 char *otp_oacp_desc_obj_path = NULL;
56 char *otp_olcp_desc_obj_path = NULL;
57
58 static GMainLoop *main_loop;
59 GDBusNodeInfo *otp_node_info = NULL;
60 static GDBusConnection *conn;
61 static GDBusConnection *g_conn;
62
63 static int property_sub_id = -1;
64 static int adapter_sub_id = -1;
65 static int device_sub_id = -1;
66 static guint g_owner_id = 0;
67 static guint server_watch_id = 0;
68
69 struct otp_char_info {
70         gchar *char_path;
71         gchar *char_value;
72         int value_length;
73 };
74
75 struct indicate_info {
76         uint8_t resp_opcode;
77         uint8_t req_opcode;
78         uint8_t result_code;
79         uint8_t *resp_param;
80 };
81
82 /* Object metadata */
83 struct object_metadata {
84         gchar *name;
85         gchar *type;
86         uint32_t curr_size;
87         uint32_t alloc_size;
88         time_t first_created;
89         time_t last_modified;
90         uint64_t id;
91         uint32_t props;
92 };
93
94 struct oacp_operation {
95         char *remote_address;
96         uint32_t offset;
97         uint32_t length;
98         uint8_t opcode;
99         uint32_t length_sofar;
100         uint8_t mode;
101         int fd;
102         FILE *fp;
103 };
104
105 struct oacp_create_operation {
106         char *remote_address;
107         char *uuid;
108         uint32_t size;
109 };
110
111 static struct object_metadata *selected_object = NULL;
112 static uint64_t object_id = OBJECT_START_ID;
113 static GSList *otp_object_list = NULL;
114 static GSList *otp_char_list = NULL;
115 static guint obj_curr_index;
116 static int adv_handle = 0;
117 static gboolean OACP_indicate = FALSE;
118 static gboolean OLCP_indicate = FALSE;
119 char *directory = NULL;
120 gboolean mutiple_obj_support = false;
121 static gboolean otc_connection_status = FALSE;
122 struct oacp_operation *oacp_op = NULL;
123 struct oacp_create_operation *oacp_create = NULL;
124 unsigned int timeout_id;
125
126 static const gchar otp_introspection_xml[] =
127 "<node name='/'>"
128 "       <interface name='org.projectx.otp_service'>"
129 "               <method name='enable'>"
130 "                       <arg type='s' name='directory'/>"
131 "                       <arg type='i' name='status' direction='out'/>"
132 "               </method>"
133 "               <method name='disable'>"
134 "                       <arg type='i' name='status' direction='out'/>"
135 "               </method>"
136 "     <method name='NewConnection'>"
137 "          <arg type='o' name='object' direction='in'/>"
138 "          <arg type='h' name='fd' direction='in'/>"
139 "     </method>"
140 "       </interface>"
141 "</node>";
142
143 void _bt_otp_deinit_event_receiver(void);
144 void _bt_otp_unregister_interface(void);
145 void update_obj_metadata_charc_value(struct object_metadata *object);
146 void _bt_convert_device_path_to_address(const char *device_path,
147                                                 char *device_address);
148 int _bt_otp_open_otc_and_listen(char *address, char *method);
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] = { 0x9C, 0x00, 0x00, 0x00,
302                                                 0x80, 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         perms = BLUETOOTH_GATT_PERMISSION_READ;
402         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OBJECT_PROP_UUID);
403         ret = add_new_characteristic(char_uuid, perms, props,
404                                         &otp_object_prop_obj_path);
405         if (ret != BLUETOOTH_ERROR_NONE)
406                 goto fail;
407
408         /* Characteristic OACP */
409         props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
410                 BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
411         perms = BLUETOOTH_GATT_PERMISSION_WRITE;
412         char_uuid = _otp_convert_uuid_to_uuid128(OTP_OACP_UUID);
413         ret = add_new_characteristic(char_uuid, perms, props,
414                                                 &otp_oacp_obj_path);
415         if (ret != BLUETOOTH_ERROR_NONE)
416                 goto fail;
417
418         /* CCCD for OACP */
419         desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
420         perms = BLUETOOTH_GATT_PERMISSION_READ |
421                 BLUETOOTH_GATT_PERMISSION_WRITE;
422         ret = bluetooth_gatt_add_descriptor(otp_oacp_obj_path, desc_uuid,
423                                                 perms, &otp_oacp_desc_obj_path);
424         if (ret != BLUETOOTH_ERROR_NONE) {
425                 BT_ERR("Failed to add new char descriptor %d", ret);
426                 goto fail;
427         }
428
429         /* OLCP Characteristics is not required
430          * for single object server
431          */
432         if (mutiple_obj_support) {
433                 /* Characteristic OLCP */
434                 props = BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_WRITE |
435                         BLUETOOTH_GATT_CHARACTERISTIC_PROPERTY_INDICATE;
436                 perms = BLUETOOTH_GATT_PERMISSION_WRITE;
437                 char_uuid = _otp_convert_uuid_to_uuid128(OTP_OLCP_UUID);
438                 ret = add_new_characteristic(char_uuid, perms, props,
439                                                         &otp_olcp_obj_path);
440                 if (ret != BLUETOOTH_ERROR_NONE)
441                         goto fail;
442
443                 /* CCCD for OLCP */
444                 desc_uuid = _otp_convert_uuid_to_uuid128(OTP_CP_CCC_DESC_UUID);
445                 perms = BLUETOOTH_GATT_PERMISSION_READ |
446                         BLUETOOTH_GATT_PERMISSION_WRITE;
447                 ret = bluetooth_gatt_add_descriptor(otp_olcp_obj_path, desc_uuid,
448                                                         perms, &otp_olcp_desc_obj_path);
449                 if (ret != BLUETOOTH_ERROR_NONE) {
450                         BT_ERR("Failed to add new char descriptor %d", ret);
451                         goto fail;
452                 }
453         }
454
455         /* Register service */
456         ret = bluetooth_gatt_register_service(otp_obj_path);
457         if (ret != BLUETOOTH_ERROR_NONE) {
458                 BT_ERR("Failed to register service %d", ret);
459                 goto fail;
460         }
461
462         /* Register Application */
463         ret = bluetooth_gatt_register_application();
464         if (ret != BLUETOOTH_ERROR_NONE) {
465                 BT_ERR("Failed to register application %d", ret);
466                 goto fail;
467         }
468
469         BT_DBG("-");
470         return ret;
471
472 fail:
473         delete_all_characterisitc();
474         return ret;
475 }
476
477 int _bt_otp_set_advertising_data(void)
478 {
479         int ret;
480         BT_DBG("");
481
482         /* OTP UUID */
483         guint8 data[4]  = {0x03, 0x02, 0x25, 0x18};
484         bluetooth_advertising_data_t adv;
485
486         BT_DBG("%x %x %x %x", data[0], data[1], data[2], data[3]);
487         memcpy(adv.data, data, sizeof(data));
488         ret = bluetooth_set_advertising_data(adv_handle, &adv, sizeof(data));
489         if (ret != BLUETOOTH_ERROR_NONE) {
490                 BT_ERR("Failed to set ADV data %d", ret);
491                 return ret;
492         }
493
494         ret = bluetooth_set_advertising(adv_handle, TRUE);
495         if (ret != BLUETOOTH_ERROR_NONE) {
496                 BT_ERR("Failed to set ADV %d", ret);
497                 return ret;
498         }
499
500         return 0;
501 }
502
503 void _bt_otp_start_write_on_fd()
504 {
505         char buf[BT_L2CAP_BUFFER_LEN];
506         int written;
507         int read;
508         int len;
509         FILE *fp;
510         char file_path[BT_FILE_PATH_MAX_LEN] = {0, };
511         int length;
512
513         if (!selected_object) {
514                 BT_DBG("Object not selected");
515                 return;
516         }
517
518         snprintf(file_path, sizeof(file_path), "%s%s",
519                                         directory, selected_object->name);
520         BT_DBG("file_path = [%s]", file_path);
521
522         fp = fopen(file_path, "r");
523         if (!fp) {
524                 BT_DBG("fopen() failed : %s", strerror(errno));
525                 return;
526         }
527
528         BT_DBG("length [%d]", oacp_op->length);
529         length = oacp_op->length;
530
531         while (length > 0) {
532                 if (length < BT_L2CAP_BUFFER_LEN)
533                         len = length;
534                 else
535                         len = BT_L2CAP_BUFFER_LEN;
536
537                 read = fread(buf, 1, len, fp);
538                 written = write(oacp_op->fd, buf, len);
539
540                 if (written < 0)
541                         goto fail;
542
543                 length -= written;
544
545                 BT_DBG("read [%d], written [%d], rem_len [%d]",
546                                                 read, written, length);
547         }
548 fail:
549         fclose(fp);
550 }
551
552
553 static bool __bt_otc_connection_timeout_cb(gpointer user_data)
554 {
555         int err = BLUETOOTH_ERROR_NONE;
556         char *remote_addr = oacp_op->remote_address;
557
558         err = _bt_otp_open_otc_and_listen(remote_addr, "DisconnectOtc");
559         if (err != BLUETOOTH_ERROR_NONE)
560                 BT_ERR("Disconnect OTC failed");
561
562         return TRUE;
563 }
564
565 static gboolean __server_data_received_cb(GIOChannel *chan, GIOCondition cond,
566                                                                 gpointer data)
567 {
568         char *remote_addr = oacp_op->remote_address;
569         GIOStatus status = G_IO_STATUS_NORMAL;
570         GError *err = NULL;
571         char *buffer = NULL;
572         gsize len = 0;
573         int written;
574         int fd;
575
576         BT_DBG("");
577
578         fd = g_io_channel_unix_get_fd(chan);
579         if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) {
580                 otc_connection_status = FALSE;
581                 BT_ERR("OTC disconnected: %d", fd);
582                 close(fd);
583                 g_source_remove(server_watch_id);
584                 return FALSE;
585         }
586
587         buffer = g_malloc0(BT_L2CAP_BUFFER_LEN + 1);
588
589         status = g_io_channel_read_chars(chan, buffer,
590                                                         BT_L2CAP_BUFFER_LEN,
591                                                         &len, &err);
592         if (status != G_IO_STATUS_NORMAL) {
593                 BT_ERR("IO Channel read is failed with %d", status);
594
595                 g_free(buffer);
596                 if (err) {
597                         otc_connection_status = FALSE;
598                         BT_ERR("IO Channel read error [%s]", err->message);
599                         if (status == G_IO_STATUS_ERROR) {
600                                 BT_ERR("cond : %d", cond);
601                                 g_error_free(err);
602                                 close(fd);
603                                 g_source_remove(server_watch_id);
604                                 return FALSE;
605                         }
606                         g_error_free(err);
607                 }
608                 return TRUE;
609         }
610
611         BT_DBG("Received data length %d, remote_addr = %s", len, remote_addr);
612
613         if (!oacp_op->fp) {
614                 char file_path[BT_FILE_PATH_MAX_LEN] = {0, };
615                 FILE *fp = NULL;
616
617                 if (!selected_object) {
618                         BT_DBG("Object not selected");
619                         goto fail;
620                 }
621
622                 snprintf(file_path, sizeof(file_path), "%s%s",
623                                                 directory, selected_object->name);
624
625                 BT_DBG("file_path = [%s]", file_path);
626                 fp = fopen(file_path, "w");
627                 if (!fp) {
628                         BT_DBG("fopen() failed : %s", strerror(errno));
629                         goto fail;
630                 }
631                 oacp_op->fp = fp;
632         }
633
634         if (oacp_op->length_sofar <= oacp_op->length) {
635                 written = fwrite(buffer, 1, len, oacp_op->fp);
636                 oacp_op->length_sofar += written;
637                 BT_DBG("written [%d], length_sofar [%lu], received_buff_len [%d], size [%lu]",
638                                         written, oacp_op->length_sofar, len, oacp_op->length);
639         }
640
641         if (timeout_id > 0) {
642                 g_source_remove(timeout_id);
643                 timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
644                         (GSourceFunc)__bt_otc_connection_timeout_cb, NULL);
645         }
646 fail:
647         g_free(buffer);
648         return TRUE;
649 }
650
651 static void _bt_otp_start_read_on_fd()
652 {
653         GIOChannel *data_io;
654         data_io = g_io_channel_unix_new(oacp_op->fd);
655
656         g_io_channel_set_encoding(data_io, NULL, NULL);
657         g_io_channel_set_flags(data_io, G_IO_FLAG_NONBLOCK, NULL);
658
659         server_watch_id = g_io_add_watch(data_io,
660                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
661                 __server_data_received_cb, NULL);
662
663         if (timeout_id > 0)
664                         g_source_remove(timeout_id);
665
666         timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
667                 (GSourceFunc)__bt_otc_connection_timeout_cb, NULL);
668 }
669
670 static void _bt_otp_method(GDBusConnection *connection,
671                 const gchar *sender,
672                 const gchar *object_path,
673                 const gchar *interface_name,
674                 const gchar *method_name,
675                 GVariant *parameters,
676                 GDBusMethodInvocation *invocation,
677                 gpointer user_data)
678 {
679         BT_DBG("+");
680         int status = BLUETOOTH_ERROR_NONE;
681
682         BT_DBG("Method[%s] Object Path[%s] Interface Name[%s]",
683                         method_name, object_path, interface_name);
684
685         if (g_strcmp0(method_name, "enable") == 0) {
686                 GDir *dir = NULL;
687                 GError *error = NULL;
688                 const gchar *filename = NULL;
689                 char absolute_path[BT_FILE_PATH_MAX_LEN];
690                 GSList *list = NULL, *l = NULL;
691                 struct stat st;
692                 struct object_metadata *object = NULL;
693
694                 g_variant_get(parameters, "(s)", &directory);
695                 BT_DBG("Directory = [%s]", directory);
696
697                 dir = g_dir_open(directory, 0, &error);
698                 if (!dir) {
699                         BT_ERR("Failed to open directory: %s", error->message);
700                         g_error_free(error);
701                         status = BLUETOOTH_ERROR_INVALID_DIRECTORY;
702                         goto fail;
703                 }
704
705                 while ((filename = g_dir_read_name(dir))) {
706                         list = g_slist_append(list, (gpointer) filename);
707                 }
708
709                 g_dir_close(dir);
710
711                 if (!list) {
712                         BT_DBG("No object found in given directory");
713                         status = BLUETOOTH_ERROR_NO_OBJECTS_FOUND;
714                         goto fail;
715                 }
716
717                 if (g_slist_length(list) > 1)
718                         mutiple_obj_support = true;
719
720                 for (l = list; l != NULL; l = l->next) {
721                         if (!l->data) continue;
722                         snprintf(absolute_path, sizeof(absolute_path), "%s%s", directory,
723                                                         (char *)l->data);
724
725                         BT_INFO("filename: %s, absoulte_path: %s",
726                                         (char *)l->data, absolute_path);
727
728                         if (stat(absolute_path, &st) == -1) {
729                                 BT_INFO("stat failed: (%d)\n", errno);
730                                 continue;
731                         }
732
733                         object = g_new0(struct object_metadata, 1);
734
735                         object->name = g_strdup((const gchar *)l->data);
736                         object->type = _otp_convert_uuid_to_uuid128(UNSUPPORTED_OBJECT_TYPE_UUID);
737                         object->first_created = st.st_ctime;
738                         object->last_modified = st.st_ctime;
739                         object->curr_size = (uint32_t) st.st_size;
740                         object->alloc_size = (uint32_t) st.st_size;
741                         object->id = object_id;
742                         object->props = OBJECT_READ | OBJECT_WRITE | OBJECT_EXECUTE;
743
744                         otp_object_list = g_slist_append(otp_object_list,
745                                                                 object);
746
747                         object_id++;
748                 }
749
750                 BT_DBG("preparing");
751                 if (_bt_otp_prepare_ots() != BLUETOOTH_ERROR_NONE) {
752                         BT_ERR("Fail to prepare OTP Proxy");
753                         status = BLUETOOTH_ERROR_INTERNAL;
754                         goto fail;
755                 }
756
757                 /* If single object is supported, make that as
758                  * selected object and update the metadata for the same.
759                  */
760                 if (!mutiple_obj_support) {
761                         BT_INFO("Server supports single object");
762                         selected_object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
763                         if (selected_object)
764                                 update_obj_metadata_charc_value(selected_object);
765                 }
766
767                 BT_DBG("advertsing");
768                 if (_bt_otp_set_advertising_data() != BLUETOOTH_ERROR_NONE) {
769                         BT_ERR("Fail to set advertising data");
770                         status = BLUETOOTH_ERROR_INTERNAL;
771                         goto fail;
772                 }
773 fail:
774                 g_dbus_method_invocation_return_value(invocation,
775                                                 g_variant_new("(i)", status));
776
777         } else if (g_strcmp0(method_name, "disable") == 0) {
778                 g_dbus_method_invocation_return_value(invocation,
779                                                 g_variant_new("(i)", status));
780                 _bt_otp_exit();
781
782         } else if (g_strcmp0(method_name, "NewConnection") == 0) {
783                 int index;
784                 GDBusMessage *msg;
785                 GUnixFDList *fd_list;
786                 char *dev_path;
787                 char address[BT_ADDRESS_STRING_SIZE] = { 0 };
788                 int fd;
789
790                 g_variant_get(parameters, "(oh)", &dev_path, &index);
791
792                 msg = g_dbus_method_invocation_get_message(invocation);
793                 fd_list = g_dbus_message_get_unix_fd_list(msg);
794                 if (fd_list == NULL) {
795                         BT_ERR("fd_list is NULL");
796                         return;
797                 }
798
799                 fd = g_unix_fd_list_get(fd_list, index, NULL);
800                 if (fd == -1) {
801                         BT_ERR("Invalid fd return");
802                         return;
803                 }
804
805                 _bt_convert_device_path_to_address(dev_path, address);
806
807                 BT_INFO("OTC Connected fd: %d, address %s", fd, address);
808                 otc_connection_status = TRUE;
809                 if (oacp_op) {
810                         oacp_op->fd = fd;
811
812                         if (oacp_op->opcode == OACP_READ)
813                                 _bt_otp_start_write_on_fd();
814                         else if (oacp_op->opcode == OACP_WRITE)
815                                 _bt_otp_start_read_on_fd();
816                 }
817                 g_dbus_method_invocation_return_value(invocation, NULL);
818         }
819         BT_DBG("-");
820 }
821
822 static const GDBusInterfaceVTable otp_method_table = {
823         _bt_otp_method,
824         NULL,
825         NULL,
826 };
827
828 static void _bt_otp_on_bus_acquired(GDBusConnection *connection,
829                                 const gchar *name, gpointer user_data)
830 {
831         guint object_id;
832         GError *error = NULL;
833
834         BT_DBG("+");
835
836         g_conn = connection;
837
838         object_id = g_dbus_connection_register_object(connection,
839                                                 BT_OTP_OBJECT_PATH,
840                                                 otp_node_info->interfaces[0],
841                                                 &otp_method_table,
842                                                 NULL, NULL, &error);
843         if (object_id == 0) {
844                 BT_ERR("Failed to register method table: %s", error->message);
845                 g_error_free(error);
846                 g_dbus_node_info_unref(otp_node_info);
847         }
848
849         BT_DBG("-");
850 }
851
852 static void _bt_otp_on_name_acquired(GDBusConnection *connection,
853                                         const gchar     *name,
854                                         gpointer user_data)
855 {
856         BT_DBG("");
857 }
858
859 static void _bt_otp_on_name_lost(GDBusConnection *connection,
860                                 const gchar     *name,
861                                 gpointer user_data)
862 {
863         BT_DBG("");
864         g_object_unref(g_conn);
865         g_conn = NULL;
866         g_dbus_node_info_unref(otp_node_info);
867         g_bus_unown_name(g_owner_id);
868 }
869
870 int _bt_otp_register_interface(void)
871 {
872         BT_DBG("+");
873         GError *error = NULL;
874         guint owner_id;
875
876         otp_node_info = g_dbus_node_info_new_for_xml(otp_introspection_xml, &error);
877         if (!otp_node_info) {
878                 BT_ERR("Failed to install: %s", error->message);
879                 return BLUETOOTH_ERROR_INTERNAL;
880         }
881
882         owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
883                                 BT_OTP_SERVICE_NAME,
884                                 G_BUS_NAME_OWNER_FLAGS_NONE,
885                                 _bt_otp_on_bus_acquired,
886                                 _bt_otp_on_name_acquired,
887                                 _bt_otp_on_name_lost,
888                                 NULL, NULL);
889         g_owner_id = owner_id;
890         BT_DBG("owner_id is [%d]\n", owner_id);
891
892         BT_DBG("-");
893         return BLUETOOTH_ERROR_NONE;
894 }
895
896 void _bt_otp_unregister_interface(void)
897 {
898         BT_DBG("+");
899
900         g_object_unref(g_conn);
901         g_conn = NULL;
902         g_dbus_node_info_unref(otp_node_info);
903         g_bus_unown_name(g_owner_id);
904
905         BT_DBG("-");
906         return;
907 }
908
909 void _bt_convert_device_path_to_address(const char *device_path,
910                                                 char *device_address)
911 {
912         char address[BT_ADDRESS_STRING_SIZE] = { 0 };
913         char *dev_addr;
914
915         dev_addr = strstr(device_path, "dev_");
916         if (dev_addr != NULL) {
917                 char *pos = NULL;
918                 dev_addr += 4;
919                 g_strlcpy(address, dev_addr, sizeof(address));
920
921                 while ((pos = strchr(address, '_')) != NULL)
922                         *pos = ':';
923
924                 g_strlcpy(device_address, address, BT_ADDRESS_STRING_SIZE);
925         }
926 }
927
928 static char *__bt_extract_device_path(GVariantIter *iter, char *address)
929 {
930         char *object_path = NULL;
931         char device_address[BT_ADDRESS_STRING_SIZE] = { 0 };
932
933         /* Parse the signature: oa{sa{sv}}} */
934         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path,
935                         NULL)) {
936                 if (!object_path) {
937                         BT_ERR("Unable to get object path");
938                         return NULL;
939                 }
940                 _bt_convert_device_path_to_address(object_path, device_address);
941                 if (g_strcmp0(address, device_address) == 0)
942                         return g_strdup(object_path);
943
944         }
945
946         BT_ERR("Unable to get object path");
947         return NULL;
948 }
949
950 char *_bt_otp_get_device_object_path(char *address)
951 {
952         GError *err = NULL;
953         GDBusProxy *proxy = NULL;
954         GVariant *result = NULL;
955         GVariantIter *iter = NULL;
956         char *object_path = NULL;
957
958         proxy =  g_dbus_proxy_new_sync(conn,
959                         G_DBUS_PROXY_FLAGS_NONE, NULL,
960                         BT_BLUEZ_NAME,
961                         BT_MANAGER_PATH,
962                         BT_MANAGER_INTERFACE,
963                         NULL, &err);
964
965         if (!proxy) {
966                 BT_ERR("Unable to create proxy: %s", err->message);
967                 goto fail;
968         }
969
970         result = g_dbus_proxy_call_sync(proxy, "GetManagedObjects", NULL,
971                         G_DBUS_CALL_FLAGS_NONE, -1, NULL, &err);
972         if (!result) {
973                 if (err != NULL)
974                         BT_ERR("Fail to get GetManagedObjects (Error: %s)", err->message);
975                 else
976                         BT_ERR("Fail to get GetManagedObjects");
977
978                 goto fail;
979         }
980
981         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
982         object_path = __bt_extract_device_path(iter, address);
983
984         g_variant_unref(result);
985         g_variant_iter_free(iter);
986
987 fail:
988         if (err)
989                 g_clear_error(&err);
990
991         if (proxy)
992                 g_object_unref(proxy);
993
994         return object_path;
995 }
996
997 int _bt_otp_open_otc_and_listen(char *address, char *method)
998 {
999         char *object_path;
1000         GDBusProxy *device_proxy = NULL;
1001         GVariant *result = NULL;
1002         GError *error = NULL;
1003         int ret = BLUETOOTH_ERROR_NONE;
1004
1005         if (method == NULL)
1006                 return BLUETOOTH_ERROR_INTERNAL;
1007
1008         if (g_strcmp0(method, "ListenOtc") &&
1009                         g_strcmp0(method, "DisconnectOtc"))
1010                 return BLUETOOTH_ERROR_INTERNAL;
1011
1012         object_path = _bt_otp_get_device_object_path(address);
1013         if (object_path == NULL) {
1014                 ret = BLUETOOTH_ERROR_NOT_PAIRED;
1015                 goto fail;
1016         }
1017
1018         device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
1019                                         NULL, BT_BLUEZ_NAME, object_path,
1020                                         BT_DEVICE_INTERFACE,  NULL, NULL);
1021         if (device_proxy == NULL) {
1022                 ret = BLUETOOTH_ERROR_INTERNAL;
1023                 goto fail;
1024         }
1025
1026
1027         result = g_dbus_proxy_call_sync(device_proxy, method,
1028                                 NULL,
1029                                 G_DBUS_CALL_FLAGS_NONE,
1030                                 -1,
1031                                 NULL,
1032                                 &error);
1033         if (result == NULL) {
1034                 if (error != NULL) {
1035                         BT_ERR("Error occured in Proxy call [%s]\n", error->message);
1036                         g_error_free(error);
1037                 }
1038                 ret = BLUETOOTH_ERROR_INTERNAL;
1039         }
1040 fail:
1041         if (object_path)
1042                 g_free(object_path);
1043         if (result)
1044                 g_variant_unref(result);
1045         if (device_proxy)
1046                 g_object_unref(device_proxy);
1047         return ret;
1048 }
1049
1050 static bool __bt_oacp_create_timeout_cb(gpointer user_data)
1051 {
1052         if (oacp_create) {
1053                 g_free(oacp_create->uuid);
1054                 g_free(oacp_create);
1055                 oacp_create = NULL;
1056         }
1057         return TRUE;
1058 }
1059
1060 static void _bt_otp_free_oacp_op()
1061 {
1062         if (timeout_id > 0) {
1063                 g_source_remove(timeout_id);
1064                 timeout_id = 0;
1065         }
1066
1067         if (oacp_op) {
1068                 g_free(oacp_op->remote_address);
1069                 if (oacp_op->fp)
1070                         fclose(oacp_op->fp);
1071                 g_free(oacp_op);
1072                 oacp_op = NULL;
1073         }
1074 }
1075
1076 int _bt_otp_send_launch_request(char *absolute_path)
1077 {
1078         void *handle;
1079         char *error;
1080         int ret;
1081
1082         /* check ARCH 64 or 32*/
1083         if (!access(FILEPATH_ARCH_64, 0)) {
1084                 BT_INFO("plugin loading for ARCH 64");
1085                 handle = dlopen(HEADED_PLUGIN_FILEPATH64, RTLD_NOW);
1086         } else {
1087                 BT_INFO("plugin loading for ARCH 32");
1088                 handle = dlopen(HEADED_PLUGIN_FILEPATH, RTLD_NOW);
1089         }
1090
1091         if (!handle) {
1092                 BT_ERR("Can not load plugin %s", dlerror());
1093                 return BLUETOOTH_ERROR_INTERNAL;
1094         }
1095
1096         dlerror();      /* Clear any existing error */
1097
1098         int (*fun)(char *) = (int (*)(char *))dlsym(handle,
1099                                         "bt_app_control_send_launch_request");
1100
1101         if ((error = dlerror()) != NULL)  {
1102                 BT_ERR("Can not load symbol : %s", dlerror());
1103                 dlclose(handle);
1104                 return BLUETOOTH_ERROR_INTERNAL;
1105         }
1106
1107         ret = fun(absolute_path);
1108         dlclose(handle);
1109
1110         return ret;
1111 }
1112
1113 int _bt_otp_oacp_write_cb(char *value, int len, int offset,
1114                                                         char *remote_addr, struct indicate_info *info)
1115 {
1116         int ret = OACP_SUCCESS;
1117         int app_err = BLUETOOTH_ERROR_NONE;
1118         int opcode = value[0];
1119         uint32_t object_offset, length, object_size;
1120         uint8_t mode = 0;
1121         char *uuid;
1122         char absolute_path[BT_FILE_PATH_MAX_LEN] = {0, };
1123
1124         BT_INFO("OACP Opcode 0x%d", opcode);
1125
1126         if (!otp_object_list) {
1127                 ret = OACP_INVALID_OBJ;
1128                 goto fail;
1129         }
1130
1131         switch (opcode) {
1132         case OACP_CREATE:
1133                 BT_INFO("OACP_CREATE");
1134                 object_size = (uint32_t)(value[4] & 0xFF) << 24 |
1135                                 (uint32_t)(value[3] & 0xFF) << 16 |
1136                                 (uint32_t)(value[2] & 0xFF) << 8  |
1137                                 (uint32_t)(value[1] & 0xFF);
1138
1139                 uuid = g_strndup(value + 5, len - 5);
1140                 BT_INFO("Size = %lu, UUID = %s", object_size, uuid);
1141
1142                 if (oacp_create) {
1143                         /* Create operation already going on. */
1144                         ret = OACP_OPERATION_FAILED;
1145                         goto fail;
1146                 }
1147                 oacp_create = g_malloc0(sizeof(struct oacp_create_operation));
1148                 oacp_create->size = object_size;
1149                 oacp_create->uuid = g_strdup(uuid);
1150                 if (timeout_id > 0)
1151                         g_source_remove(timeout_id);
1152                 timeout_id = g_timeout_add(BT_OACP_MAX_TIMEOUT,
1153                         (GSourceFunc)__bt_oacp_create_timeout_cb, NULL);
1154                 g_free(uuid);
1155                 ret = OACP_SUCCESS;
1156                 break;
1157         case OACP_DELETE:
1158                 ret = OACP_OPCODE_NOT_SUPPORTED;
1159                 break;
1160         case OACP_CALC_CHECKSUM:
1161                 ret = OACP_OPCODE_NOT_SUPPORTED;
1162                 break;
1163         case OACP_EXECUTE:
1164                 if (!selected_object) {
1165                         BT_DBG("Object not selected");
1166                         ret = OACP_OPERATION_FAILED;
1167                         goto fail;
1168                 }
1169
1170                 snprintf(absolute_path, sizeof(absolute_path), "file://%s%s", directory,
1171                                                         selected_object->name);
1172
1173                 BT_DBG("absolute_path = [%s]", absolute_path);
1174
1175                 app_err = _bt_otp_send_launch_request(absolute_path);
1176                 if (app_err == BLUETOOTH_ERROR_NONE)
1177                         ret = OACP_SUCCESS;
1178                 else
1179                         ret = OACP_OPERATION_FAILED;
1180                 break;
1181         case OACP_READ:
1182         case OACP_WRITE:
1183                 object_offset = (uint32_t)(value[4] & 0xFF) << 24 |
1184                                 (uint32_t)(value[3] & 0xFF) << 16 |
1185                                 (uint32_t)(value[2] & 0xFF) << 8  |
1186                                 (uint32_t)(value[1] & 0xFF);
1187                 length = (uint32_t)(value[8] & 0xFF) << 24 |
1188                         (uint32_t)(value[7] & 0xFF) << 16 |
1189                         (uint32_t)(value[6] & 0xFF) << 8  |
1190                         (uint32_t)(value[5] & 0xFF);
1191
1192                 if (opcode == OACP_WRITE)
1193                         mode = (uint8_t)value[9] & 0xFF;
1194
1195                 BT_INFO("Offset = %lu, Length = %lu", object_offset, length, mode);
1196
1197                 if (oacp_op) {
1198                         if (otc_connection_status) {
1199                                 /* Read/Write operation already going on. */
1200                                 ret = OACP_OBJECT_LOCKED;
1201                                 goto fail;
1202                         }
1203                         _bt_otp_free_oacp_op();
1204                 }
1205
1206                 oacp_op = g_malloc0(sizeof(struct oacp_operation));
1207                 oacp_op->offset = object_offset;
1208                 oacp_op->length = length;
1209                 oacp_op->remote_address = g_strdup(remote_addr);
1210                 oacp_op->mode = mode;
1211                 oacp_op->opcode = opcode;
1212                 oacp_op->length_sofar = 0;
1213                 oacp_op->fp = NULL;
1214
1215                 app_err = _bt_otp_open_otc_and_listen(remote_addr, "ListenOtc");
1216                 if (app_err != BLUETOOTH_ERROR_NONE) {
1217                         ret = OACP_OPERATION_FAILED;
1218                         _bt_otp_free_oacp_op();
1219                         goto fail;
1220                 }
1221                 ret = OACP_SUCCESS;
1222                 break;
1223         case OACP_ABORT:
1224                 ret = OACP_OPCODE_NOT_SUPPORTED;
1225                 break;
1226         default:
1227                 ret = OACP_OPCODE_NOT_SUPPORTED;
1228                 break;
1229         }
1230 fail:
1231         info->resp_opcode = OACP_RESPONSE;
1232         info->req_opcode = opcode;
1233         info->result_code = ret;
1234         info->resp_param = NULL;
1235         return app_err;
1236 }
1237
1238 void convert_to_hex(struct object_metadata *object, char *type, char *value)
1239 {
1240         struct tm fc_tm;
1241
1242         BT_DBG("type : %s", type);
1243
1244         memset(value, 0, 8);
1245
1246         if (!g_strcmp0(type, "size")) {
1247
1248                 value[3] = (object->curr_size >> 24) & 0xFF;
1249                 value[2] = (object->curr_size >> 16) & 0xFF;
1250                 value[1] = (object->curr_size >> 8) & 0xFF;
1251                 value[0] = object->curr_size & 0xFF;
1252
1253                 value[7] = (object->alloc_size >> 24) & 0xFF;
1254                 value[6] = (object->alloc_size >> 16) & 0xFF;
1255                 value[5] = (object->alloc_size >> 8) & 0xFF;
1256                 value[4] = object->alloc_size & 0xFF;
1257
1258         } else if (!g_strcmp0(type, "date")) {
1259
1260                 localtime_r(&(object->first_created), &fc_tm);
1261
1262                 value[1] = ((fc_tm.tm_year+1900) >> 8) & 0xFF;
1263                 value[0] = (fc_tm.tm_year+1900) & 0xFF;
1264                 value[2] = (fc_tm.tm_mon+1) & 0xFF;
1265                 value[3] = fc_tm.tm_mday & 0xFF;
1266                 value[4] = fc_tm.tm_hour & 0xFF;
1267                 value[5] = fc_tm.tm_min & 0xFF;
1268                 value[6] = fc_tm.tm_sec & 0xFF;
1269
1270         } else if (!g_strcmp0(type, "id")) {
1271
1272                 value[5] = (object->id >> 48) & 0xFF;
1273                 value[4] = (object->id >> 32) & 0xFF;
1274                 value[3] = (object->id >> 24) & 0xFF;
1275                 value[2] = (object->id >> 16) & 0xFF;
1276                 value[1] = (object->id >> 8) & 0xFF;
1277                 value[0] = object->id & 0xFF;
1278
1279         } else if (!g_strcmp0(type, "props")) {
1280                 value[3] = (object->props >> 24) & 0xFF;
1281                 value[2] = (object->props >> 16) & 0xFF;
1282                 value[1] = (object->props >> 8) & 0xFF;
1283                 value[0] = object->props & 0xFF;
1284         }
1285 }
1286
1287 void update_obj_metadata_charc_value(struct object_metadata *object)
1288 {
1289         /* Value can be of maximum eight bytes */
1290         char value[8];
1291
1292         _bt_otp_set_char_value(otp_object_name_obj_path, object->name,
1293                                                         strlen(object->name));
1294         _bt_otp_set_char_value(otp_object_type_obj_path, object->type,
1295                                                         strlen(object->type));
1296
1297         convert_to_hex(object, "size", value);
1298         _bt_otp_set_char_value(otp_object_size_obj_path, value, 8);
1299
1300         convert_to_hex(object, "date", value);
1301         _bt_otp_set_char_value(otp_object_first_created_obj_path, value, 7);
1302         _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, 7);
1303
1304         /* Object ID is optonal for single object server */
1305         if (mutiple_obj_support) {
1306                 convert_to_hex(object, "id", value);
1307                 _bt_otp_set_char_value(otp_object_id_obj_path, value, 6);
1308         }
1309
1310         convert_to_hex(object, "props", value);
1311         _bt_otp_set_char_value(otp_object_prop_obj_path, value, 4);
1312 }
1313
1314 struct object_metadata *_bt_otp_client_find_object(GSList *list, uint64_t id, guint *index)
1315 {
1316         GSList *l;
1317         struct object_metadata *info;
1318
1319         for (l = list; l; l = g_slist_next(l)) {
1320                 (*index)++;
1321                 info = l->data;
1322
1323                 if (info && (info->id == id))
1324                         return info;
1325         }
1326         return NULL;
1327 }
1328
1329 int _bt_otp_olcp_write_cb(char *value, int len, int offset,
1330                                         struct indicate_info *info)
1331 {
1332         int ret = OLCP_SUCCESS;
1333         int opcode = value[0];
1334         struct object_metadata *object;
1335         uint64_t object_id;
1336         guint index = 0;
1337
1338         BT_INFO("OLCP Opcode 0x%d", opcode);
1339
1340         if (!otp_object_list) {
1341                 ret = OLCP_NO_OBJ;
1342                 goto fail;
1343         }
1344
1345         switch (opcode) {
1346         case OLCP_FIRST:
1347                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, 0);
1348                 if (!object) {
1349                         ret = OLCP_OUT_OF_BOUNDS;
1350                         goto fail;
1351                 }
1352                 update_obj_metadata_charc_value(object);
1353                 selected_object = object;
1354                 obj_curr_index = 0;
1355                 break;
1356         case OLCP_LAST:
1357                 len = g_slist_length(otp_object_list);
1358                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, len-1);
1359                 if (!object) {
1360                         ret = OLCP_OUT_OF_BOUNDS;
1361                         goto fail;
1362                 }
1363                 update_obj_metadata_charc_value(object);
1364                 selected_object = object;
1365                 obj_curr_index = len-1;
1366                 break;
1367         case OLCP_PREVIOUS:
1368                 if (obj_curr_index == 0) {
1369                         ret = OLCP_OUT_OF_BOUNDS;
1370                         goto fail;
1371                 }
1372                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, obj_curr_index-1);
1373                 if (!object) {
1374                         ret = OLCP_OUT_OF_BOUNDS;
1375                         goto fail;
1376                 }
1377                 update_obj_metadata_charc_value(object);
1378                 selected_object = object;
1379                 obj_curr_index -= 1;
1380                 break;
1381         case OLCP_NEXT:
1382                 object = (struct object_metadata *) g_slist_nth_data(otp_object_list, obj_curr_index+1);
1383                 if (!object) {
1384                         ret = OLCP_OUT_OF_BOUNDS;
1385                         goto fail;
1386                 }
1387                 update_obj_metadata_charc_value(object);
1388                 selected_object = object;
1389                 obj_curr_index += 1;
1390                 break;
1391         case OLCP_GOTO:
1392                 object_id = (uint64_t)(value[6] & 0xFF) << 40 |
1393                                 (uint64_t)(value[5] & 0xFF) << 32 |
1394                                 (uint64_t)(value[4] & 0xFF) << 24 |
1395                                 (uint64_t)(value[3] & 0xFF) << 16 |
1396                                 (uint64_t)(value[2] & 0xFF) << 8  |
1397                                 (uint64_t)(value[1] & 0xFF);
1398                 BT_INFO("Object ID [%llu]", object_id);
1399                 if (selected_object && selected_object->id == object_id)
1400                         goto fail;
1401
1402                 object = _bt_otp_client_find_object(otp_object_list, object_id, &index);
1403                 if (!object) {
1404                         ret = OLCP_OJECT_ID_NOT_FOUND;
1405                         goto fail;
1406                 }
1407                 update_obj_metadata_charc_value(object);
1408                 selected_object = object;
1409                 obj_curr_index = index - 1;
1410                 break;
1411         case OLCP_ORDER:
1412         case OLCP_REQ_NO_OBJ:
1413         case OLCP_CLEAR_MARKING:
1414         default:
1415                 ret = OLCP_OPCODE_NOT_SUPPORTED;
1416                 break;
1417         }
1418 fail:
1419         info->resp_opcode = OLCP_RESPONSE;
1420         info->req_opcode = opcode;
1421         info->result_code = ret;
1422         info->resp_param = NULL;
1423         return BLUETOOTH_ERROR_NONE;
1424 }
1425
1426 int _bt_otp_obj_name_cb(char *value, int len)
1427 {
1428         int ret = BLUETOOTH_ERROR_NONE;
1429
1430         struct object_metadata *object = NULL;
1431         struct stat st;
1432         char *file_path;
1433         char *filename;
1434         int length;
1435         FILE *fp = NULL;
1436
1437         filename = g_strndup(value, len);
1438         length = len + strlen(BT_OTP_BASE_DIR_PATH) + 1;
1439         file_path = malloc(length);
1440
1441         snprintf(file_path, length, "%s%s",
1442                         BT_OTP_BASE_DIR_PATH, filename);
1443         BT_DBG("file_path = [%s]", file_path);
1444
1445         fp = fopen(file_path, "a");
1446         if (!fp) {
1447                 BT_DBG("fopen() failed : %s", strerror(errno));
1448                 ret = BLUETOOTH_ERROR_INTERNAL;
1449                 goto fail;
1450         }
1451
1452         if (stat(file_path, &st) == -1) {
1453                 BT_INFO("stat failed: (%d)\n", errno);
1454                 ret = BLUETOOTH_ERROR_INTERNAL;
1455                 goto fail;
1456         }
1457
1458         object = g_new0(struct object_metadata, 1);
1459
1460         object->name = g_strdup(filename);
1461         object->type = _otp_convert_uuid_to_uuid128(oacp_create->uuid);
1462         object->first_created = st.st_ctime;
1463         object->last_modified = st.st_ctime;
1464         object->curr_size = (uint32_t)st.st_size;
1465         object->alloc_size = oacp_create->size;
1466         object->id = object_id;
1467         object->props = OBJECT_READ | OBJECT_WRITE;
1468
1469         otp_object_list = g_slist_append(otp_object_list,
1470                                                 object);
1471
1472         update_obj_metadata_charc_value(object);
1473         selected_object = object;
1474         obj_curr_index = g_slist_length(otp_object_list) - 1;
1475         object_id++;
1476 fail:
1477         if (fp)
1478                 fclose(fp);
1479         g_free(filename);
1480         free(file_path);
1481         g_free(oacp_create->uuid);
1482         g_free(oacp_create);
1483         oacp_create = NULL;
1484
1485         return ret;
1486 }
1487
1488 static struct otp_char_info *otp_get_char_value(const char *path)
1489 {
1490         GSList *tmp = NULL;
1491
1492         for (tmp = otp_char_list; tmp != NULL; tmp = tmp->next) {
1493                 if (tmp->data) {
1494                         struct otp_char_info *char_info = tmp->data;
1495                         if (!g_strcmp0(char_info->char_path, path))
1496                                 return char_info;
1497                 }
1498         }
1499
1500         return NULL;
1501 }
1502
1503 int _bt_otp_read_cb(const char *obj_path, char **value, int *len)
1504 {
1505         struct otp_char_info *info = NULL;
1506
1507         if (!obj_path) {
1508                 BT_ERR("Wrong Obj path");
1509                 return BLUETOOTH_ERROR_INTERNAL;
1510         }
1511
1512         if (g_strcmp0(obj_path, otp_feature_obj_path)) {
1513                 if (!selected_object) {
1514                         return BLUETOOTH_ERROR_OBJECT_NOT_SELECTED;
1515                 }
1516         }
1517
1518         info = otp_get_char_value(obj_path);
1519         if (info) {
1520                 if (info->char_value == NULL || info->value_length == 0)
1521                         return BLUETOOTH_ERROR_INTERNAL;
1522
1523                 *len = info->value_length;
1524                 *value = (char *)malloc(sizeof(char)*(*len));
1525                 memcpy(*value, info->char_value, *len);
1526
1527                 return BLUETOOTH_ERROR_NONE;
1528         } else {
1529                 return BLUETOOTH_ERROR_INTERNAL;
1530         }
1531 }
1532
1533 static void _otp_convert_address_to_hex(bluetooth_device_address_t *addr_hex,
1534                                                         const char *addr_str)
1535 {
1536         int i = 0;
1537         unsigned int addr[BLUETOOTH_ADDRESS_LENGTH] = { 0, };
1538
1539         if (addr_str == NULL || addr_str[0] == '\0')
1540                 return;
1541
1542         i = sscanf(addr_str, "%X:%X:%X:%X:%X:%X", &addr[0], &addr[1],
1543                                 &addr[2], &addr[3], &addr[4], &addr[5]);
1544         if (i != BLUETOOTH_ADDRESS_LENGTH)
1545                 BT_ERR("Invalid format string - [%s]", addr_str);
1546
1547         for (i = 0; i < BLUETOOTH_ADDRESS_LENGTH; i++)
1548                 addr_hex->addr[i] = (unsigned char)addr[i];
1549 }
1550
1551 static void _bt_otp_send_indication(const char *obj_path,
1552                                 struct indicate_info *info,
1553                                 bluetooth_device_address_t *remote_address)
1554 {
1555         int ret = BLUETOOTH_ERROR_NONE;
1556         char value[7] = {0x00};
1557
1558         BT_DBG("");
1559
1560         value[0] = info->resp_opcode & 0xFF;
1561         value[1] = info->req_opcode & 0xFF;
1562         value[2] = info->result_code & 0xFF;
1563         if (info->resp_param) {
1564                 value[6] = (info->resp_param[3] >> 24) & 0xFF;
1565                 value[5] = (info->resp_param[4] >> 16) & 0xFF;
1566                 value[4] = (info->resp_param[5] >> 8) & 0xFF;
1567                 value[3] = info->resp_param[6] & 0xFF;
1568         }
1569
1570         BT_DBG("Opcode: %d", value[1]);
1571
1572         /* Store the status value */
1573         _bt_otp_set_char_value(obj_path, value, 7);
1574
1575         /* Send indication */
1576         ret = bluetooth_gatt_server_set_notification(obj_path, remote_address);
1577         if (ret != BLUETOOTH_ERROR_NONE) {
1578                 BT_ERR("_bt_otp_send_control_point_indication failed");
1579                 return;
1580         }
1581         ret = bluetooth_gatt_update_characteristic(obj_path, value, 7);
1582         if (ret != BLUETOOTH_ERROR_NONE) {
1583                 BT_ERR("_bt_otp_send_control_point_indication failed");
1584                 return;
1585         }
1586 }
1587
1588 void _bt_otp_gatt_char_property_changed_event(GVariant *msg,
1589                                 const char *path)
1590 {
1591         int result = BLUETOOTH_ERROR_NONE;
1592         GVariantIter value_iter;
1593         const char *property = NULL;
1594         const char *char_path = NULL;
1595         const char *svc_handle = NULL;
1596         GVariant *var = NULL;
1597         GVariant *val = NULL;
1598         g_variant_iter_init(&value_iter, msg);
1599
1600         while ((g_variant_iter_loop(&value_iter, "{sv}", &property, &var))) {
1601
1602                 if (property == NULL) {
1603                         BT_ERR("Property NULL");
1604                         return;
1605                 }
1606
1607                 if (!g_strcmp0(property, "WriteValue")) {
1608                         int len = 0;
1609                         BT_INFO("WriteValue");
1610                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1611
1612                         if (var) {
1613                                 bluetooth_device_address_t addr_hex = { {0,} };
1614                                 gchar *addr = NULL;
1615                                 guint8 req_id = 1;
1616                                 guint16 offset = 0;
1617                                 char *value = NULL;
1618                                 struct indicate_info info;
1619                                 g_variant_get(var, "(&s&s&syq@ay)",
1620                                                 &char_path, &svc_handle,
1621                                                 &addr, &req_id, &offset, &val);
1622
1623                                 len = g_variant_get_size(val);
1624
1625                                 BT_DBG("Len = %d, BT_ADDR = %s", len, addr);
1626
1627                                 value = (char *) g_variant_get_data(val);
1628                                 _otp_convert_address_to_hex(&addr_hex, addr);
1629
1630                                 if (len != 0) {
1631                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1632                                                 result = _bt_otp_oacp_write_cb(value, len, offset, addr, &info);
1633                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1634                                                 result = _bt_otp_olcp_write_cb(value, len, offset, &info);
1635                                         } else if (!g_strcmp0(char_path, otp_object_name_obj_path)) {
1636                                                 if (oacp_create) {
1637                                                         /* OACP_CREATE is ongoing */
1638                                                         result = _bt_otp_obj_name_cb(value, len);
1639                                                 } else {
1640                                                         /* Dont permit writting object name except while creating object.
1641                                                          * As this is directly pointing local objects.
1642                                                          */
1643                                                         result = BLUETOOTH_ERROR_WRITE_REQUEST_REJECTED;
1644                                                 }
1645                                         } else if (!g_strcmp0(char_path, otp_object_first_created_obj_path)) {
1646                                                 _bt_otp_set_char_value(otp_object_first_created_obj_path, value, len);
1647                                         } else if (!g_strcmp0(char_path, otp_object_last_modified_obj_path)) {
1648                                                 _bt_otp_set_char_value(otp_object_last_modified_obj_path, value, len);
1649                                         } else {
1650                                                 BT_ERR("Wrong Object Path %s", char_path);
1651                                                 result = BLUETOOTH_ERROR_INTERNAL;
1652                                         }
1653                                         bluetooth_gatt_send_response(req_id,
1654                                         BLUETOOTH_GATT_ATT_REQUEST_TYPE_WRITE,
1655                                                         result, 0, NULL, 0);
1656
1657                                         /* Send indication for CPs */
1658                                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1659                                                 if (OACP_indicate) {
1660                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1661                                                 }
1662                                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1663                                                 if (OLCP_indicate) {
1664                                                         _bt_otp_send_indication(char_path, &info, &addr_hex);
1665                                                 }
1666                                         }
1667                                 } else {
1668                                         BT_ERR("Array Len 0");
1669                                 }
1670                         } else {
1671                                 BT_ERR("var==NULL");
1672                         }
1673                 } else if (!g_strcmp0(property, "ReadValue")) {
1674                         gchar *addr = NULL;
1675                         guint8 req_id = 1;
1676                         guint16 offset = 0;
1677                         char *value = NULL;
1678                         int len = 0;
1679                         result = BLUETOOTH_ERROR_NONE;
1680
1681                         BT_INFO("ReadValue");
1682                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1683
1684                         g_variant_get(var, "(&s&s&syq)", &char_path,
1685                                         &svc_handle, &addr, &req_id, &offset);
1686
1687                         result = _bt_otp_read_cb(char_path, &value, &len);
1688
1689                         if (result != BLUETOOTH_ERROR_NONE) {
1690                                 BT_ERR("ReadValue failed %s", char_path);
1691                                 bluetooth_gatt_send_response(req_id,
1692                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1693                                                 result, offset, NULL, 0);
1694                         } else {
1695                                 bluetooth_gatt_send_response(req_id,
1696                                 BLUETOOTH_GATT_ATT_REQUEST_TYPE_READ,
1697                                                 result, offset, value, len);
1698                                 if (value)
1699                                         g_free(value);
1700                         }
1701                 } else if (!g_strcmp0(property, "NotificationStateChanged")) {
1702                         gboolean indicate = FALSE;
1703
1704                         g_variant_get(var, "(&s&sb)", &char_path,
1705                                                 &svc_handle, &indicate);
1706
1707                         BT_INFO("%s : [%s]", property,
1708                                 indicate ? "StartNotify" : "StopNotify");
1709                         BT_INFO("Type '%s'\n", g_variant_get_type_string(var));
1710
1711                         if (!g_strcmp0(char_path, otp_oacp_obj_path)) {
1712                                 OACP_indicate = indicate;
1713                         } else if (!g_strcmp0(char_path, otp_olcp_obj_path)) {
1714                                 OLCP_indicate = indicate;
1715                         }
1716                 }
1717         }
1718         return;
1719 }
1720
1721 void _bt_otp_property_event_filter(GDBusConnection *connection,
1722                                         const gchar *sender_name,
1723                                         const gchar *object_path,
1724                                         const gchar *interface_name,
1725                                         const gchar *signal_name,
1726                                         GVariant *parameters,
1727                                         gpointer user_data)
1728 {
1729         GVariant *value;
1730
1731         if (signal_name == NULL) {
1732                 BT_ERR("Wrong Signal");
1733                 return;
1734         }
1735
1736         if (g_strcmp0(signal_name, PROPERTIES_CHANGED) == 0) {
1737
1738                 g_variant_get(parameters, "(@a{sv}@as)", &value, NULL);
1739                 _bt_otp_gatt_char_property_changed_event(value, object_path);
1740         }
1741 }
1742
1743 void _bt_otp_adapter_event_filter(GDBusConnection *connection,
1744                                         const gchar *sender_name,
1745                                         const gchar *object_path,
1746                                         const gchar *interface_name,
1747                                         const gchar *signal_name,
1748                                         GVariant *parameters,
1749                                         gpointer user_data)
1750 {
1751         if (signal_name == NULL) {
1752                 BT_ERR("Wrong Signal");
1753                 return;
1754         }
1755
1756         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
1757
1758         if (g_strcmp0(interface_name, BT_OTP_INTERFACE_NAME) == 0) {
1759                 if (strcasecmp(signal_name, BLE_DISABLED) == 0) {
1760                         _bt_otp_exit();
1761                 }
1762         }
1763 }
1764
1765 void _bt_otc_disconnected_cb(GDBusConnection *connection,
1766                                         const gchar *sender_name,
1767                                         const gchar *object_path,
1768                                         const gchar *interface_name,
1769                                         const gchar *signal_name,
1770                                         GVariant *parameters,
1771                                         gpointer user_data)
1772 {
1773         if (signal_name == NULL) {
1774                 BT_ERR("Wrong Signal");
1775                 return;
1776         }
1777
1778         BT_INFO("Interface %s, Signal %s", interface_name, signal_name);
1779
1780         if (g_strcmp0(interface_name, BT_DEVICE_INTERFACE) == 0) {
1781                 if (strcasecmp(signal_name, OTC_DISCONNECTED) == 0) {
1782                         BT_DBG("OTC Channel Disconnected dev_path[%s]",
1783                                                                 object_path);
1784                         otc_connection_status = FALSE;
1785                         _bt_otp_free_oacp_op();
1786                 }
1787         }
1788 }
1789
1790 int _bt_otp_init_event_receiver()
1791 {
1792         BT_DBG("+");
1793         GError *error = NULL;
1794
1795         if (conn == NULL) {
1796                 conn =  g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
1797                 if (error != NULL) {
1798                         BT_ERR("ERROR: Can't get on system bus [%s]",
1799                                                         error->message);
1800                         g_clear_error(&error);
1801                 }
1802         }
1803
1804         property_sub_id = g_dbus_connection_signal_subscribe(conn,
1805                                 NULL,
1806                                 BT_OTP_INTERFACE_NAME,
1807                                 PROPERTIES_CHANGED,
1808                                 BT_OTP_OBJECT_PATH, NULL, 0,
1809                                 _bt_otp_property_event_filter,
1810                                 NULL, NULL);
1811
1812         adapter_sub_id = g_dbus_connection_signal_subscribe(conn,
1813                                 NULL,
1814                                 BT_OTP_INTERFACE_NAME,
1815                                 BLE_DISABLED,
1816                                 BT_OTP_OBJECT_PATH, NULL, 0,
1817                                 _bt_otp_adapter_event_filter,
1818                                 NULL, NULL);
1819
1820         device_sub_id = g_dbus_connection_signal_subscribe(conn,
1821                                         NULL, BT_DEVICE_INTERFACE,
1822                                         OTC_DISCONNECTED, NULL, NULL, 0,
1823                                         _bt_otc_disconnected_cb,
1824                                         NULL, NULL);
1825
1826         BT_DBG("-");
1827         return 0;
1828 }
1829
1830 void _bt_otp_deinit_event_receiver(void)
1831 {
1832         BT_DBG("+");
1833
1834         g_dbus_connection_signal_unsubscribe(conn, property_sub_id);
1835         g_dbus_connection_signal_unsubscribe(conn, adapter_sub_id);
1836         g_dbus_connection_signal_unsubscribe(conn, device_sub_id);
1837         conn = NULL;
1838
1839         BT_DBG("-");
1840 }
1841
1842 static void _bt_otp_sig_handler(int sig)
1843 {
1844         BT_DBG("+");
1845         switch (sig) {
1846         case SIGTERM:
1847                 BT_DBG("caught signal - sigterm\n");
1848                 break;
1849         case SIGINT:
1850                 BT_DBG("caught signal - sigint\n");
1851                 break;
1852         case SIGKILL:
1853                 BT_DBG("caught signal - sigkill\n");
1854                 break;
1855         default:
1856                 BT_DBG("caught signal %d and ignored\n", sig);
1857                 break;
1858         }
1859         BT_DBG("-");
1860 }
1861
1862 /* OTP Service Main loop */
1863 int main(void)
1864 {
1865         struct sigaction sa;
1866         BT_ERR("Starting the bt-otp daemon");
1867
1868         memset(&sa, 0, sizeof(sa));
1869         sa.sa_handler = _bt_otp_sig_handler;
1870         sa.sa_flags = SA_SIGINFO;
1871         sigaction(SIGINT, &sa, NULL);
1872         sigaction(SIGTERM, &sa, NULL);
1873         sigaction(SIGKILL, &sa, NULL);
1874
1875         if (_bt_otp_register_interface() != BLUETOOTH_ERROR_NONE) {
1876                 BT_ERR("Fail to register otp service");
1877                 return -4;
1878         }
1879
1880         if (_bt_otp_init_event_receiver() != BLUETOOTH_ERROR_NONE) {
1881                 BT_ERR("Fail to init event reciever");
1882                 return -5;
1883         }
1884
1885         main_loop = g_main_loop_new(NULL, FALSE);
1886
1887         g_main_loop_run(main_loop);
1888
1889         BT_DBG("g_main_loop_quit called!");
1890
1891         if (main_loop != NULL) {
1892                 g_main_loop_unref(main_loop);
1893         }
1894
1895         return 0;
1896 }