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