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