913c7b83175a46b9b653b504031be96bb3e93039
[platform/core/connectivity/bluetooth-frwk.git] / bt-oal / bluez_hal / src / bt-hal-gatt-server.c
1 /*
2  * BLUETOOOTH HAL
3  *
4  * Copyright (c) 2015 - 2016 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact:  Anupam Roy <anupam.r@samsung.com>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *              http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21
22 #include <hardware/bluetooth.h>
23 #include <hardware/bt_gatt.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 #include <string.h>
28 #include <gio/gio.h>
29 #include <glib.h>
30 #include <dlog.h>
31 #include <vconf.h>
32 #include <stdbool.h>
33 #include <stddef.h>
34 #include <string.h>
35 #include <fcntl.h>
36
37 #include "bt-hal.h"
38 #include "bt-hal-log.h"
39 #include "bt-hal-msg.h"
40 #include "bt-hal-utils.h"
41 #include "bt-hal-dbus-common-utils.h"
42
43 #include "bt-hal-adapter-le.h"
44 #include "bt-hal-event-receiver.h"
45
46 #define NUMBER_OF_FLAGS 10
47
48 #define GATT_SERV_INTERFACE             "org.bluez.GattService1"
49 #define GATT_CHAR_INTERFACE             "org.bluez.GattCharacteristic1"
50 #define GATT_DESC_INTERFACE             "org.bluez.GattDescriptor1"
51
52 #define BT_GATT_SERVICE_NAME    "org.frwk.gatt_service"
53 #define GATT_SERV_OBJECT_PATH   "/service"
54
55 static GDBusProxy *manager_gproxy = NULL;
56
57 /************************************************************************************
58  **  Static variables
59  ************************************************************************************/
60 extern const btgatt_callbacks_t *bt_gatt_callbacks;
61 guint owner_id;
62 GDBusConnection *g_conn = NULL;
63 //GDBusConnection *conn = NULL;
64 GDBusNodeInfo *manager_node_info = NULL;
65 guint manager_id;
66
67 /* Global handles which needs to be incremented during each addition */
68 static int gatt_service_handle = 10;
69 static int gatt_char_handle = 20;
70 static int gatt_desc_handle = 30;
71
72 struct gatt_service_info {
73         gchar *serv_path;
74         guint serv_id;
75         gchar *service_uuid;
76         guint manager_id;
77         guint prop_id;
78         GSList *char_data;
79         gboolean is_svc_registered;
80         gboolean is_svc_primary;
81         int service_handle;
82 };
83
84 struct gatt_char_info {
85         gchar *char_path;
86         guint char_id;
87         gchar *char_uuid;
88         gchar *char_value;
89         gchar *char_flags[NUMBER_OF_FLAGS];
90         int value_length;
91         int flags_length;
92         int char_handle;
93         GSList *desc_data;
94 };
95
96 struct gatt_desc_info {
97         gchar *desc_path;
98         guint desc_id;
99         gchar *desc_uuid;
100         gchar *desc_value;
101         gchar *desc_flags[NUMBER_OF_FLAGS];
102         int value_length;
103         int flags_length;
104         int desc_handle;
105 };
106
107 /**
108  * GATT Server Request type
109  */
110 typedef enum {
111         BT_HAL_GATT_REQUEST_TYPE_READ = 0x00,       /* Read Requested */
112         BT_HAL_GATT_REQUEST_TYPE_WRITE = 0x01,      /* Write Requested */
113         BT_HAL_GATT_REQUEST_TYPE_EXEC_WRITE = 0x02, /* Exec Write Requested */
114         BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_WRITE = 0x03, /* Exec Write Requested */
115         BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_NOTIFY = 0x04, /* Exec Write Requested */
116 } bt_gatt_request_type_e;
117
118 struct gatt_req_info {
119         gchar *attr_path;
120         gchar *svc_path;
121         guint  request_id;
122         guint  offset;
123         bt_gatt_request_type_e request_type;  /* Read or Write request */
124         GDBusMethodInvocation *context;
125 };
126
127 struct gatt_server_app {
128         int slot;
129         char *app_path;
130         GSList *services;
131 };
132
133 /* Linked List of gatt server app's */
134 static GSList *gatt_server_apps = NULL;
135
136 static GSList *gatt_services = NULL;
137
138 static int conn_id = 0;
139
140 /* Linked List of connected Remote GATT clients */
141 static GSList *gatt_client_info_list = NULL;
142
143 /* GATT Client Info List Structure */
144 struct gatt_client_info_t {
145         int connection_id;                               /* This value will uniquely identify a GATT client-server connection */
146         int instance_id;                                 /* This value unique identifies a GATT server instance */
147         char *addr;                                      /* Remote GATT client address */
148         GSList *gatt_req_info_list;                              /* List of transactions per Connection*/
149 };
150
151 static handle_stack_msg event_cb = NULL;
152
153 typedef struct {
154         uint32_t instance_data;
155         bt_uuid_t uuid;
156 } hal_register_server_data;
157
158 typedef struct {
159         uint32_t instance_data;
160         uint32_t srvc_hdl;
161         bt_uuid_t uuid;
162         uint8_t is_primary;
163 } hal_gatt_service_added;
164
165 typedef struct {
166         uint32_t instance_data;
167         uint32_t srvc_hdl;
168 } hal_gatt_service_started;
169
170 typedef struct {
171         uint32_t instance_data;
172         uint32_t srvc_hdl;
173 } hal_gatt_service_deleted;
174
175 typedef struct {
176         uint32_t instance_data;
177         uint32_t srvc_hdl;
178         uint32_t char_hdl;
179         bt_uuid_t uuid;
180 } hal_gatt_char_added;
181
182 typedef struct {
183         uint32_t instance_data;
184         uint32_t srvc_hdl;
185         uint32_t desc_hdl;
186         bt_uuid_t uuid;
187 } hal_gatt_desc_added;
188
189 #define CHECK_BTGATT_INIT() if (bt_gatt_callbacks == NULL)\
190 {\
191         ERR("%s: BTGATT not initialized", __FUNCTION__);\
192         return BT_STATUS_NOT_READY;\
193 } else {\
194         DBG("%s", __FUNCTION__);\
195 }
196
197 static gboolean __bt_hal_gatt_service_added_cb(gpointer user_data);
198
199 static void __bt_hal_gatt_deinit(char *app_path);
200
201 static void __bt_hal_register_application_cb(GObject *object,
202                                 GAsyncResult *res, gpointer user_data);
203
204 static void __bt_hal_unregister_application_cb(GObject *object, GAsyncResult *res,
205                 gpointer user_data);
206
207 static GDBusProxy *__bt_gatt_gdbus_get_gatt_manager_proxy(const gchar *service,
208                 const gchar *path, const gchar *interface);
209
210 /* Introspection data for the service we are exporting */
211 static const gchar service_introspection_xml[] =
212 "<node name='/'>"
213 "  <interface name='org.freedesktop.DBus.Properties'>"
214 "    <property type='s' name='UUID' access='read'>"
215 "    </property>"
216 "        <property type='b' name='primary' access='read'>"
217 "        </property>"
218 "        <property type='o' name='Device' access='read'>"
219 "        </property>"
220 "        <property type='ao' name='Characteristics' access='read'>"
221 "        </property>"
222 "        <property type='s' name='Includes' access='read'>"
223 "        </property>"
224 "  </interface>"
225 "</node>";
226
227 /* Introspection data for the characteristics we are exporting */
228 static const gchar characteristics_introspection_xml[] =
229 "<node name='/'>"
230 "  <interface name='org.bluez.GattCharacteristic1'>"
231 "        <method name='ReadValue'>"
232 "               <arg type='s' name='address' direction='in'/>"
233 "               <arg type='u' name='id' direction='in'/>"
234 "               <arg type='q' name='offset' direction='in'/>"
235 "               <arg type='ay' name='Value' direction='out'/>"
236 "        </method>"
237 "        <method name='WriteValue'>"
238 "               <arg type='s' name='address' direction='in'/>"
239 "               <arg type='u' name='id' direction='in'/>"
240 "               <arg type='q' name='offset' direction='in'/>"
241 "               <arg type='b' name='response_needed' direction='in'/>"
242 "               <arg type='ay' name='value' direction='in'/>"
243 "        </method>"
244 "       <method name ='AcquireWrite'>"
245 "      <arg type='a{sv}' name='properties' direction='in'/>"
246 "               <arg type='h' name='fd' direction='out'/>"
247 "               <arg type='q' name='mtu' direction='out'/>"
248 "        </method>"
249 "       <method name = 'AcquireNotify'>"
250 "               <arg type='a{sv}' name='properties' direction='in'/>"
251 "               <arg type='h' name='fd' direction='out'/>"
252 "               <arg type='q' name='mtu' direction='out'/>"
253 "        </method>"
254 "        <method name='StartNotify'>"
255 "        </method>"
256 "        <method name='StopNotify'>"
257 "        </method>"
258 "        <method name='IndicateConfirm'>"
259 "               <arg type='s' name='address' direction='in'/>"
260 "               <arg type='b' name='complete' direction='in'/>"
261 "        </method>"
262 "  </interface>"
263 "  <interface name='org.freedesktop.DBus.Properties'>"
264 "    <property type='s' name='UUID' access='read'>"
265 "    </property>"
266 "    <property type='o' name='Service' access='read'>"
267 "    </property>"
268 "    <property type='ay' name='Value' access='readwrite'>"
269 "    </property>"
270 "        <property type='b' name='Notifying' access='read'>"
271 "        </property>"
272 "    <property type='as' name='Flags' access='read'>"
273 "    </property>"
274 "    <property type='s' name='Unicast' access='read'>"
275 "    </property>"
276 "        <property type='ao' name='Descriptors' access='read'>"
277 "        </property>"
278 "        <property type='b' name='WriteAcquired' access='read'>"
279 "        </property>"
280 "        <property type='b' name='NotifyAcquired' access='read'>"
281 "        </property>"
282 "  </interface>"
283 "</node>";
284
285 /* Introspection data for the descriptor we are exporting */
286 static const gchar descriptor_introspection_xml[] =
287 "<node name='/'>"
288 "  <interface name='org.bluez.GattDescriptor1'>"
289 "        <method name='ReadValue'>"
290 "               <arg type='s' name='address' direction='in'/>"
291 "               <arg type='u' name='id' direction='in'/>"
292 "               <arg type='q' name='offset' direction='in'/>"
293 "               <arg type='ay' name='Value' direction='out'/>"
294 "        </method>"
295 "        <method name='WriteValue'>"
296 "               <arg type='s' name='address' direction='in'/>"
297 "               <arg type='u' name='id' direction='in'/>"
298 "               <arg type='q' name='offset' direction='in'/>"
299 "               <arg type='b' name='response_needed' direction='in'/>"
300 "               <arg type='ay' name='value' direction='in'/>"
301 "        </method>"
302 "  </interface>"
303 "  <interface name='org.freedesktop.DBus.Properties'>"
304 "    <property type='s' name='UUID' access='read'>"
305 "    </property>"
306 "    <property type='o' name='Characteristic' access='read'>"
307 "    </property>"
308 "    <property type='ay' name='Value' access='read'>"
309 "    </property>"
310 "    <property type='as' name='Flags' access='read'>"
311 "    </property>"
312 "  </interface>"
313 "</node>";
314
315
316 static const gchar manager_introspection_xml[] =
317 "<node name='/'>"
318 "  <interface name='org.freedesktop.DBus.ObjectManager'>"
319 "    <method name='GetManagedObjects'>"
320 "     <arg type='a{oa{sa{sv}}}' name='object_paths_interfaces_and_properties' direction='out'/>"
321 "        </method>"
322 "  </interface>"
323 "</node>";
324
325 GSList *_bt_get_service_list_from_server(int instance)
326 {
327         GSList *l;
328         INFO("Number of GATT Server apps [%d]", g_slist_length(gatt_server_apps));
329         INFO("Find App with slot [%d]", instance);
330
331         for (l = gatt_server_apps; l; l = g_slist_next(l)) {
332                 struct gatt_server_app *app = (struct gatt_server_app *)l->data;
333
334                 if (app->slot == instance) {
335                         INFO("App slot [%d] Found, Number of services registered [%d]",
336                                         app->slot, g_slist_length(app->services));
337                         return app->services;
338                 }
339         }
340         return NULL;
341 }
342
343 void _bt_remote_service_from_gatt_server(int instance, int service_handle)
344 {
345         GSList *l;
346         GSList *l1;
347
348         for (l = gatt_server_apps; l; l = g_slist_next(l)) {
349                 struct gatt_server_app *app = (struct gatt_server_app *)l->data;
350
351                 if (app->slot == instance) {
352                         for (l1 = app->services; l1; l1 = g_slist_next(l1)) {
353                                 struct gatt_service_info *srv = (struct gatt_service_info *)l1->data;
354                                 if (srv->service_handle == service_handle) {
355                                         app->services = g_slist_remove(app->services, srv);
356                                         return;
357                                 }
358                         }
359                 }
360         }
361 }
362
363 void _bt_hal_update_gatt_service_in_gatt_server(int slot, struct gatt_service_info *serv_info)
364 {
365         GSList *l;
366         for (l = gatt_server_apps; l; l = g_slist_next(l)) {
367                 struct gatt_server_app *app = (struct gatt_server_app *)l->data;
368
369                 if (app->slot == slot) {
370                         INFO("Updating service in GATT server's service list service handle [%d] slot [%d]",
371                                 serv_info->service_handle, slot);
372                         app->services = g_slist_append(app->services, serv_info);
373                 }
374         }
375 }
376
377 static struct gatt_client_info_t *__bt_find_remote_gatt_client_info(char *address)
378 {
379         GSList *l;
380         struct gatt_client_info_t *info = NULL;
381
382         for (l = gatt_client_info_list; l != NULL; l = g_slist_next(l)) {
383                 info = (struct gatt_client_info_t*)l->data;
384                 if (info == NULL)
385                         continue;
386
387                 if (!g_strcmp0(info->addr, address)) {
388                         INFO("Remote GATT client found addr[%s]", info->addr);
389                         return info;
390                 }
391         }
392         return NULL;
393 }
394
395 static struct gatt_client_info_t *__bt_find_remote_gatt_client_info_from_conn(int conn_id)
396 {
397         GSList *l;
398         struct gatt_client_info_t *info = NULL;
399
400         for (l = gatt_client_info_list; l != NULL; l = g_slist_next(l)) {
401                 info = (struct gatt_client_info_t*)l->data;
402                 if (info == NULL)
403                         continue;
404
405                 if (info->connection_id == conn_id) {
406                         INFO("Remote GATT client found addr[%s]", info->addr);
407                         return info;
408                 }
409         }
410         return NULL;
411 }
412
413 static struct gatt_req_info *__bt_find_remote_gatt_client_request_info(int conn_id, int trans_id)
414 {
415         GSList *l;
416         GSList *l1;
417
418         struct gatt_client_info_t *info = NULL;
419         struct gatt_req_info *info1 = NULL;
420
421         for (l = gatt_client_info_list; l != NULL; l = g_slist_next(l)) {
422                 info = (struct gatt_client_info_t*)l->data;
423
424                 if (info == NULL)
425                         continue;
426                 if (info->connection_id == conn_id) {
427
428                         for (l1 = info->gatt_req_info_list; l1; l1 = g_slist_next(l1)) {
429
430                                 info1 = (struct gatt_req_info*)l1->data;
431                                 if (info1 == NULL)
432                                         continue;
433
434                                 if (info1->request_id == trans_id) {
435                                         INFO("Remote GATT client found addr[%s]", info->addr);
436                                         return info1;
437                                 }
438                         }
439                 }
440         }
441         return NULL;
442 }
443
444 void _bt_hal_gatt_connected_state_event(gboolean is_connected, char *address)
445 {
446         struct hal_ev_gatt_server_connected ev;
447         struct gatt_client_info_t *conn_info = NULL;
448         int instance = -1;
449         memset(&ev, 0, sizeof(ev));
450
451         /* Find Server Instance */
452         _bt_hal_get_gatt_server_instance_initialized(&instance);
453         if (instance == -1) {
454                 ERR("Not even a single GATT server is registered");
455                 return;
456         }
457
458         /* Convert address to hex */
459         _bt_hal_convert_addr_string_to_type(ev.bdaddr, address);
460
461         /* Create Connection ID */
462         /* Check if device is already in connected list */
463         conn_info = __bt_find_remote_gatt_client_info(address);
464
465
466         /* If disconnected, and conn info found, then remove conn info */
467         if (is_connected == FALSE) {
468                 DBG("GATT Disconnected");
469                 if (conn_info) {
470                         INFO("Remove GATT client info from List..");
471                         /* Remove info from List */
472                         gatt_client_info_list = g_slist_remove(gatt_client_info_list, conn_info);
473                         INFO("Total num of connected GATT clients [%d]", g_slist_length(gatt_client_info_list));
474
475                         if (!event_cb)
476                                 ERR("GATT callback not registered");
477                         else {
478                                 DBG("GATT callback registered: server if [%d] Is Connected [%d] addr[%s] conn ID [%d]",
479                                                 conn_info->instance_id, is_connected, conn_info->addr, conn_info->connection_id);
480                                 ev.conn_id = conn_info->connection_id;
481                                 ev.server_instance = conn_info->instance_id;
482                                 ev.connected = is_connected;
483
484                                 event_cb(HAL_EV_GATT_SERVER_CONNECTED, (void *)&ev, sizeof(ev));
485                         }
486                         g_free(conn_info->addr);
487                         g_free(conn_info);
488                 }
489                 /* If connected, and conn info NOT found, then add conn info */
490         } else {
491                 if (!conn_info) {
492                         /* Save Connection info */
493                         conn_info = g_new0(struct gatt_client_info_t, 1);
494                         conn_info->addr = g_strdup(address);
495                         INFO("Added GATT client addr[%s]", conn_info->addr);
496                         conn_info->connection_id = ++conn_id;
497                         conn_info->instance_id = instance;
498                         gatt_client_info_list = g_slist_append(gatt_client_info_list, conn_info);
499                         INFO("Total num of connected GATT clients [%d]", g_slist_length(gatt_client_info_list));
500
501                         if (!event_cb)
502                                 ERR("GATT callback not registered");
503                         else {
504                                 DBG("GATT callback registered: server if [%d] Is Connected [%d] addr[%s] conn ID [%d]",
505                                                 conn_info->instance_id, is_connected, conn_info->addr, conn_info->connection_id);
506                                 ev.conn_id = conn_info->connection_id;
507                                 ev.server_instance = conn_info->instance_id;
508                                 ev.connected = is_connected;
509
510                                 event_cb(HAL_EV_GATT_SERVER_CONNECTED, (void *)&ev, sizeof(ev));
511                         }
512                 }
513         }
514         /* Send GATT connected or disconnected event */
515 }
516
517 static struct gatt_service_info *__bt_gatt_find_gatt_service_from_char(const char *char_path, int *char_hdl)
518 {
519         GSList *l1, *l2;
520
521         for (l1 = gatt_services; l1 != NULL; l1 = l1->next) {
522                 struct gatt_service_info *serv_info = l1->data;
523
524                 for (l2 = serv_info->char_data; l2 != NULL; l2 = l2->next) {
525                         struct gatt_char_info *char_info = l2->data;
526
527                         if (g_strcmp0(char_info->char_path, char_path)
528                                         == 0) {
529                                 *char_hdl = char_info->char_handle;
530                                 return serv_info;
531                         }
532                 }
533         }
534         ERR("Gatt service not found");
535         return NULL;
536 }
537
538 char *__bt_gatt_find_char_path_from_handle(int char_hdl)
539 {
540         GSList *l1, *l2;
541
542         for (l1 = gatt_services; l1 != NULL; l1 = l1->next) {
543                 struct gatt_service_info *serv_info = l1->data;
544
545                 for (l2 = serv_info->char_data; l2 != NULL; l2 = l2->next) {
546                         struct gatt_char_info *char_info = l2->data;
547
548                         if (char_info->char_handle == char_hdl)
549                                 return char_info->char_path;
550                 }
551         }
552         ERR("Not found");
553         return NULL;
554 }
555
556 struct gatt_char_info *__bt_gatt_find_char_info_from_handle(int char_hdl)
557 {
558         GSList *l1, *l2;
559
560         for (l1 = gatt_services; l1 != NULL; l1 = l1->next) {
561                 struct gatt_service_info *serv_info = l1->data;
562
563                 for (l2 = serv_info->char_data; l2 != NULL; l2 = l2->next) {
564                         struct gatt_char_info *char_info = l2->data;
565
566                         if (char_info->char_handle == char_hdl)
567                                 return char_info;
568                 }
569         }
570         ERR("Not found");
571         return NULL;
572 }
573
574 static struct gatt_service_info *__bt_gatt_find_gatt_service_from_desc(const char *desc_path, int *desc_hdl)
575 {
576         GSList *l1, *l2, *l3;
577
578         for (l1 = gatt_services; l1 != NULL; l1 = l1->next) {
579                 struct gatt_service_info *serv_info = l1->data;
580
581                 for (l2 = serv_info->char_data; l2 != NULL; l2 = l2->next) {
582                         struct gatt_char_info *char_info = l2->data;
583
584                         for (l3 = char_info->desc_data; l3 != NULL; l3 = l3->next) {
585                                 struct gatt_desc_info *desc_info = l3->data;
586
587                                 if (g_strcmp0(desc_info->desc_path, desc_path)
588                                                 == 0) {
589                                         *desc_hdl = desc_info->desc_handle;
590                                         return serv_info;
591                                 }
592                         }
593                 }
594         }
595         ERR("Gatt service not found");
596         return NULL;
597 }
598
599 static void __bt_gatt_manager_method_call(GDBusConnection *connection,
600                 const gchar *sender,
601                 const gchar *object_path,
602                 const gchar *interface_name,
603                 const gchar *method_name,
604                 GVariant *parameters,
605                 GDBusMethodInvocation *invocation,
606                 gpointer user_data)
607 {
608         GSList *l = NULL;
609
610         if (g_strcmp0(method_name, "GetManagedObjects") == 0) {
611                 GVariantBuilder *builder;
612                 GVariantBuilder *inner_builder1 = NULL;
613                 GVariant *svc_char = NULL;
614                 GSList *l4;
615                 GSList *gatt_services = NULL;
616                 int *instance;
617                 instance = (int*)user_data;
618                 gboolean writeAcquired = FALSE;
619                 gboolean notifyAcquired = FALSE;
620
621                 DBG("Getting values for service, chars and descriptors");
622                 DBG("GATT Server App for which services are requested [%d]", *instance);
623
624                 /*Main Builder */
625                 builder = g_variant_builder_new(
626                                 G_VARIANT_TYPE("a{oa{sa{sv}}}"));
627
628
629                 gatt_services = _bt_get_service_list_from_server(*instance);
630
631                 if (g_slist_length(gatt_services) == 0) {
632                         ERR("No registered GATT services!!!!");
633                         g_dbus_method_invocation_return_value(invocation, NULL);
634                         g_variant_builder_unref(builder);
635                         return;
636                 }
637
638                 for (l = gatt_services; l != NULL; l = l->next) {
639                         GVariantBuilder *svc_builder = NULL;
640                         GVariantBuilder *inner_builder = NULL;
641                         struct gatt_service_info *serv_info = l->data;
642                         INFO("GATT Service fetched handle [%d]", serv_info->service_handle);
643
644                         /* Prepare inner builder for GattService1 interface */
645                         DBG("Creating builder for service");
646                         svc_builder = g_variant_builder_new(
647                                         G_VARIANT_TYPE("a{sa{sv}}"));
648                         inner_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
649
650                         g_variant_builder_add(inner_builder, "{sv}", "UUID",
651                                         g_variant_new_string(serv_info->service_uuid));
652
653                         g_variant_builder_add(inner_builder, "{sv}", "Primary",
654                                         g_variant_new_boolean(serv_info->is_svc_primary));
655
656                         /*Characteristics*/
657                         inner_builder1 = g_variant_builder_new(G_VARIANT_TYPE("ao"));
658                         DBG("Adding Charatarisitcs list");
659                         for (l4 = serv_info->char_data; l4 != NULL; l4 = l4->next) {
660                                 struct gatt_char_info *char_info = l4->data;
661                                 INFO("GATT Char handle [%d] found in GATT service handle [%d]",
662                                                 char_info->char_handle, serv_info->service_handle);
663                                 g_variant_builder_add(inner_builder1, "o",
664                                                 char_info->char_path);
665                                 DBG("%s", char_info->char_path);
666                         }
667
668                         svc_char = g_variant_new("ao", inner_builder1);
669                         g_variant_builder_add(inner_builder, "{sv}", "Characteristics",
670                                         svc_char);
671
672                         g_variant_builder_add(svc_builder, "{sa{sv}}",
673                                         GATT_SERV_INTERFACE,
674                                         inner_builder);
675
676                         g_variant_builder_add(builder, "{oa{sa{sv}}}",
677                                         serv_info->serv_path,
678                                         svc_builder);
679
680                         g_variant_builder_unref(inner_builder1);
681
682                         /* Prepare inner builder for GattCharacteristic1 interface */
683
684                         GSList *l2 = serv_info->char_data;
685                         DBG("Creating builder for characteristics \n");
686
687                         if (l2 == NULL)
688                                 DBG("characteristic data is NULL");
689
690                         for (l2 = serv_info->char_data; l2 != NULL; l2 = l2->next) {
691
692                                 GVariantBuilder *char_builder = NULL;
693                                 GVariantBuilder *inner_builder = NULL;
694                                 GVariantBuilder *builder1 = NULL;
695                                 GVariantBuilder *builder2 = NULL;
696                                 GVariantBuilder *builder3 = NULL;
697                                 GVariant *char_val = NULL;
698                                 GVariant *flags_val = NULL;
699                                 GVariant *char_desc = NULL;
700                                 char *unicast = NULL;
701                                 gboolean notify = FALSE;
702                                 int i = 0;
703
704                                 char_builder = g_variant_builder_new(
705                                                 G_VARIANT_TYPE(
706                                                         "a{sa{sv}}"));
707                                 inner_builder = g_variant_builder_new(
708                                                 G_VARIANT_TYPE(
709                                                         "a{sv}"));
710
711                                 struct gatt_char_info *char_info = l2->data;
712                                 if (char_info == NULL) {
713                                         ERR("char_info is NULL");
714                                         continue;
715                                 }
716
717                                 /*Uuid*/
718                                 g_variant_builder_add(inner_builder, "{sv}", "UUID",
719                                                 g_variant_new_string(char_info->char_uuid));
720                                 /*Service*/
721                                 g_variant_builder_add(inner_builder, "{sv}", "Service",
722                                                 g_variant_new("o", serv_info->serv_path));
723                                 /*Value*/
724                                 builder1 = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
725
726                                 if (char_info->char_value != NULL) {
727                                         for (i = 0; i < char_info->value_length; i++) {
728                                                 g_variant_builder_add(builder1, "y",
729                                                                 char_info->char_value[i]);
730                                         }
731                                         char_val = g_variant_new("ay", builder1);
732                                         g_variant_builder_add(inner_builder, "{sv}",
733                                                         "Value", char_val);
734                                 }
735                                 /*Flags*/
736                                 builder2 = g_variant_builder_new(G_VARIANT_TYPE("as"));
737                                 for (i = 0; i < char_info->flags_length; i++) {
738                                         g_variant_builder_add(builder2, "s",
739                                                         char_info->char_flags[i]);
740                                         if (strncmp(char_info->char_flags[i], "write-without-response", 16) == 0)
741                                                 writeAcquired = TRUE;
742
743                                         if (strncmp(char_info->char_flags[i], "notify", 4) == 0)
744                                                 notifyAcquired = TRUE;
745                                 }
746
747                                 flags_val = g_variant_new("as", builder2);
748                                 g_variant_builder_add(inner_builder, "{sv}", "Flags",
749                                                 flags_val);
750
751                                 /* Notifying */
752                                 g_variant_builder_add(inner_builder, "{sv}", "Notifying",
753                                                 g_variant_new("b", notify));
754
755                                 /* Unicast */
756                                 g_variant_builder_add(inner_builder, "{sv}", "WriteAcquired",
757                                                                         g_variant_new("b", writeAcquired));
758
759                                 /* NotifyAcquired */
760                                                         g_variant_builder_add(inner_builder, "{sv}", "NotifyAcquired",
761                                                                         g_variant_new("b", notifyAcquired));
762
763                                 /* Unicast */
764                                 unicast = g_strdup("00:00:00:00:00:00");
765                                 g_variant_builder_add(inner_builder, "{sv}", "Unicast",
766                                                 g_variant_new("s", unicast));
767
768                                 /*Descriptors*/
769                                 builder3 = g_variant_builder_new(G_VARIANT_TYPE("ao"));
770                                 DBG("Adding Descriptors list");
771
772                                 for (l4 = char_info->desc_data; l4 != NULL; l4 = l4->next) {
773                                         struct gatt_desc_info *desc_info = l4->data;
774                                         INFO("GATT Descriptor handle [%d] found inside GATT Char handle [%d] found in GATT service handle [%d]",
775                                                         desc_info->desc_handle, char_info->char_handle, serv_info->service_handle);
776                                         g_variant_builder_add(builder3, "o",
777                                                         desc_info->desc_path);
778                                         DBG("%s", desc_info->desc_path);
779                                 }
780
781                                 char_desc = g_variant_new("ao", builder3);
782                                 g_variant_builder_add(inner_builder, "{sv}", "Descriptors",
783                                                 char_desc);
784
785                                 g_variant_builder_add(char_builder, "{sa{sv}}",
786                                                 GATT_CHAR_INTERFACE , inner_builder);
787                                 g_variant_builder_add(builder, "{oa{sa{sv}}}",
788                                                 char_info->char_path, char_builder);
789
790                                 /*Prepare inner builder for GattDescriptor1 interface*/
791
792                                 GSList *l3 = char_info->desc_data;
793
794                                 if (l3 == NULL)
795                                         DBG("descriptor data is NULL");
796
797                                 for (l3 = char_info->desc_data; l3 != NULL; l3 = l3->next) {
798
799                                         DBG("Creating builder for descriptor \n");
800
801                                         GVariantBuilder *desc_builder = NULL;
802                                         GVariantBuilder *inner_builder = NULL;
803                                         GVariantBuilder *builder1 = NULL;
804                                         GVariantBuilder *builder2 = NULL;
805                                         GVariant *desc_val = NULL;
806
807                                         desc_builder = g_variant_builder_new(
808                                                         G_VARIANT_TYPE(
809                                                                 "a{sa{sv}}"));
810                                         inner_builder = g_variant_builder_new(
811                                                         G_VARIANT_TYPE(
812                                                                 "a{sv}"));
813
814                                         struct gatt_desc_info *desc_info = l3->data;
815                                         if (desc_info == NULL) {
816                                                 ERR("desc_info is NULL");
817                                                 continue;
818                                         }
819
820                                         /*Uuid*/
821                                         g_variant_builder_add(inner_builder,
822                                                         "{sv}", "UUID",
823                                                         g_variant_new_string(
824                                                                 desc_info->desc_uuid));
825
826                                         /*Characteristic*/
827                                         g_variant_builder_add(inner_builder, "{sv}",
828                                                         "Characteristic",
829                                                         g_variant_new("o",
830                                                                 char_info->char_path));
831
832                                         /*Value*/
833                                         builder1 = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
834
835                                         if (desc_info->desc_value != NULL) {
836                                                 for (i = 0; i < desc_info->value_length; i++) {
837                                                         g_variant_builder_add(builder1, "y",
838                                                                         desc_info->desc_value[i]);
839                                                 }
840                                                 desc_val = g_variant_new("ay", builder1);
841                                                 g_variant_builder_add(inner_builder, "{sv}",
842                                                                 "Value", desc_val);
843                                         }
844
845                                         /*Flags*/
846                                         builder2 = g_variant_builder_new(G_VARIANT_TYPE("as"));
847
848                                         for (i = 0; i < desc_info->flags_length; i++) {
849                                                 g_variant_builder_add(builder2, "s",
850                                                                 desc_info->desc_flags[i]);
851                                         }
852
853                                         flags_val = g_variant_new("as", builder2);
854                                         g_variant_builder_add(inner_builder, "{sv}", "Flags",
855                                                         flags_val);
856
857                                         g_variant_builder_add(desc_builder, "{sa{sv}}",
858                                                         GATT_DESC_INTERFACE,
859                                                         inner_builder);
860
861                                         g_variant_builder_add(builder, "{oa{sa{sv}}}",
862                                                         desc_info->desc_path,
863                                                         desc_builder);
864
865                                         /*unref descriptor builder pointers*/
866                                         g_variant_builder_unref(builder1);
867                                         g_variant_builder_unref(builder2);
868                                         g_variant_builder_unref(inner_builder);
869                                         g_variant_builder_unref(desc_builder);
870                                 }
871
872                                 if (unicast)
873                                         g_free(unicast);
874                                 /*unref char builder pointers*/
875                                 g_variant_builder_unref(builder1);
876                                 g_variant_builder_unref(builder2);
877                                 g_variant_builder_unref(builder3);
878                                 g_variant_builder_unref(inner_builder);
879                                 g_variant_builder_unref(char_builder);
880                         }
881
882                         /*unref service builder pointers*/
883                         g_variant_builder_unref(inner_builder);
884                         g_variant_builder_unref(svc_builder);
885
886                 }
887                 /* Return builder as method reply */
888                 DBG("Sending gatt service builder values to Bluez");
889                 g_dbus_method_invocation_return_value(invocation,
890                                 g_variant_new(
891                                         "(a{oa{sa{sv}}})",
892                                         builder));
893         }
894
895         /* Free User Data */
896         g_free(user_data);
897 }
898
899 static void __bt_gatt_desc_method_call(GDBusConnection *connection,
900                 const gchar *sender,
901                 const gchar *object_path,
902                 const gchar *interface_name,
903                 const gchar *method_name,
904                 GVariant *parameters,
905                 GDBusMethodInvocation *invocation,
906                 gpointer user_data)
907 {
908
909         if (g_strcmp0(method_name, "ReadValue") == 0) {
910                 struct hal_ev_gatt_server_read_req ev;
911
912                 gchar *addr = NULL;
913                 guint req_id = 0;
914                 guint16 offset = 0;
915                 struct gatt_client_info_t *conn_info = NULL;
916                 struct gatt_req_info *req_info = NULL;
917                 struct gatt_service_info *svc_info = NULL;
918                 int desc_hdl = -1;
919
920                 DBG("ReadValue");
921                 DBG("Application path = %s", object_path);
922                 DBG("Sender = %s", sender);
923
924                 svc_info = __bt_gatt_find_gatt_service_from_desc(object_path, &desc_hdl);
925                 if (svc_info == NULL) {
926                         ERR("Coudn't find service for %s", object_path);
927                         g_dbus_method_invocation_return_value(invocation, NULL);
928                         return;
929                 }
930
931                 g_variant_get(parameters, "(&suq)", &addr, &req_id, &offset);
932                 DBG("Request id = %u, Offset = %u", req_id, offset);
933
934                 /* Check if device is already in connected list */
935                 conn_info = __bt_find_remote_gatt_client_info(addr);
936
937                 if (conn_info == NULL) {
938                         ERR("Coudn't find Connection info for %s", addr);
939                         g_dbus_method_invocation_return_value(invocation, NULL);
940                         return;
941                 }
942
943                 if (!event_cb) {
944                         ERR("GATT callback NOT registered");
945                         g_dbus_method_invocation_return_value(invocation, NULL);
946                         return;
947                 }
948
949                 /* Store requests information */
950                 req_info = g_new0(struct gatt_req_info, 1);
951                 req_info->attr_path = g_strdup(object_path);
952                 req_info->svc_path = g_strdup(svc_info->serv_path);
953                 req_info->request_id = req_id;
954                 req_info->offset = offset;
955                 req_info->context = invocation;
956
957                 /* Append request info in list of requests for the particular connection */
958                 conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
959
960                 /* Send HAL event */
961                 memset(&ev, 0, sizeof(ev));
962                 ev.conn_id = conn_info->connection_id;
963                 ev.trans_id = req_id;
964                 ev.att_handle = desc_hdl;
965                 ev.offset = offset;
966                 ev.is_long = false; /* TODO*/
967
968                 /* Convert address to hex */
969                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
970
971                 event_cb(HAL_EV_GATT_READ_REQUESTED, (void *)&ev, sizeof(ev));
972                 return;
973         } else if (g_strcmp0(method_name, "WriteValue") == 0) {
974
975                 GVariant *var = NULL;
976                 gchar *addr = NULL;
977                 guint req_id = 0;
978                 guint16 offset = 0;
979                 gboolean response_needed = FALSE;
980                 struct hal_ev_gatt_server_write_req ev;
981                 int desc_hdl = -1;
982                 int len;
983
984                 struct gatt_service_info *svc_info = NULL;
985                 struct gatt_client_info_t *conn_info = NULL;
986                 struct gatt_req_info *req_info = NULL;
987
988                 memset(&ev, 0, sizeof(ev));
989
990                 DBG("WriteValue");
991                 DBG("Application path = %s", object_path);
992                 DBG("Sender = %s", sender);
993
994                 g_variant_get(parameters, "(&suqb@ay)",
995                                 &addr, &req_id, &offset, &response_needed, &var);
996                 DBG("Request id = %u, Offset = %u", req_id, offset);
997
998                 /* Check if device is already in connected list */
999                 conn_info = __bt_find_remote_gatt_client_info(addr);
1000
1001                 svc_info = __bt_gatt_find_gatt_service_from_desc(object_path, &desc_hdl);
1002
1003                 if (conn_info == NULL || svc_info == NULL || event_cb == NULL) {
1004                         g_variant_unref(var);
1005                         if (response_needed)
1006                                 g_dbus_method_invocation_return_value(invocation, NULL);
1007                         else
1008                                 g_object_unref(invocation);
1009                         return;
1010                 }
1011
1012                 len = g_variant_get_size(var);
1013                 if (len > 0 && len < 600) {
1014                         char *data;
1015                         data = (char *)g_variant_get_data(var);
1016                         memcpy(ev.value, data, len);
1017                         ev.length = len;
1018                 }
1019                 if (response_needed) {
1020                         /* Store request information */
1021                         req_info = g_new0(struct gatt_req_info, 1);
1022                         req_info->attr_path = g_strdup(object_path);
1023                         req_info->svc_path = g_strdup(svc_info->serv_path);
1024                         req_info->request_id = req_id;
1025                         req_info->offset = offset;
1026                         req_info->context = invocation;
1027
1028                         /* Append request info in list of requests for the particular connection */
1029                         conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
1030                 } else {
1031                         g_object_unref(invocation);
1032                 }
1033
1034                 /* Send HAL event */
1035                 ev.conn_id = conn_info->connection_id;
1036                 ev.trans_id = req_id;
1037                 ev.att_handle = desc_hdl;
1038                 ev.offset = offset;
1039                 ev.need_rsp = response_needed;
1040                 ev.is_prep = 0;
1041
1042                 /* Convert address to hex */
1043                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
1044
1045                 event_cb(HAL_EV_GATT_WRITE_REQUESTED, (void *)&ev, sizeof(ev));
1046
1047                 g_variant_unref(var);
1048                 return;
1049         }
1050 }
1051
1052 static void __bt_gatt_char_method_call(GDBusConnection *connection,
1053                 const gchar *sender,
1054                 const gchar *object_path,
1055                 const gchar *interface_name,
1056                 const gchar *method_name,
1057                 GVariant *parameters,
1058                 GDBusMethodInvocation *invocation,
1059                 gpointer user_data)
1060 {
1061         if (g_strcmp0(method_name, "ReadValue") == 0) {
1062                 gchar *addr = NULL;
1063                 guint req_id = 0;
1064                 guint16 offset = 0;
1065                 struct hal_ev_gatt_server_read_req ev;
1066                 int char_hdl = -1;
1067
1068                 struct gatt_req_info *req_info = NULL;
1069                 struct gatt_client_info_t *conn_info = NULL;
1070                 struct gatt_service_info *svc_info = NULL;
1071
1072                 g_variant_get(parameters, "(&suq)",
1073                                         &addr, &req_id, &offset);
1074
1075                 DBG("Request id = %u, Offset = %u", req_id, offset);
1076                 DBG("Application path = %s", object_path);
1077                 DBG("Sender = %s", sender);
1078                 DBG("Address = %s", addr);
1079
1080                 /* Check if device is already in connected list */
1081                 conn_info = __bt_find_remote_gatt_client_info(addr);
1082
1083                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1084
1085                 if (svc_info == NULL || conn_info == NULL) {
1086                         g_dbus_method_invocation_return_value(invocation, NULL);
1087                         return;
1088                 }
1089
1090                 if (!event_cb) {
1091                         ERR("GATT callback NOT registered");
1092                         g_dbus_method_invocation_return_value(invocation, NULL);
1093                         return;
1094                 }
1095
1096                 /* Store requets information */
1097                 req_info = g_new0(struct gatt_req_info, 1);
1098                 req_info->attr_path = g_strdup(object_path);
1099                 req_info->svc_path = g_strdup(svc_info->serv_path);
1100                 req_info->request_id = req_id;
1101                 req_info->request_type = BT_HAL_GATT_REQUEST_TYPE_READ;
1102                 req_info->offset = offset;
1103                 req_info->context = invocation;
1104
1105                 /* Append request info in list of requests for the particular connection */
1106                 conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
1107
1108                 /* Send HAL event */
1109                 memset(&ev, 0, sizeof(ev));
1110                 ev.conn_id = conn_info->connection_id;
1111                 ev.trans_id = req_id;
1112                 ev.att_handle = char_hdl;
1113                 ev.offset = offset;
1114                 ev.is_long = false; /* TODO*/
1115
1116                 /* Convert address to hex */
1117                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
1118                 event_cb(HAL_EV_GATT_READ_REQUESTED, (void *)&ev, sizeof(ev));
1119                 return;
1120         } else if (g_strcmp0(method_name, "WriteValue") == 0) {
1121                 GVariant *var = NULL;
1122                 gchar *addr = NULL;
1123                 guint req_id = 0;
1124                 guint16 offset = 0;
1125                 gboolean response_needed = FALSE;
1126                 struct hal_ev_gatt_server_write_req ev;
1127                 int char_hdl = -1;
1128                 int len;
1129
1130                 struct gatt_service_info *svc_info = NULL;
1131                 struct gatt_req_info *req_info = NULL;
1132                 struct gatt_client_info_t *conn_info = NULL;
1133
1134                 memset(&ev, 0, sizeof(ev));
1135
1136                 DBG("WriteValue");
1137                 DBG("Application path = %s", object_path);
1138                 DBG("Sender = %s", sender);
1139
1140                 g_variant_get(parameters, "(&suqb@ay)",
1141                                 &addr, &req_id, &offset, &response_needed, &var);
1142                 DBG("Request id = %u, Offset = %u", req_id, offset);
1143
1144                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1145
1146                 /* Check if device is already in connected list */
1147                 conn_info = __bt_find_remote_gatt_client_info(addr);
1148
1149                 if (svc_info == NULL || conn_info == NULL || event_cb == NULL) {
1150                         g_variant_unref(var);
1151                         if (response_needed)
1152                                 g_dbus_method_invocation_return_value(invocation, NULL);
1153                         else
1154                                 g_object_unref(invocation);
1155                         return;
1156                 }
1157
1158                 len = g_variant_get_size(var);
1159                 if (len > 0 && len < 600) {
1160                         char *data;
1161                         data = (char *)g_variant_get_data(var);
1162                         memcpy(ev.value, data, len);
1163                         ev.length = len;
1164                 }
1165
1166                 if (response_needed) {
1167                         /* Store requets information */
1168                         req_info = g_new0(struct gatt_req_info, 1);
1169                         req_info->attr_path = g_strdup(object_path);
1170                         req_info->svc_path = g_strdup(svc_info->serv_path);
1171                         req_info->request_id = req_id;
1172                         req_info->request_type = BT_HAL_GATT_REQUEST_TYPE_WRITE;
1173                         req_info->offset = offset;
1174                         req_info->context = invocation;
1175
1176                         /* Append request info in list of requests for the particular connection */
1177                         conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
1178
1179                 } else {
1180                         g_object_unref(invocation);
1181                 }
1182
1183                 /* Send HAL event */
1184                 ev.conn_id = conn_info->connection_id;
1185                 ev.trans_id = req_id;
1186                 ev.att_handle = char_hdl;
1187                 ev.offset = offset;
1188                 ev.need_rsp = response_needed;
1189                 ev.is_prep = 0;
1190
1191                 /* Convert address to hex */
1192                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
1193
1194                 event_cb(HAL_EV_GATT_WRITE_REQUESTED, (void *)&ev, sizeof(ev));
1195
1196                 g_variant_unref(var);
1197                 return;
1198
1199         } else if (g_strcmp0(method_name, "StartNotify") == 0) {
1200                 DBG("StartNotify");
1201 #ifdef TIZEN_BT_HAL
1202                 struct gatt_service_info *svc_info = NULL;
1203                 struct hal_ev_gatt_server_notifcation_change ev;
1204                 int char_hdl = -1;
1205
1206                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1207                 if (svc_info == NULL || event_cb == NULL)
1208                         return;
1209
1210                 /* Send HAL event */
1211                 memset(&ev, 0, sizeof(ev));
1212                 ev.conn_id = -1;  /*TODO Bluez does not provide remote GATT client address, so no conn_id */
1213                 ev.trans_id = -1; /*TODO Bluez does not provide request id or transacion ID */
1214                 ev.att_handle = char_hdl;
1215                 ev.notify = true;
1216
1217                 /* Convert address to hex */
1218                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, "00:00:00:00:00"); /* TODO Bluez Does not provide address of GATT client */
1219
1220                 event_cb(HAL_EV_GATT_NOTIFICATION_CHANGE, (void *)&ev, sizeof(ev));
1221 #endif
1222
1223         } else if (g_strcmp0(method_name, "StopNotify") == 0) {
1224                 DBG("StopNotify");
1225 #ifdef TIZEN_BT_HAL
1226                 struct gatt_service_info *svc_info = NULL;
1227                 struct hal_ev_gatt_server_notifcation_change ev;
1228                 int char_hdl = -1;
1229
1230                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1231                 if (svc_info == NULL || event_cb == NULL)
1232                         return;
1233
1234                 /* Send HAL event */
1235                 memset(&ev, 0, sizeof(ev));
1236                 ev.conn_id = -1;  /*TODO Bluez does not provide remote GATT client address, so no conn_id */
1237                 ev.trans_id = -1; /*TODO Bluez does not provide request id or transacion ID */
1238                 ev.att_handle = char_hdl;
1239                 ev.notify = false;
1240
1241                 /* Convert address to hex */
1242                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, "00:00:00:00:00"); /* TODO Bluez DOes not provide address of GATT client */
1243
1244                 event_cb(HAL_EV_GATT_NOTIFICATION_CHANGE, (void *)&ev, sizeof(ev));
1245 #endif
1246
1247         } else if (g_strcmp0(method_name, "IndicateConfirm") == 0) {
1248                 gchar *addr = NULL;
1249                 gboolean complete = FALSE;
1250                 int char_hdl = -1;
1251
1252                 struct gatt_service_info *svc_info = NULL;
1253                 struct gatt_client_info_t *conn_info = NULL;
1254
1255                 struct hal_ev_gatt_server_indicate_cfm ev;
1256
1257                 DBG("IndicateConfirm");
1258                 DBG("Application path = %s", object_path);
1259                 DBG("Sender = %s", sender);
1260
1261                 g_variant_get(parameters, "(&sb)", &addr, &complete);
1262                 DBG("Remote Device address number = %s", addr);
1263                 DBG("Is Indicate confirmation for last device [%d]", complete);
1264
1265                 /* Check if device is already in connected list */
1266                 conn_info = __bt_find_remote_gatt_client_info(addr);
1267
1268                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1269
1270                 if (svc_info == NULL || conn_info == NULL
1271                         || event_cb == NULL) {
1272                         return;
1273                 }
1274
1275                 /* Send HAL event */
1276                 memset(&ev, 0, sizeof(ev));
1277                 ev.conn_id = conn_info->connection_id;
1278                 ev.trans_id = -1; /*TODO Bluez does not provide Transaction ID or request ID */
1279                 ev.att_handle = char_hdl;
1280
1281                 /* Convert address to hex */
1282                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
1283
1284                 event_cb(HAL_EV_GATT_INDICATE_CFM, (void *)&ev, sizeof(ev));
1285         } else if (g_strcmp0(method_name, "AcquireWrite") == 0) {
1286
1287                                 uint16_t mtu = 512;
1288                                 int char_hdl = -1;
1289                                 struct hal_ev_gatt_server_acquire_write_res  ev;
1290                                 struct gatt_service_info *svc_info = NULL;
1291                                 struct gatt_req_info *req_info = NULL;
1292                                 struct gatt_client_info_t *conn_info = NULL;
1293                                 char * dev_path = NULL;
1294                                 char * link = 0;
1295                                 char  addr[BT_HAL_ADDRESS_STRING_SIZE];
1296
1297                                 DBG("AcquireWrite");
1298                                 DBG("Application path = %s", object_path);
1299                                 DBG("Sender = %s", sender);
1300
1301                                 GVariantIter* iter;
1302                                 g_variant_get(parameters, "(a{sv})", &iter);
1303                                 char* key = NULL;
1304                                 GVariant* value = NULL;
1305                                 while (g_variant_iter_loop(iter, "{sv}", &key, &value)) {
1306                                                 if (g_strcmp0(key, "MTU") == 0)
1307                                                         g_variant_get(value, "i", &mtu);
1308                                                 else if (g_strcmp0(key, "link") == 0)
1309                                                         g_variant_get(value, "s", &link);
1310                                                 else if (g_strcmp0(key, "device") == 0)
1311                                                         g_variant_get(value, "o", &dev_path);
1312                                 }
1313
1314                                 DBG("AcquireWrite   values retived");
1315                                 DBG(" path  %s LINK = %s, MTU = %u", addr, link, mtu);
1316
1317                                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1318
1319                                 _bt_hal_convert_device_path_to_address(dev_path, addr);
1320
1321                                 DBG("remote address %s", addr);
1322
1323                                 /* Check if device is already in connected list */
1324                                 conn_info = __bt_find_remote_gatt_client_info(addr);
1325
1326                                 if (conn_info == NULL) {
1327                                         ERR("Cleint info not found\n");
1328                                         goto done;
1329                                 }
1330
1331                                 if (svc_info == NULL) {
1332                                         ERR("svc_info  info not found\n");
1333                                         goto done;
1334                                 }
1335
1336                                 /* Store requets information */
1337                                 req_info = g_new0(struct gatt_req_info, 1);
1338                                 req_info->attr_path = g_strdup(object_path);
1339                                 req_info->svc_path = g_strdup(svc_info->serv_path);
1340                                 req_info->request_id = conn_info->connection_id;
1341                                 req_info->request_type = BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_WRITE;
1342                                 req_info->offset = mtu;
1343                                 req_info->context = invocation;
1344
1345                                 /* Append request info in list of requests for the particular connection */
1346                                 conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
1347
1348                                 /* Send HAL event */
1349                                 memset(&ev, 0, sizeof(ev));
1350                                 ev.conn_id = conn_info->connection_id;
1351                                 ev.char_handl = char_hdl;
1352                                 ev.mtu = mtu;
1353                                 ev.trans_id = conn_info->connection_id;
1354                                 _bt_hal_convert_addr_string_to_type(ev.bdaddr, addr);
1355                                 event_cb(HAL_EV_GATT_SERVER_ACQUIRE_WRITE_RES, (void *)&ev, sizeof(ev));
1356
1357                                 DBG("HAL_EV_GATT_ACQUIRE_WRITE_RES   called");
1358
1359
1360                         return;
1361                 } else if (g_strcmp0(method_name, "AcquireNotify") == 0) {
1362
1363                                 uint16_t mtu = 512;
1364                                 int char_hdl = -1;
1365                                 struct hal_ev_gatt_server_acquire_notify  ev;
1366                                 struct gatt_service_info *svc_info = NULL;
1367                                 struct gatt_client_info_t *conn_info = NULL;
1368                                 struct gatt_req_info *req_info = NULL;
1369
1370                                 DBG("AcquireNotify");
1371                                 DBG("Application path = %s", object_path);
1372                                 DBG("Sender = %s", sender);
1373
1374                                 GVariantIter* iter;
1375                                 g_variant_get(parameters, "(a{sv})", &iter);
1376                                 char* key = NULL;
1377                                 GVariant* value = NULL;
1378                                 while (g_variant_iter_loop(iter, "{sv}", &key, &value)) {
1379                                                 if (g_strcmp0(key, "MTU") == 0)
1380                                                         g_variant_get(value, "q", &mtu);
1381                                 }
1382
1383                                 DBG("AcquireNotify  values retived");
1384                                 DBG(" MTU = %u",  mtu);
1385
1386                                 svc_info = __bt_gatt_find_gatt_service_from_char(object_path, &char_hdl);
1387
1388                         if (svc_info == NULL) {
1389                                         ERR("svc_info  info not found\n");
1390                                         goto done;
1391                                 }
1392
1393                                 /* Store requets information */
1394                                 req_info = g_new0(struct gatt_req_info, 1);
1395                                 req_info->attr_path = g_strdup(object_path);
1396                                 req_info->svc_path = g_strdup(svc_info->serv_path);
1397                                 req_info->request_id = 33;
1398                                 req_info->request_type = BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_NOTIFY;
1399                                 req_info->offset = mtu;
1400                                 req_info->context = invocation;
1401
1402                                 conn_info = g_new0(struct gatt_client_info_t, 1);
1403                                 conn_info->addr = g_strdup(object_path);
1404                                 INFO("Added GATT client path[%s]", conn_info->addr);
1405                                 conn_info->connection_id = 33;
1406                                 conn_info->instance_id = 33;
1407                                 /* Append request info in list of requests for the particular connection */
1408                                 conn_info->gatt_req_info_list = g_slist_append(conn_info->gatt_req_info_list, req_info);
1409                                 gatt_client_info_list = g_slist_append(gatt_client_info_list, conn_info);
1410
1411                                 /* Send HAL event */
1412                                 memset(&ev, 0, sizeof(ev));
1413                                 ev.conn_id = 33;
1414                                 ev.char_handl = char_hdl;
1415                                 ev.mtu = mtu;
1416                                 ev.trans_id = 33;
1417
1418                                 event_cb(HAL_EV_GATT_SERVER_ACQUIRE_NOTIFY_RES, (void *)&ev, sizeof(ev));
1419
1420                                 DBG("HAL_EV_GATT_ACQUIRE_NOTIFY_RES   called");
1421
1422                                 return;
1423         }
1424
1425 done:
1426         g_dbus_method_invocation_return_value(invocation, NULL);
1427 }
1428
1429 gboolean __bt_hal_gatt_emit_interface_removed(gchar *object_path, gchar *interface)
1430 {
1431         gboolean ret;
1432         GError *error = NULL;
1433         GVariantBuilder *array_builder;
1434
1435         array_builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
1436         g_variant_builder_init(array_builder, G_VARIANT_TYPE("as"));
1437         g_variant_builder_add(array_builder, "s", interface);
1438
1439         ret = g_dbus_connection_emit_signal(g_conn, NULL, "/",
1440                         "org.freedesktop.Dbus.Objectmanager",
1441                         "InterfacesRemoved",
1442                         g_variant_new("(oas)",
1443                                 object_path, array_builder),
1444                         &error);
1445
1446         if (!ret) {
1447                 if (error != NULL) {
1448                         /* dbus gives error cause */
1449                         ERR("d-bus api failure: errcode[%x], message[%s]",
1450                                         error->code, error->message);
1451                         g_clear_error(&error);
1452                 }
1453         }
1454         g_variant_builder_unref(array_builder);
1455
1456         return ret;
1457 }
1458
1459 static void __bt_hal_gatt_free_descriptor_info(struct gatt_desc_info *desc_info)
1460 {
1461         int i;
1462
1463         if (!desc_info)
1464                 return;
1465
1466         g_free(desc_info->desc_path);
1467         g_free(desc_info->desc_uuid);
1468         g_free(desc_info->desc_value);
1469
1470         for (i = 0; i < desc_info->flags_length; i++)
1471                 g_free(desc_info->desc_flags[i]);
1472
1473         g_free(desc_info);
1474 }
1475
1476 static void __bt_hal_gatt_free_characteristic_info(struct gatt_char_info *char_info)
1477 {
1478         int i;
1479
1480         if (!char_info)
1481                 return;
1482
1483         g_free(char_info->char_path);
1484         g_free(char_info->char_uuid);
1485         g_free(char_info->char_value);
1486
1487         for (i = 0; i < char_info->flags_length; i++)
1488                 g_free(char_info->char_flags[i]);
1489
1490         g_free(char_info);
1491 }
1492
1493
1494 static void __bt_hal_gatt_free_service_info(struct gatt_service_info *svc_info)
1495 {
1496         if (!svc_info)
1497                 return;
1498
1499         g_free(svc_info->serv_path);
1500         g_free(svc_info->service_uuid);
1501         g_free(svc_info);
1502 }
1503
1504 static const GDBusInterfaceVTable desc_interface_vtable = {
1505         __bt_gatt_desc_method_call,
1506         NULL,
1507         NULL,
1508 };
1509
1510 static const GDBusInterfaceVTable char_interface_vtable = {
1511         __bt_gatt_char_method_call,
1512         NULL,
1513         NULL,
1514 };
1515
1516 static const GDBusInterfaceVTable serv_interface_vtable = {
1517         NULL,
1518         NULL,
1519         NULL,
1520 };
1521
1522 static const GDBusInterfaceVTable manager_interface_vtable = {
1523         __bt_gatt_manager_method_call,
1524         NULL,
1525         NULL
1526 };
1527
1528
1529 static GDBusNodeInfo *__bt_gatt_create_method_node_info(
1530                 const gchar *introspection_data)
1531 {
1532         GError *err = NULL;
1533         GDBusNodeInfo *node_info = NULL;
1534
1535         if (introspection_data == NULL)
1536                 return NULL;
1537
1538
1539         DBG("Create new node info");
1540         node_info = g_dbus_node_info_new_for_xml(introspection_data, &err);
1541
1542         if (err) {
1543                 ERR("Unable to create node: %s", err->message);
1544                 g_clear_error(&err);
1545                 return NULL;
1546         }
1547
1548         return node_info;
1549 }
1550
1551 /* To send stack event to hal-av handler */
1552 void _bt_hal_register_gatt_server_handler_cb(handle_stack_msg cb)
1553 {
1554         event_cb = cb;
1555 }
1556
1557 void _bt_hal_unregister_gatt_server_handler_cb(void)
1558 {
1559         event_cb = NULL;
1560 }
1561
1562 static gboolean __bt_hal_gatt_desc_added_cb(gpointer user_data)
1563 {
1564         struct hal_ev_gatt_desc_added ev;
1565         hal_gatt_desc_added *data = (hal_gatt_desc_added*) user_data;
1566
1567         /* Prepare to GATT characteristic added event */
1568         memset(&ev, 0, sizeof(ev));
1569         ev.status = BT_STATUS_SUCCESS;
1570         ev.server_instance = data->instance_data;
1571         memcpy(ev.desc_uuid, data->uuid.uu, sizeof(data->uuid.uu));
1572         ev.service_handle = data->srvc_hdl;
1573         ev.desc_handle = data->desc_hdl;
1574
1575         if (!event_cb)
1576                 ERR("GATT Descriptor Added callback registered");
1577         else {
1578                 DBG("GATT Descriptor Added: server if [%d] Service handle [%d] Descriptor Handle [%d]",
1579                                 data->instance_data, data->srvc_hdl, data->desc_hdl);
1580
1581                 event_cb(HAL_EV_GATT_DESC_ADDED, (void *)&ev, sizeof(ev));
1582         }
1583
1584         g_free(data);
1585         return FALSE;
1586 }
1587
1588 static gboolean __bt_hal_gatt_char_added_cb(gpointer user_data)
1589 {
1590         struct hal_ev_gatt_char_added ev;
1591         hal_gatt_char_added *data = (hal_gatt_char_added*) user_data;
1592
1593         /* Prepare to GATT characteristic added event */
1594         memset(&ev, 0, sizeof(ev));
1595         ev.status = BT_STATUS_SUCCESS;
1596         ev.server_instance = data->instance_data;
1597         memcpy(ev.char_uuid, data->uuid.uu, sizeof(data->uuid.uu));
1598         ev.service_handle = data->srvc_hdl;
1599         ev.char_handle = data->char_hdl;
1600
1601         if (!event_cb)
1602                 ERR("GATT Characteristic Added callback registered");
1603         else {
1604                 DBG("GATT Characteristic Added: server if [%d] Service handle [%d] Characteristic handle [%d]",
1605                                 data->instance_data, data->srvc_hdl, data->char_hdl);
1606
1607                 event_cb(HAL_EV_GATT_CHAR_ADDED, (void *)&ev, sizeof(ev));
1608         }
1609
1610         g_free(data);
1611         return FALSE;
1612 }
1613
1614 static gboolean __bt_hal_gatt_service_added_cb(gpointer user_data)
1615 {
1616         struct hal_ev_gatt_service_added ev;
1617         hal_gatt_service_added *data = (hal_gatt_service_added*) user_data;
1618
1619         /* Prepare to GATT Service added event */
1620         memset(&ev, 0, sizeof(ev));
1621         ev.status = BT_STATUS_SUCCESS;
1622         ev.server_instance = data->instance_data;
1623         memcpy(ev.svc_uuid, data->uuid.uu, sizeof(data->uuid.uu));
1624         ev.service_handle = data->srvc_hdl;
1625         ev.is_primary = data->is_primary;
1626
1627         if (!event_cb)
1628                 ERR("GATT Service Added callback registered");
1629         else {
1630                 DBG("GATT Service Added: server if [%d] Service handle [%d]",
1631                                 data->instance_data,  data->srvc_hdl);
1632                 event_cb(HAL_EV_GATT_SERVICE_ADDED, (void *)&ev, sizeof(ev));
1633         }
1634
1635         g_free(data);
1636         return FALSE;
1637 }
1638
1639 static gboolean __bt_hal_gatt_service_started_cb(gpointer user_data)
1640 {
1641         struct hal_ev_gatt_service_started ev;
1642         hal_gatt_service_started *data = (hal_gatt_service_started*) user_data;
1643
1644         /* Prepare to GATT Service added event */
1645         memset(&ev, 0, sizeof(ev));
1646         ev.status = BT_STATUS_SUCCESS;
1647         ev.server_instance = data->instance_data;
1648         ev.service_handle = data->srvc_hdl;
1649
1650         if (!event_cb)
1651                 ERR("GATT Service Started callback registered");
1652         else {
1653                 DBG("GATT Service Started: server if [%d] Service handle [%d]",
1654                                 data->instance_data,  data->srvc_hdl);
1655                 event_cb(HAL_EV_GATT_SERVICE_STARTED, (void *)&ev, sizeof(ev));
1656         }
1657
1658         g_free(data);
1659         return FALSE;
1660 }
1661
1662 static gboolean __bt_hal_gatt_service_deleted_cb(gpointer user_data)
1663 {
1664         struct hal_ev_gatt_service_deleted ev;
1665         hal_gatt_service_deleted *data = (hal_gatt_service_deleted*) user_data;
1666
1667         /* Prepare to GATT Service added event */
1668         memset(&ev, 0, sizeof(ev));
1669         ev.status = BT_STATUS_SUCCESS;
1670         ev.server_instance = data->instance_data;
1671         ev.service_handle = data->srvc_hdl;
1672
1673         if (!event_cb)
1674                 ERR("GATT Service Deleted callback registered");
1675         else {
1676                 DBG("GATT Service Deleted: server if [%d] Service handle [%d]",
1677                                 data->instance_data,  data->srvc_hdl);
1678                 event_cb(HAL_EV_GATT_SERVICE_DELETED, (void *)&ev, sizeof(ev));
1679         }
1680
1681         g_free(data);
1682         return FALSE;
1683 }
1684
1685 static gboolean __bt_hal_register_slot_id_cb(gpointer user_data)
1686 {
1687         struct hal_ev_server_instance_registered ev;
1688         hal_register_server_data *data = (hal_register_server_data*) user_data;
1689
1690         /* Prepare to send AV connecting event */
1691         memset(&ev, 0, sizeof(ev));
1692         ev.status = BT_STATUS_SUCCESS;
1693         ev.server_instance = data->instance_data;
1694         memcpy(ev.app_uuid, data->uuid.uu, sizeof(ev.app_uuid));
1695
1696         if (!event_cb)
1697                 ERR("GATT Register Server Instance Callback not registered");
1698         else {
1699                 DBG("Server Instance is registered!! server if [%d]", data->instance_data);
1700                 event_cb(HAL_EV_SERVER_INSTANCE_INITIALIZED, (void *)&ev, sizeof(ev));
1701         }
1702
1703         g_free(data);
1704         return FALSE;
1705 }
1706
1707 static bt_status_t gatt_server_register_app(bt_uuid_t *uuid)
1708 {
1709         CHECK_BTGATT_INIT();
1710         int status = BT_STATUS_FAIL;
1711         int server_if;
1712         DBG("Register server instance request");
1713         hal_register_server_data *user_data = g_malloc0(sizeof(hal_register_server_data));
1714
1715         /* Check if slot available */
1716         server_if = _bt_hal_get_available_adv_slot_id(uuid);
1717
1718         if (server_if == -1) {
1719                 ERR("Allocation of server instance failed");
1720                 g_free(user_data);
1721                 return status;
1722         } else {
1723                 user_data->instance_data = server_if;
1724                 DBG("Allocated new Advertising slot with Stack [%d]", user_data->instance_data);
1725         }
1726
1727         /*
1728          * As we need to provide async callback to user from HAL, simply schedule a
1729          * callback method which will carry actual result
1730          */
1731         memcpy(user_data->uuid.uu, uuid->uu, sizeof(bt_uuid_t));
1732         g_idle_add(__bt_hal_register_slot_id_cb, (gpointer)user_data);
1733
1734         /* If available, then return success, else return error */
1735         return BT_STATUS_SUCCESS;
1736 }
1737
1738 void _bt_hal_remove_gatt_server_from_list(int server_if)
1739 {
1740         GSList *l;
1741         struct gatt_server_app *info = NULL;
1742
1743         for (l = gatt_server_apps; l != NULL;) {
1744                 info = (struct gatt_server_app*)l->data;
1745                 l = g_slist_next(l);
1746                 if (info == NULL)
1747                         continue;
1748                 if (info->slot == server_if) {
1749                         INFO("Found Matching GATT Server in List path[%s] slot [%d]",
1750                                 info->app_path, info->slot);
1751
1752                         /* Only if all services are deleted from the GATT Server, then only Unregister it.
1753                         Reason: it is possible, GATT Server app oly wants to disable multi advertising
1754                         In above case, only advertising block will be deallocated, Gatt Server will remain
1755                         unaffected */
1756                         if (info->services == NULL) {
1757                                 gatt_server_apps = g_slist_remove(gatt_server_apps, (gpointer)info);
1758                                 INFO("Total gatt server apps still existing after removing above is [%d]",
1759                                                 g_slist_length(gatt_server_apps));
1760
1761                                 /* DBUS Unregister only for current app */
1762                                 __bt_hal_gatt_deinit(info->app_path);
1763
1764                                 g_free(info->app_path);
1765                                 g_free(info);
1766                                 return;
1767                         } else {
1768                                 INFO("GATT Server still has services count[%d] in it..Can not remove it!!!",
1769                                         g_slist_length(info->services));
1770                         }
1771                 }
1772         }
1773 }
1774
1775 static bt_status_t gatt_server_unregister_app(int server_if)
1776 {
1777         CHECK_BTGATT_INIT();
1778         DBG("Un-Register server instance request [%d]", server_if);
1779
1780         if (_bt_hal_is_advertising_in_slot(server_if) == FALSE)
1781                 _bt_hal_free_server_slot(server_if);
1782
1783         /* If server_if belongs to a GATT Server, then delete the GATT server from List */
1784         _bt_hal_remove_gatt_server_from_list(server_if);
1785         return BT_STATUS_SUCCESS;
1786 }
1787
1788 static bt_status_t gatt_server_open(int server_if, const bt_bdaddr_t *bd_addr, bool is_direct)
1789 {
1790         CHECK_BTGATT_INIT();
1791         return BT_STATUS_SUCCESS;
1792 }
1793
1794 static bt_status_t gatt_server_close(int server_if, const bt_bdaddr_t *bd_addr, int conn_id)
1795 {
1796         CHECK_BTGATT_INIT();
1797         return BT_STATUS_SUCCESS;
1798 }
1799
1800 static void __bt_gatt_close_gdbus_connection(void)
1801 {
1802         GError *err = NULL;
1803         DBG("+");
1804
1805         if (g_conn == NULL)
1806                 return;
1807
1808         if (!g_dbus_connection_flush_sync(g_conn, NULL, &err)) {
1809                 ERR("Fail to flush the connection: %s", err->message);
1810                 g_error_free(err);
1811                 err = NULL;
1812         }
1813
1814         if (!g_dbus_connection_close_sync(g_conn, NULL, &err)) {
1815                 if (err) {
1816                         ERR("Fail to close the dbus connection: %s", err->message);
1817                         g_error_free(err);
1818                 }
1819         }
1820
1821         g_object_unref(g_conn);
1822         g_conn = NULL;
1823         DBG("-");
1824 }
1825
1826 static GDBusConnection *__bt_gatt_get_gdbus_connection(void)
1827 {
1828         GDBusConnection *local_system_gconn = NULL;
1829         char *address;
1830         GError *err = NULL;
1831
1832         if (g_conn == NULL) {
1833                 address = g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
1834                 if (address == NULL) {
1835                         if (err) {
1836                                 ERR("Failed to get bus address: %s", err->message);
1837                                 g_clear_error(&err);
1838                         }
1839                         return NULL;
1840                 }
1841
1842                 g_conn = g_dbus_connection_new_for_address_sync(address,
1843                                 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
1844                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
1845                                 NULL, /* GDBusAuthObserver */
1846                                 NULL,
1847                                 &err);
1848                 if (!g_conn) {
1849                         if (err) {
1850                                 ERR("Unable to connect to dbus: %s", err->message);
1851                                 g_clear_error(&err);
1852                         }
1853                         return NULL;
1854                 }
1855         } else if (g_dbus_connection_is_closed(g_conn)) {
1856                 address = g_dbus_address_get_for_bus_sync(G_BUS_TYPE_SYSTEM, NULL, &err);
1857                 if (address == NULL) {
1858                         if (err) {
1859                                 ERR("Failed to get bus address: %s", err->message);
1860                                 g_clear_error(&err);
1861                         }
1862                         return NULL;
1863                 }
1864
1865                 local_system_gconn = g_dbus_connection_new_for_address_sync(address,
1866                                 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
1867                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
1868                                 NULL, /* GDBusAuthObserver */
1869                                 NULL,
1870                                 &err);
1871
1872                 if (!local_system_gconn) {
1873                         ERR("Unable to connect to dbus: %s", err->message);
1874                         g_clear_error(&err);
1875                 }
1876
1877                 g_conn = local_system_gconn;
1878         }
1879
1880         return g_conn;
1881 }
1882
1883 static char* __bt_hal_convert_uuid_to_string(bt_uuid_t *srvc_id)
1884 {
1885         char uuid_buf[5];
1886         const char *uuid;
1887
1888         uuid = btuuid2str(srvc_id->uu);
1889         DBG("Original UUID [%s]", uuid);
1890
1891         if (_bt_hal_uuid_is_standard(srvc_id) == TRUE) {
1892                 /* Extract Standard UUID string */
1893                 memcpy(uuid_buf, &uuid[4], 4);
1894                 uuid_buf[4] = '\0';
1895                 DBG("Converted string [%s]", uuid_buf);
1896                 return g_strdup(uuid_buf);
1897         } else
1898                 return strdup(uuid);
1899 }
1900
1901 int __bt_hal_add_service_to_dbus(char *app_path, int slot, btgatt_srvc_id_t *srvc_id)
1902 {
1903         gboolean ret;
1904         /* For GATT service specific */
1905         GDBusNodeInfo *node_info;
1906         guint object_id;
1907         gchar *path = NULL;
1908         struct gatt_service_info *serv_info = NULL;
1909         GVariantBuilder *builder = NULL;
1910         GVariantBuilder *builder1 = NULL;
1911         GVariantBuilder *inner_builder = NULL;
1912         gboolean svc_primary = TRUE;
1913         GError *error = NULL;
1914         hal_gatt_service_added *user_data = NULL;
1915         DBG("Service add to DBUS slot [%d]", slot);
1916
1917         node_info = __bt_gatt_create_method_node_info(
1918                         service_introspection_xml);
1919
1920         if (node_info == NULL)
1921                 return BT_STATUS_FAIL;
1922
1923         DBG("Add new GATT Service: Current GATT Service handle [%d]", gatt_service_handle);
1924         path = g_strdup_printf("%s"GATT_SERV_OBJECT_PATH"%d", app_path, ++gatt_service_handle);
1925         DBG("gatt service path is [%s]", path);
1926
1927         object_id = g_dbus_connection_register_object(g_conn, path,
1928                         node_info->interfaces[0],
1929                         &serv_interface_vtable,
1930                         NULL, NULL, &error);
1931
1932         if (object_id == 0) {
1933                 ERR("failed to register: %s", error->message);
1934                 g_error_free(error);
1935                 g_free(path);
1936                 return BT_STATUS_FAIL;
1937         }
1938         /* Add object_id/gatt service information; it's required at the time of
1939          *  service unregister and Getmanagedobjects
1940          */
1941         serv_info = g_new0(struct gatt_service_info, 1);
1942
1943         serv_info->serv_path = g_strdup(path);
1944         serv_info->serv_id = object_id;
1945         serv_info->service_uuid = __bt_hal_convert_uuid_to_string(&srvc_id->id.uuid);//g_strdup(btuuid2str(srvc_id->id.uuid.uu));
1946         serv_info->is_svc_registered = FALSE;
1947         serv_info->is_svc_primary = svc_primary;
1948         DBG("Service Handle to be added is [%d]", gatt_service_handle);
1949         serv_info->service_handle = gatt_service_handle;
1950
1951         /* Update service in GATT Server service List */
1952         gatt_services = g_slist_append(gatt_services, serv_info);
1953
1954         /* emit interfacesadded signal here for service path */
1955         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sa{sv}}"));
1956         inner_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
1957
1958         g_variant_builder_add(inner_builder, "{sv}",
1959                         "UUID", g_variant_new_string(btuuid2str(srvc_id->id.uuid.uu)));
1960
1961         g_variant_builder_add(inner_builder, "{sv}",
1962                         "Primary", g_variant_new_boolean(svc_primary));
1963
1964         builder1 = g_variant_builder_new(G_VARIANT_TYPE("ao"));
1965
1966         g_variant_builder_add(inner_builder, "{sv}", "Characteristics",
1967                         g_variant_new("ao", builder1));
1968
1969         g_variant_builder_add(builder, "{sa{sv}}",
1970                         GATT_SERV_INTERFACE, inner_builder);
1971
1972         ret = g_dbus_connection_emit_signal(g_conn, NULL, "/",
1973                         "org.freedesktop.Dbus.ObjectManager",
1974                         "InterfacesAdded",
1975                         g_variant_new("(oa{sa{sv}})",
1976                                 path, builder),
1977                         &error);
1978         if (!ret) {
1979                 if (error) {
1980                         /* dbus gives error cause */
1981                         ERR("d-bus api failure: errcode[%x], message[%s]",
1982                                         error->code, error->message);
1983                         g_clear_error(&error);
1984                 }
1985         }
1986
1987         /* Send Service handle to application */
1988         user_data = g_malloc0(sizeof(hal_gatt_service_added));
1989         user_data->srvc_hdl = serv_info->service_handle;
1990         user_data->instance_data = slot;
1991         memcpy(user_data->uuid.uu, srvc_id->id.uuid.uu, sizeof(srvc_id->id.uuid.uu));
1992         g_idle_add(__bt_hal_gatt_service_added_cb, (gpointer)user_data);
1993
1994         /* Save newly created service in GATT Server's service list */
1995         _bt_hal_update_gatt_service_in_gatt_server(slot, serv_info);
1996
1997         /* Free data */
1998         g_free(path);
1999         g_variant_builder_unref(inner_builder);
2000         g_variant_builder_unref(builder);
2001         g_variant_builder_unref(builder1);
2002         return BT_STATUS_SUCCESS;
2003 }
2004
2005 static void __bt_hal_unregister_application_cb(GObject *object, GAsyncResult *res,
2006                 gpointer user_data)
2007 {
2008         char *app_path = (char*)user_data;
2009         INFO("UnregisterApplication is completed app [%s]", app_path);
2010         GError *error = NULL;
2011         GVariant *result = NULL;
2012
2013         if (manager_gproxy)
2014         result = g_dbus_proxy_call_finish(manager_gproxy, res, &error);
2015
2016         if (result == NULL) {
2017                 /* dBUS-RPC is failed */
2018                 ERR("Dbus-RPC is failed\n");
2019
2020                 if (error != NULL) {
2021                         /* dBUS gives error cause */
2022                         ERR("D-Bus API failure: errCode[%x], message[%s]\n",
2023                                         error->code, error->message);
2024                         g_clear_error(&error);
2025                 }
2026         } else {
2027                 g_variant_unref(result);
2028         }
2029         g_free(app_path);
2030 }
2031
2032 static void __bt_hal_gatt_deinit(char *app_path)
2033 {
2034         GDBusProxy *proxy = NULL;
2035         char *data;
2036         INFO("+");
2037
2038         /* Step1: Remove requested App */
2039         proxy = __bt_gatt_gdbus_get_gatt_manager_proxy("org.bluez",
2040                         "/org/bluez/hci0", "org.bluez.GattManager1");
2041
2042         if (proxy == NULL)
2043                 return;
2044
2045         INFO("UnregisterApplication : path [%s]", app_path);
2046
2047         /* Async Call to Unregister Service */
2048         data = g_strdup(app_path);
2049         g_dbus_proxy_call(proxy,
2050                         "UnregisterApplication",
2051                         g_variant_new("(o)",
2052                                 app_path),
2053                         G_DBUS_CALL_FLAGS_NONE, -1,
2054                         NULL,
2055                         (GAsyncReadyCallback)__bt_hal_unregister_application_cb,
2056                         (gpointer)data);
2057
2058         /* If requested app is last GATT Server app, then clean all resources */
2059         if (gatt_server_apps == NULL) {
2060                 INFO("All GATT servers are removed, clean all DBUS resources");
2061                 if (owner_id) {
2062                         /* unregister the exported interface for object manager
2063                            g_conn and manager_id are common for all GATT servers */
2064                         g_dbus_connection_unregister_object(g_conn,
2065                                         manager_id);
2066                         manager_id = 0;
2067                         g_bus_unown_name(owner_id);
2068                         owner_id = 0;
2069
2070                         g_object_unref(manager_gproxy);
2071                         manager_gproxy = NULL;
2072
2073                         /* Close the GDBUS connection */
2074                         __bt_gatt_close_gdbus_connection();
2075                 }
2076         }
2077         INFO("-");
2078 }
2079
2080 int __bt_hal_gatt_init(void)
2081 {
2082         GDBusConnection *conn = NULL;
2083         DBG("+");
2084         /* Only once for ALL GATT Servers */
2085         if (owner_id == 0) {
2086                 owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
2087                                 BT_GATT_SERVICE_NAME,
2088                                 G_BUS_NAME_OWNER_FLAGS_NONE,
2089                                 NULL, NULL, NULL, NULL, NULL);
2090         }
2091         INFO("Owner ID [%d]", owner_id);
2092
2093         /* Only once for ALL GATT Servers conn = g_conn(global)*/
2094         conn = __bt_gatt_get_gdbus_connection();
2095         if (!conn) {
2096                 ERR("Unable to get connection");
2097                 return BT_STATUS_FAIL;
2098         }
2099
2100         /* Only once for ALL GATT Servers */
2101         if (manager_node_info == NULL) {
2102                 /* Register ObjectManager interface */
2103                 manager_node_info = __bt_gatt_create_method_node_info(
2104                                 manager_introspection_xml);
2105
2106                 if (manager_node_info == NULL) {
2107                         ERR("failed to get node info");
2108                         return BT_STATUS_FAIL;
2109                 }
2110         }
2111
2112         INFO("-");
2113         return BT_STATUS_SUCCESS;
2114 }
2115
2116 void _bt_hal_is_gatt_server_initialzed(int slot, char **app_path)
2117 {
2118         GSList *l;
2119
2120         for (l = gatt_server_apps; l; l = g_slist_next(l)) {
2121                 struct gatt_server_app *app = (struct gatt_server_app *)l->data;
2122                 if (app->slot == slot) {
2123                         INFO("GATT Server app found app path [%s] instance [%d]",
2124                                         app->app_path, app->slot);
2125                         *app_path = app->app_path;
2126                         return;
2127                 }
2128         }
2129         /* GATT Server not found */
2130         *app_path = NULL;
2131 }
2132
2133 void _bt_hal_update_gatt_server_path(int slot, char *app_path)
2134 {
2135         if (app_path == NULL)
2136                 return;
2137
2138         struct gatt_server_app *app = g_malloc0(sizeof(struct gatt_server_app));
2139         app->app_path = g_strdup(app_path);
2140         app->slot = slot;
2141         gatt_server_apps = g_slist_append(gatt_server_apps, app);
2142         INFO("GATT Server: Path [%s] Slot [%d]-> Updated", app_path, slot);
2143
2144 }
2145
2146
2147 static bt_status_t gatt_server_add_service(int server_if, btgatt_srvc_id_t *srvc_id,
2148                 int num_handles)
2149 {
2150         CHECK_BTGATT_INIT();
2151         char *app_path = NULL;
2152         GError *error = NULL;
2153         int *app_id = NULL;
2154         guint manager_id;
2155
2156         int result = BT_STATUS_SUCCESS;
2157
2158         DBG("GATT Server Add service request: Instance ID[%d] Is Primary [%d] UUID [%s]",
2159                         server_if, srvc_id->is_primary, btuuid2str(srvc_id->id.uuid.uu));
2160
2161         /* Check if this GATT server Application is already registered with DBUS */
2162         _bt_hal_is_gatt_server_initialzed(server_if, &app_path);
2163
2164         if (app_path != NULL) {
2165                 DBG("GATT server path is already defined [%s]", app_path);
2166                 return __bt_hal_add_service_to_dbus(app_path, server_if, srvc_id);
2167         } else {
2168                 DBG("GATT server application path for instance [%d] is not defined yet", server_if);
2169                 result = __bt_hal_gatt_init();
2170                 if (result != BT_STATUS_SUCCESS)
2171                         return result;
2172
2173                 /* Only once for each GATT Server */
2174                 app_path = g_strdup_printf("/com/%d", server_if);
2175
2176                 app_id = g_malloc0(sizeof(int));
2177                 *app_id = server_if;
2178
2179                 manager_id = g_dbus_connection_register_object(g_conn, app_path,
2180                                 manager_node_info->interfaces[0],
2181                                 &manager_interface_vtable,
2182                                 (gpointer)app_id, NULL, &error);
2183
2184                 if (manager_id == 0) {
2185                         ERR("failed to register: %s", error->message);
2186                         g_error_free(error);
2187                         goto failed;
2188                 }
2189
2190                 /* For current GATT Server, app_path is created, save it in Table */
2191                 _bt_hal_update_gatt_server_path(server_if, app_path);
2192
2193                 /* Add GATT Service to DBUS */
2194                 if (__bt_hal_add_service_to_dbus(app_path, server_if, srvc_id) != BT_STATUS_SUCCESS)
2195                         goto failed;
2196
2197                 g_free(app_path);
2198         }
2199
2200         INFO("Successfully added service");
2201         return BT_STATUS_SUCCESS;
2202 failed:
2203
2204         g_free(app_id);
2205
2206         if (app_path)
2207                 g_free(app_path);
2208         INFO("Service addition failed!!");
2209         return BT_STATUS_FAIL;
2210 }
2211
2212 static bt_status_t gatt_server_add_included_service(int server_if, int service_handle,
2213                 int included_handle)
2214 {
2215         CHECK_BTGATT_INIT();
2216         return BT_STATUS_SUCCESS;
2217 }
2218
2219
2220 static gboolean __bt_is_service_last_in_server_list(int instance, int service_handle)
2221 {
2222         GSList *l;
2223         GSList *gatt_services = NULL;
2224         int len;
2225         struct gatt_service_info *info = NULL;
2226
2227         gatt_services =  _bt_get_service_list_from_server(instance);
2228
2229         len = g_slist_length(gatt_services);
2230         l = g_slist_nth(gatt_services, len -1);
2231         if (NULL == l)
2232                 return FALSE;
2233
2234         info = l->data;
2235
2236         if (info->service_handle == service_handle)
2237                 return TRUE;
2238         return FALSE;
2239 }
2240
2241 static struct gatt_service_info *__bt_gatt_find_gatt_service_info(int instance,
2242                 int service_handle)
2243 {
2244         GSList *l;
2245         GSList *gatt_services = NULL;
2246         INFO("Find Service: svc handle [%d] from GATT Server slot[%d]", service_handle, instance);
2247
2248         gatt_services = _bt_get_service_list_from_server(instance);
2249
2250         for (l = gatt_services; l != NULL; l = g_slist_next(l)) {
2251                 struct gatt_service_info *info = l->data;
2252                 INFO("Got one service with handle [%d]", info->service_handle);
2253                 if (info->service_handle == service_handle)
2254                         return info;
2255         }
2256         ERR("Gatt service with handle [%d] not found", service_handle);
2257         return NULL;
2258 }
2259
2260 static bt_status_t gatt_server_add_characteristic(int slot, int service_handle,
2261                 bt_uuid_t *uuid, int properties,
2262                 int permissions)
2263 {
2264         gboolean ret;
2265         GError *error = NULL;
2266         guint object_id;
2267         GDBusNodeInfo *node_info;
2268         gchar *path = NULL;
2269         GVariantBuilder *builder = NULL;
2270         GVariantBuilder *inner_builder = NULL;
2271         struct gatt_service_info *serv_info = NULL;
2272         struct gatt_char_info *char_info = NULL;
2273         GVariantBuilder *builder2 = NULL;
2274         GVariantBuilder *builder3 = NULL;
2275         GVariant *flags_val = NULL;
2276         int i = 0;
2277         char *char_flags[NUMBER_OF_FLAGS];
2278         int flag_count = 0;
2279         hal_gatt_char_added *user_data = NULL;
2280         int *app_id;
2281
2282         CHECK_BTGATT_INIT();
2283         DBG("Add new characteristic to GATT Service handle [%d]", service_handle);
2284         DBG("Properties of new charateristic [%d] Permission [%d]", properties, permissions);
2285
2286         serv_info = __bt_gatt_find_gatt_service_info(slot, service_handle);
2287         if (serv_info == NULL)
2288                 return BT_STATUS_FAIL;
2289
2290         node_info = __bt_gatt_create_method_node_info(
2291                         characteristics_introspection_xml);
2292
2293         if (node_info == NULL)
2294                 return BT_STATUS_FAIL;
2295
2296         DBG("Add new GATT characteristic: Current GATT char handle [%d]", gatt_char_handle);
2297         path = g_strdup_printf("%s/characteristic%d", serv_info->serv_path, ++gatt_char_handle);
2298         DBG("gatt characteristic path is [%s]", path);
2299
2300         app_id = g_malloc0(sizeof(int));
2301         *app_id = slot;
2302
2303         object_id = g_dbus_connection_register_object(g_conn, path,
2304                         node_info->interfaces[0],
2305                         &char_interface_vtable,
2306                         (gpointer)app_id, NULL, &error);
2307
2308         if (object_id == 0) {
2309                 ERR("failed to register: %s", error->message);
2310                 g_error_free(error);
2311                 g_free(path);
2312                 g_free(app_id);
2313                 return BT_STATUS_FAIL;
2314         }
2315
2316         if (permissions & BT_HAL_GATT_PERMISSION_ENCRYPT_READ)
2317                 properties |= BT_HAL_GATT_CHARACTERISTIC_PROPERTY_ENCRYPT_READ;
2318         if (permissions & BT_HAL_GATT_PERMISSION_ENCRYPT_AUTHENTICATED_READ)
2319                 properties |= BT_HAL_GATT_CHARACTERISTIC_PROPERTY_ENCRYPT_AUTHENTICATED_READ;
2320         if (permissions & BT_HAL_GATT_PERMISSION_ENCRYPT_WRITE)
2321                 properties |= BT_HAL_GATT_CHARACTERISTIC_PROPERTY_ENCRYPT_WRITE;
2322         if (permissions & BT_HAL_GATT_PERMISSION_ENCRYPT_AUTHENTICATED_WRITE)
2323                 properties |= BT_HAL_GATT_CHARACTERISTIC_PROPERTY_ENCRYPT_AUTHENTICATED_WRITE;
2324
2325         flag_count = bt_hal_gatt_convert_prop2string(properties, char_flags);
2326
2327         char_info = g_new0(struct gatt_char_info, 1);
2328
2329         char_info->char_path = g_strdup(path);
2330         char_info->char_id = object_id;
2331         char_info->char_uuid = __bt_hal_convert_uuid_to_string(uuid);//g_strdup(btuuid2str(uuid->uu));
2332         for (i = 0; i < flag_count; i++)
2333                 char_info->char_flags[i] = char_flags[i];
2334
2335
2336         char_info->flags_length = flag_count;
2337         char_info->char_handle = gatt_char_handle;
2338
2339
2340         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sa{sv}}"));
2341         inner_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
2342
2343         g_variant_builder_add(inner_builder, "{sv}", "UUID",
2344                         g_variant_new("s", char_info->char_uuid));
2345         g_variant_builder_add(inner_builder, "{sv}", "Service",
2346                         g_variant_new("o", serv_info->serv_path));
2347
2348         builder2 = g_variant_builder_new(G_VARIANT_TYPE("as"));
2349
2350         for (i = 0; i < flag_count; i++)
2351                 g_variant_builder_add(builder2, "s", char_flags[i]);
2352
2353         flags_val = g_variant_new("as", builder2);
2354         g_variant_builder_add(inner_builder, "{sv}", "Flags",
2355                         flags_val);
2356
2357         builder3 = g_variant_builder_new(G_VARIANT_TYPE("ao"));
2358
2359         g_variant_builder_add(inner_builder, "{sv}", "Descriptors",
2360                         g_variant_new("ao", builder3));
2361
2362         g_variant_builder_add(builder, "{sa{sv}}",
2363                         GATT_CHAR_INTERFACE,
2364                         inner_builder);
2365
2366         ret = g_dbus_connection_emit_signal(g_conn, NULL, "/",
2367                         "org.freedesktop.Dbus.ObjectManager",
2368                         "InterfacesAdded",
2369                         g_variant_new("(oa{sa{sv}})",
2370                                 path, builder),
2371                         &error);
2372         if (!ret) {
2373                 if (error) {
2374                         /* dbus gives error cause */
2375                         ERR("d-bus api failure: errcode[%x], message[%s]",
2376                                         error->code, error->message);
2377                         g_clear_error(&error);
2378                 }
2379         }
2380
2381         //*char_path = g_strdup(path);
2382
2383         //new_char = TRUE;
2384
2385
2386         /* Send Service handle to application */
2387         user_data = g_malloc0(sizeof(hal_gatt_char_added));
2388         user_data->srvc_hdl = serv_info->service_handle;
2389         user_data->char_hdl = gatt_char_handle;
2390         user_data->instance_data = slot;
2391         memcpy(user_data->uuid.uu, uuid->uu, sizeof(uuid->uu));
2392         g_idle_add(__bt_hal_gatt_char_added_cb, (gpointer)user_data);
2393
2394         /* Save newly created charatcristic to GATT Server's service's characteristic  list */
2395         serv_info->char_data = g_slist_append(serv_info->char_data, char_info);
2396
2397         /* Free data */
2398         g_free(path);
2399
2400         g_variant_builder_unref(inner_builder);
2401         g_variant_builder_unref(builder);
2402         g_variant_builder_unref(builder2);
2403         g_variant_builder_unref(builder3);
2404
2405         return BT_STATUS_SUCCESS;
2406 }
2407
2408 static bt_status_t gatt_server_add_descriptor(int slot, int service_handle, bt_uuid_t *uuid,
2409                 int permissions)
2410 {
2411         CHECK_BTGATT_INIT();
2412
2413 //      static int desc_id = 1;
2414         GError *error = NULL;
2415         guint object_id;
2416         GDBusNodeInfo *node_info;
2417         gchar *path = NULL;
2418         GVariantBuilder *builder = NULL;
2419         GVariantBuilder *inner_builder = NULL;
2420
2421         struct gatt_char_info *char_info = NULL;
2422         struct gatt_desc_info *desc_info = NULL;
2423         struct gatt_service_info *serv_info = NULL;
2424
2425         gchar **line_argv = NULL;
2426         char *serv_path;
2427         char *char_path = NULL;
2428         GSList *l;
2429
2430         GVariantBuilder *builder2 = NULL;
2431         GVariant *flags_val = NULL;
2432         int i = 0;
2433         char *desc_flags[NUMBER_OF_FLAGS];
2434         int flag_count = 0;
2435         int *app_id;
2436
2437         hal_gatt_desc_added *user_data = NULL;
2438 #if 0
2439         if (new_char) {
2440                 desc_id = 1;
2441                 new_char = FALSE;
2442         }
2443 #endif
2444         /* Fetch service data for the GATT server */
2445         serv_info = __bt_gatt_find_gatt_service_info(slot, service_handle);
2446         if (serv_info == NULL)
2447                 return BT_STATUS_FAIL;
2448
2449         /* Fetch list of characteristics from the service info */
2450         l = serv_info->char_data;
2451
2452         /* Fetch last char info from the characteristic list */
2453         char_info = g_slist_last(l)->data;
2454         if (char_info == NULL)
2455                 return BT_STATUS_FAIL;
2456
2457         /* Fetch characteristic path from char info */
2458         char_path = char_info->char_path;
2459
2460         line_argv = g_strsplit_set(char_path, "/", 0);
2461         serv_path = g_strdup_printf("/%s/%s/%s", line_argv[1], line_argv[2], line_argv[3]);
2462
2463
2464         node_info = __bt_gatt_create_method_node_info(
2465                         descriptor_introspection_xml);
2466
2467         if (node_info == NULL) {
2468                 g_strfreev(line_argv);
2469                 g_free(serv_path);
2470                 return BT_STATUS_FAIL;
2471         }
2472
2473         DBG("Add new Descriptor: Current GATT desc handle [%d]", gatt_desc_handle);
2474
2475         path = g_strdup_printf("%s/descriptor%d", char_path, ++gatt_desc_handle);
2476         DBG("gatt descriptor path is [%s]", path);
2477
2478         app_id = g_malloc0(sizeof(int));
2479         *app_id = slot;
2480
2481         object_id = g_dbus_connection_register_object(g_conn, path,
2482                         node_info->interfaces[0],
2483                         &desc_interface_vtable,
2484                         (gpointer)app_id, NULL, &error);
2485
2486         if (object_id == 0) {
2487                 ERR("failed to register: %s", error->message);
2488                 g_error_free(error);
2489                 g_free(path);
2490                 g_strfreev(line_argv);
2491                 g_free(serv_path);
2492                 g_free(app_id);
2493                 return BT_STATUS_FAIL;
2494         }
2495
2496         flag_count = bt_hal_gatt_convert_perm2string(permissions, desc_flags);
2497
2498         desc_info = g_new0(struct gatt_desc_info, 1);
2499
2500         desc_info->desc_path = g_strdup(path);
2501         desc_info->desc_id = object_id;
2502         desc_info->desc_uuid = __bt_hal_convert_uuid_to_string(uuid);//g_strdup(btuuid2str(uuid->uu));
2503
2504         for (i = 0; i < flag_count; i++)
2505                 desc_info->desc_flags[i] = desc_flags[i];
2506
2507         desc_info->flags_length = flag_count;
2508         desc_info->desc_handle = gatt_desc_handle;
2509
2510
2511         builder = g_variant_builder_new(G_VARIANT_TYPE("a{sa{sv}}"));
2512         inner_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
2513
2514         g_variant_builder_add(inner_builder, "{sv}", "UUID",
2515                         g_variant_new("s", btuuid2str(uuid->uu)));
2516         g_variant_builder_add(inner_builder, "{sv}", "Characteristic",
2517                         g_variant_new("o", char_path));
2518
2519         builder2 = g_variant_builder_new(G_VARIANT_TYPE("as"));
2520
2521         for (i = 0; i < flag_count; i++)
2522                 g_variant_builder_add(builder2, "s", desc_flags[i]);
2523
2524         flags_val = g_variant_new("as", builder2);
2525         g_variant_builder_add(inner_builder, "{sv}", "Flags",
2526                         flags_val);
2527
2528         g_variant_builder_add(builder, "{sa{sv}}",
2529                         GATT_DESC_INTERFACE,
2530                         inner_builder);
2531
2532         g_dbus_connection_emit_signal(g_conn, NULL, "/",
2533                         "org.freedesktop.Dbus.ObjectManager",
2534                         "InterfacesAdded",
2535                         g_variant_new("(oa{sa{sv}})",
2536                                 path, builder),
2537                         &error);
2538         if (error != NULL) {
2539                 ERR("g_dbus_connection_emit_signal failed: errCode[%x], message[%s]",
2540                                 error->code, error->message);
2541                 g_clear_error(&error);
2542         }
2543
2544         //*desc_path = g_strdup(path);
2545
2546         /* Save newly created descriptor to GATT server's service's characteristic */
2547         char_info->desc_data = g_slist_append(char_info->desc_data, desc_info);
2548
2549         /* Send descriptor handle to application */
2550         user_data = g_malloc0(sizeof(hal_gatt_desc_added));
2551         user_data->srvc_hdl = serv_info->service_handle;
2552         user_data->desc_hdl = gatt_desc_handle;
2553         user_data->instance_data = slot;
2554         memcpy(user_data->uuid.uu, uuid->uu, sizeof(uuid->uu));
2555         g_idle_add(__bt_hal_gatt_desc_added_cb, (gpointer)user_data);
2556
2557         /* Free data */
2558         g_free(path);
2559         g_free(serv_path);
2560         g_strfreev(line_argv);
2561         g_variant_builder_unref(inner_builder);
2562         g_variant_builder_unref(builder);
2563         return BT_STATUS_SUCCESS;
2564 }
2565
2566 static void __bt_hal_register_application_cb(GObject *object, GAsyncResult *res, gpointer user_data)
2567 {
2568         GError *error = NULL;
2569         GVariant *result;
2570         char *data = (char*) user_data;
2571         INFO("RegisterApplication is completed path [%s]", data);
2572
2573         result = g_dbus_proxy_call_finish(manager_gproxy, res, &error);
2574
2575         if (result == NULL) {
2576                 /* dBUS-RPC is failed */
2577                 ERR("Dbus-RPC is failed\n");
2578
2579                 if (error != NULL) {
2580                         /* dBUS gives error cause */
2581                         ERR("D-Bus API failure: errCode[%x], message[%s]\n",
2582                                         error->code, error->message);
2583                         g_clear_error(&error);
2584                 }
2585         } else {
2586                 g_variant_unref(result);
2587         }
2588         g_free(data);
2589 }
2590
2591 static GDBusProxy *__bt_hal_gatt_gdbus_init_manager_proxy(const gchar *service,
2592                 const gchar *path, const gchar *interface)
2593 {
2594         GDBusProxy *proxy;
2595         GError *err = NULL;
2596
2597         if (g_conn == NULL)
2598                 g_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM,
2599                                 NULL, &err);
2600
2601         if (!g_conn) {
2602                 if (err) {
2603                         ERR("Unable to connect to gdbus: %s", err->message);
2604                         g_clear_error(&err);
2605                 }
2606                 return NULL;
2607         }
2608
2609         proxy =  g_dbus_proxy_new_sync(g_conn,
2610                         G_DBUS_PROXY_FLAGS_NONE, NULL,
2611                         service, path,
2612                         interface, NULL, &err);
2613
2614         if (!proxy) {
2615                 if (err) {
2616                         ERR("Unable to create proxy: %s", err->message);
2617                         g_clear_error(&err);
2618                 }
2619                 return NULL;
2620         }
2621         manager_gproxy = proxy;
2622
2623         return proxy;
2624 }
2625
2626 static GDBusProxy *__bt_gatt_gdbus_get_gatt_manager_proxy(const gchar *service,
2627                 const gchar *path, const gchar *interface)
2628 {
2629         return (manager_gproxy) ? manager_gproxy :
2630                 __bt_hal_gatt_gdbus_init_manager_proxy(service,
2631                                 path, interface);
2632 }
2633
2634 static void __bt_register_application_to_dbus(int slot)
2635 {
2636         GDBusProxy *proxy = NULL;
2637         char *app_path = NULL;
2638         char *data;
2639         DBG("RegisterApplication slot [%d]", slot);
2640
2641         /* It is impossible that app path is still not initialized */
2642         _bt_hal_is_gatt_server_initialzed(slot, &app_path);
2643
2644         proxy = __bt_gatt_gdbus_get_gatt_manager_proxy("org.bluez",
2645                         "/org/bluez/hci0", "org.bluez.GattManager1");
2646
2647         data = g_strdup(app_path);
2648         g_dbus_proxy_call(proxy,
2649                         "RegisterApplication",
2650                         g_variant_new("(oa{sv})",
2651                                 app_path, NULL),
2652                         G_DBUS_CALL_FLAGS_NONE, -1,
2653                         NULL,
2654                         (GAsyncReadyCallback)__bt_hal_register_application_cb,
2655                         (gpointer)data);
2656         INFO("GATT server started");
2657 }
2658
2659 static bt_status_t gatt_server_start_service(int server_if, int service_handle, int transport)
2660 {
2661         CHECK_BTGATT_INIT();
2662         struct gatt_service_info *serv_info = NULL;
2663         hal_gatt_service_started *user_data = NULL;
2664         DBG("Start GATT Service svc hdl [%d], slot [%d]", service_handle, server_if);
2665
2666         /* Fetch service data for the GATT server */
2667         serv_info = __bt_gatt_find_gatt_service_info(server_if, service_handle);
2668         if (serv_info == NULL)
2669                 return BT_STATUS_FAIL;
2670
2671         if (serv_info->is_svc_registered)
2672                 DBG("service already registered \n");
2673
2674         serv_info->is_svc_registered = TRUE;
2675
2676         /* Send Service handle to application */
2677         user_data = g_malloc0(sizeof(hal_gatt_service_started));
2678         user_data->srvc_hdl = serv_info->service_handle;
2679         user_data->instance_data = server_if;
2680         g_idle_add(__bt_hal_gatt_service_started_cb, (gpointer)user_data);
2681
2682         /* If this is nth Service that is started, then register application at this point */
2683         if (__bt_is_service_last_in_server_list(server_if, service_handle)) {
2684                 DBG("This is the last service started from the GATT Server's list of services handle [%d]",
2685                         service_handle);
2686                 __bt_register_application_to_dbus(server_if);
2687         }
2688
2689         return BT_STATUS_SUCCESS;
2690 }
2691
2692 static bt_status_t gatt_server_stop_service(int server_if, int service_handle)
2693 {
2694         CHECK_BTGATT_INIT();
2695         INFO("Stop service successful");
2696         return BT_STATUS_SUCCESS;
2697 }
2698
2699 static bt_status_t gatt_server_delete_service(int server_if, int service_handle)
2700 {
2701         CHECK_BTGATT_INIT();
2702         struct gatt_service_info *serv_info = NULL;
2703         hal_gatt_service_deleted *user_data = NULL;
2704         GSList *l = NULL;
2705         GSList *l1 = NULL;
2706         int err = BT_STATUS_SUCCESS;
2707         int ret = BT_STATUS_SUCCESS;
2708         INFO("Slot [%d] service handle [%d]", server_if, service_handle);
2709
2710         /* Fetch service data for the GATT server */
2711         serv_info = __bt_gatt_find_gatt_service_info(server_if, service_handle);
2712         if (serv_info == NULL) {
2713                 ERR("Could not find service info svc handle [%d] server slot [%d]",
2714                                 service_handle, server_if);
2715                 return BT_STATUS_FAIL;
2716         }
2717
2718         if (serv_info->is_svc_registered == FALSE) {
2719                 ERR("service Not registered path [%s] handle [%d]",
2720                         serv_info->serv_path, service_handle);
2721         }
2722
2723         for (l = serv_info->char_data; l != NULL; l = g_slist_next(l)) {
2724                 struct gatt_char_info *char_info = l->data;
2725
2726                 if (char_info == NULL)
2727                         break;
2728
2729                 for (l1 = char_info->desc_data; l1 != NULL; l1 = g_slist_next(l1)) {
2730                         struct gatt_desc_info *desc_info = l1->data;
2731
2732                         if (desc_info == NULL)
2733                                 break;
2734
2735                         ret = g_dbus_connection_unregister_object(g_conn,
2736                                         desc_info->desc_id);
2737                         if (ret) {
2738                                 __bt_hal_gatt_emit_interface_removed(
2739                                                 desc_info->desc_path,
2740                                                 GATT_DESC_INTERFACE);
2741                         } else {
2742                                 err = BT_STATUS_FAIL;
2743                         }
2744
2745                         /* list remove & free */
2746                         char_info->desc_data = g_slist_remove(char_info->desc_data, desc_info);
2747                         __bt_hal_gatt_free_descriptor_info(desc_info);
2748                 }
2749
2750                 g_slist_free(char_info->desc_data);
2751                 char_info->desc_data = NULL;
2752
2753                 ret = g_dbus_connection_unregister_object(g_conn,
2754                                 char_info->char_id);
2755                 if (ret) {
2756                         __bt_hal_gatt_emit_interface_removed(char_info->char_path,
2757                                         GATT_CHAR_INTERFACE);
2758                 } else {
2759                         INFO("Err");
2760                         err = BT_STATUS_FAIL;
2761                 }
2762
2763                 /* list remove & free */
2764                 serv_info->char_data = g_slist_remove(serv_info->char_data, char_info);
2765                 __bt_hal_gatt_free_characteristic_info(char_info);
2766         }
2767
2768         g_slist_free(serv_info->char_data);
2769         serv_info->char_data = NULL;
2770
2771         ret = g_dbus_connection_unregister_object(g_conn, serv_info->serv_id);
2772         if (ret) {
2773                 __bt_hal_gatt_emit_interface_removed(serv_info->serv_path,
2774                                 GATT_SERV_INTERFACE);
2775         } else {
2776                 INFO("Failed!!");
2777                 err = BT_STATUS_FAIL;
2778         }
2779
2780         ret = g_dbus_connection_unregister_object(g_conn, serv_info->prop_id);
2781         if (ret)
2782                 DBG("Unregistered the service on properties interface");
2783
2784         /* Remove from global list */
2785         gatt_services = g_slist_remove(gatt_services, serv_info);
2786         INFO("After removing from global list total service dount [%d]", g_slist_length(gatt_services));
2787
2788         /* Remove from GATT Server's list of services */
2789         _bt_remote_service_from_gatt_server(server_if, service_handle);
2790
2791         if (gatt_services == NULL)
2792                 INFO("All GATT Services of all GATT Servers are unregistered");
2793
2794         if (err == BT_STATUS_SUCCESS) {
2795                 INFO("Send GATT Service deleted Event");
2796                 /* Send Service handle to application */
2797                 user_data = g_malloc0(sizeof(hal_gatt_service_deleted));
2798                 user_data->srvc_hdl = serv_info->service_handle;
2799                 user_data->instance_data = server_if;
2800                 g_idle_add(__bt_hal_gatt_service_deleted_cb, (gpointer)user_data);
2801         }
2802
2803         /* Free the service */
2804         __bt_hal_gatt_free_service_info(serv_info);
2805         return err;
2806 }
2807
2808 static gboolean __bt_gatt_get_service_state(const char *service_path)
2809 {
2810         struct gatt_service_info *svc_info = NULL;
2811         GSList *l = NULL;
2812         for (l = gatt_services; l; l = g_slist_next(l)) {
2813
2814                 svc_info = (struct gatt_service_info *)l->data;
2815
2816
2817                 if (!g_strcmp0(svc_info->serv_path, service_path)) {
2818                         DBG("Return the state of the gatt service %d",
2819                                         svc_info->is_svc_registered);
2820                         return svc_info->is_svc_registered;
2821                 }
2822         }
2823
2824         DBG("gatt service info is NULL");
2825         return FALSE;
2826 }
2827
2828 static bt_status_t gatt_server_send_indication(int server_if, int attribute_handle, int conn_id,
2829                 int len, int confirm, char* p_value)
2830 {
2831         CHECK_BTGATT_INIT();
2832
2833         /* For Notifying */
2834         GVariantBuilder *outer_builder;
2835         GVariantBuilder *invalidated_builder;
2836
2837         /* For Value update via PropertyChange */
2838         GVariantBuilder *outer_builder1;
2839         GVariantBuilder *inner_builder1;
2840         GVariantBuilder *invalidated_builder1;
2841         GVariant *update_value = NULL;
2842
2843         /* Other variables */
2844         struct gatt_client_info_t *conn_info = NULL;
2845         gchar *serv_path = NULL;
2846         char *char_path = NULL;
2847         gchar **line_argv = NULL;
2848         gboolean notify = TRUE;
2849         gboolean ret = TRUE;
2850         int err = BT_STATUS_SUCCESS;
2851         char addr[20];
2852         GError *error = NULL;
2853         int i;
2854
2855         memset(addr, 0x00, sizeof(addr));
2856
2857         conn_info = __bt_find_remote_gatt_client_info_from_conn(conn_id);
2858         if (conn_info == NULL) {
2859                 ERR("No Connection Inforamtion!!!");
2860                 return BT_STATUS_FAIL;
2861         }
2862
2863         DBG("Send Indication to GATT client addr [%s]", conn_info->addr);
2864
2865         char_path = __bt_gatt_find_char_path_from_handle(attribute_handle);
2866         if (char_path == NULL)
2867                 return BT_STATUS_FAIL;
2868
2869         line_argv = g_strsplit_set(char_path, "/", 0);
2870         serv_path = g_strdup_printf("/%s/%s/%s", line_argv[1], line_argv[2], line_argv[3]);
2871
2872         if (!__bt_gatt_get_service_state(serv_path)) {
2873                 DBG("service not registered for this characteristic \n");
2874                 g_free(serv_path);
2875                 g_strfreev(line_argv);
2876                 return BT_STATUS_FAIL;
2877         }
2878
2879         outer_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
2880         invalidated_builder = g_variant_builder_new(G_VARIANT_TYPE("as"));
2881
2882         g_variant_builder_add(outer_builder, "{sv}", "Notifying",
2883                         g_variant_new("b", notify));
2884
2885         _bt_hal_convert_addr_type_to_string(addr, (unsigned char *)conn_info->addr);
2886
2887         g_variant_builder_add(outer_builder, "{sv}", "Unicast",
2888                         g_variant_new("s", addr));
2889
2890         DBG("Set characteristic Notification \n");
2891         ret = g_dbus_connection_emit_signal(g_conn, NULL,
2892                         char_path,
2893                         "org.freedesktop.DBus.Properties",
2894                         "PropertiesChanged",
2895                         g_variant_new("(sa{sv}as)",
2896                                 "org.bluez.GattCharacteristic1",
2897                                 outer_builder, invalidated_builder),
2898                         &error);
2899
2900         if (!ret) {
2901                 if (error != NULL) {
2902                         ERR("D-Bus API failure: errCode[%x], \
2903                                         message[%s]",
2904                                         error->code, error->message);
2905                         g_clear_error(&error);
2906                 }
2907                 err = BT_STATUS_FAIL;
2908         }
2909
2910         g_variant_builder_unref(outer_builder);
2911         g_variant_builder_unref(invalidated_builder);
2912
2913
2914         /* Notifying Done, now update Value to Bluez via PropertyChanged */
2915         invalidated_builder1 = g_variant_builder_new(G_VARIANT_TYPE("as"));
2916
2917         inner_builder1 = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
2918         for (i = 0; i < len; i++)
2919                 g_variant_builder_add(inner_builder1, "y", p_value[i]);
2920
2921         update_value = g_variant_new("ay", inner_builder1);
2922
2923
2924         outer_builder1 = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
2925         g_variant_builder_add(outer_builder1, "{sv}", "Value",
2926                         update_value);
2927
2928         DBG("Updating characteristic value \n");
2929         ret = g_dbus_connection_emit_signal(g_conn, NULL,
2930                         char_path,
2931                         "org.freedesktop.DBus.Properties",
2932                         "PropertiesChanged",
2933                         g_variant_new("(sa{sv}as)",
2934                                 "org.bluez.GattCharacteristic1",
2935                                 outer_builder1, invalidated_builder1),
2936                         &error);
2937
2938         if (!ret) {
2939                 if (error != NULL) {
2940                         ERR("D-Bus API failure: errCode[%x], \
2941                                         message[%s]",
2942                                         error->code, error->message);
2943                         g_clear_error(&error);
2944                 }
2945                 err = BT_STATUS_FAIL;
2946         } else {
2947                 struct gatt_char_info *char_info = NULL;
2948
2949                 char_info = __bt_gatt_find_char_info_from_handle(attribute_handle);
2950                 if (char_info == NULL) {
2951                         g_free(serv_path);
2952                         g_strfreev(line_argv);
2953                         g_variant_builder_unref(inner_builder1);
2954                         g_variant_builder_unref(outer_builder1);
2955                         g_variant_builder_unref(invalidated_builder1);
2956
2957                         return BT_STATUS_FAIL;
2958                 }
2959
2960                 char_info->value_length = len;
2961
2962                 char_info->char_value = (char *)realloc(char_info->char_value, len);
2963                 if (char_info->char_value) {
2964                         for (i = 0; i < len; i++)
2965                                 char_info->char_value[i] = p_value[i];
2966                 }
2967         }
2968
2969         g_free(serv_path);
2970         g_strfreev(line_argv);
2971         g_variant_builder_unref(inner_builder1);
2972         g_variant_builder_unref(outer_builder1);
2973         g_variant_builder_unref(invalidated_builder1);
2974
2975         return err;
2976 }
2977
2978 static bt_status_t gatt_server_send_response(int conn_id, int trans_id,
2979                 int status, btgatt_response_t *response)
2980 {
2981         CHECK_BTGATT_INIT();
2982
2983         struct gatt_req_info *req_info = NULL;
2984         struct gatt_client_info_t *conn_info = NULL;
2985         int i;
2986
2987         DBG("GATT Server Send Response Conn ID [%d]", conn_id);
2988
2989         conn_info = __bt_find_remote_gatt_client_info_from_conn(conn_id);
2990         if (conn_info == NULL) {
2991                 ERR("No Connection Inforamtion!!!");
2992                 return BT_STATUS_FAIL;
2993         }
2994
2995         req_info =  __bt_find_remote_gatt_client_request_info(conn_id, trans_id);
2996         if (req_info == NULL) {
2997                 ERR("No Request Inforamtion!!!");
2998                 return BT_STATUS_FAIL;
2999         }
3000
3001         if (status != BT_STATUS_SUCCESS) {
3002                 ERR("resp_state is 0x%X", status);
3003
3004                 g_dbus_method_invocation_return_dbus_error(req_info->context,
3005                                 "org.bluez.Error.Failed", "Application Error");
3006
3007                 conn_info->gatt_req_info_list = g_slist_remove(conn_info->gatt_req_info_list, req_info);
3008
3009                 req_info->context = NULL;
3010                 if (req_info->attr_path)
3011                         g_free(req_info->attr_path);
3012                 if (req_info->svc_path)
3013                         g_free(req_info->svc_path);
3014                 g_free(req_info);
3015
3016                 return BT_STATUS_SUCCESS;
3017         }
3018
3019         DBG("Reponse Value length [%d]", response->attr_value.len);
3020         DBG("Request type: [%d]", req_info->request_type);
3021
3022         /* DEBUG */
3023         for (i = 0; i < response->attr_value.len; i++)
3024                 DBG("Resonse [%d] = [0x%x]", response->attr_value.value[i]);
3025
3026         if (req_info->request_type == BT_HAL_GATT_REQUEST_TYPE_READ) {
3027                 GVariantBuilder *inner_builder = NULL;
3028                 inner_builder = g_variant_builder_new(G_VARIANT_TYPE("ay"));
3029
3030                 if (response->attr_value.len > 0) {
3031                         for (i = 0; i < response->attr_value.len; i++)
3032                                 g_variant_builder_add(inner_builder, "y", response->attr_value.value[i]);
3033                 }
3034                 g_dbus_method_invocation_return_value(req_info->context,
3035                                 g_variant_new("(ay)", inner_builder));
3036
3037                 g_variant_builder_unref(inner_builder);
3038         } else {
3039                 g_dbus_method_invocation_return_value(req_info->context, NULL);
3040         }
3041         conn_info->gatt_req_info_list = g_slist_remove(conn_info->gatt_req_info_list, req_info);
3042
3043         req_info->context = NULL;
3044         if (req_info->attr_path)
3045                 g_free(req_info->attr_path);
3046         if (req_info->svc_path)
3047                 g_free(req_info->svc_path);
3048         g_free(req_info);
3049
3050         return BT_STATUS_SUCCESS;
3051 }
3052
3053
3054 static bt_status_t gatt_server_send_acquire_response(int conn_id, int trans_id,
3055                 int status, int fd, int mtu, void *fdlist)
3056 {
3057         CHECK_BTGATT_INIT();
3058
3059         struct gatt_req_info *req_info = NULL;
3060         struct gatt_client_info_t *conn_info = NULL;
3061
3062         DBG("GATT Server Send Response Conn ID [%d]", conn_id);
3063
3064         conn_info = __bt_find_remote_gatt_client_info_from_conn(conn_id);
3065         if (conn_info == NULL) {
3066                 ERR("No Connection Inforamtion!!!");
3067                 return BT_STATUS_FAIL;
3068         }
3069
3070         req_info =  __bt_find_remote_gatt_client_request_info(conn_id, trans_id);
3071         if (req_info == NULL) {
3072                 ERR("No Request Inforamtion!!!");
3073                 return BT_STATUS_FAIL;
3074         }
3075
3076         if (status != BT_STATUS_SUCCESS) {
3077                 ERR("resp_state is 0x%X", status);
3078
3079                 g_dbus_method_invocation_return_dbus_error(req_info->context,
3080                                 "org.bluez.Error.Failed", "Application Error");
3081
3082                 conn_info->gatt_req_info_list = g_slist_remove(conn_info->gatt_req_info_list, req_info);
3083
3084                 req_info->context = NULL;
3085                 if (req_info->attr_path)
3086                         g_free(req_info->attr_path);
3087                 if (req_info->svc_path)
3088                         g_free(req_info->svc_path);
3089                 g_free(req_info);
3090
3091                 return BT_STATUS_SUCCESS;
3092         }
3093
3094
3095          if (req_info->request_type == BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_WRITE) {
3096
3097                 INFO("GATT Server Send Response BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_WRITE to bluez  %d\n", fd);
3098                 g_dbus_method_invocation_return_value_with_unix_fd_list(
3099                                 req_info->context, g_variant_new("(hq)", 0, mtu), (GUnixFDList*)fdlist);
3100
3101         } else if (req_info->request_type == BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_NOTIFY) {
3102
3103                 INFO("GATT Server Send Response BT_HAL_GATT_REQUEST_TYPE_ACQUIRE_NOTIFY  to bluez  %d\n", fd);
3104                 g_dbus_method_invocation_return_value_with_unix_fd_list(
3105                                 req_info->context, g_variant_new("(hq)", 0, mtu), (GUnixFDList*)fdlist);
3106
3107         } else {
3108                 g_dbus_method_invocation_return_value(req_info->context, NULL);
3109         }
3110         conn_info->gatt_req_info_list = g_slist_remove(conn_info->gatt_req_info_list, req_info);
3111
3112         req_info->context = NULL;
3113         if (req_info->attr_path)
3114                 g_free(req_info->attr_path);
3115         if (req_info->svc_path)
3116                 g_free(req_info->svc_path);
3117         g_free(req_info);
3118
3119         return BT_STATUS_SUCCESS;
3120 }
3121
3122
3123 static bt_status_t gatt_server_update_att_value(int server_if, int attribute_handle,
3124                 int value_length, char* att_value)
3125 {
3126         CHECK_BTGATT_INIT();
3127
3128         /* Other variables */
3129         char *char_path = NULL;
3130         gboolean ret = TRUE;
3131         GError *error = NULL;
3132
3133         GVariantBuilder *outer_builder;
3134         GVariantBuilder *inner_builder;
3135         GVariantBuilder *invalidated_builder;
3136         GVariant *update_value = NULL;
3137         int err = BT_STATUS_SUCCESS;
3138         int i = 0;
3139         gchar **line_argv = NULL;
3140         gchar *serv_path = NULL;
3141
3142         char_path = __bt_gatt_find_char_path_from_handle(attribute_handle);
3143         if (char_path == NULL)
3144                 return BT_STATUS_FAIL;
3145
3146         line_argv = g_strsplit_set(char_path, "/", 0);
3147         serv_path = g_strdup_printf("/%s/%s/%s", line_argv[1], line_argv[2], line_argv[3]);
3148
3149         if (!__bt_gatt_get_service_state(serv_path)) {
3150                 DBG("service not registered for this characteristic \n");
3151                 g_free(serv_path);
3152                 g_strfreev(line_argv);
3153                 return BT_STATUS_FAIL;
3154         }
3155
3156         g_free(serv_path);
3157         line_argv = g_strsplit_set(char_path, "/", 0);
3158         serv_path = g_strdup_printf("/%s/%s/%s", line_argv[1], line_argv[2], line_argv[3]);
3159
3160         if (!__bt_gatt_get_service_state(serv_path)) {
3161                 DBG("service not registered for this characteristic \n");
3162                 g_free(serv_path);
3163                 g_strfreev(line_argv);
3164                 return BT_STATUS_FAIL;
3165         }
3166
3167         outer_builder = g_variant_builder_new(G_VARIANT_TYPE("a{sv}"));
3168         invalidated_builder = g_variant_builder_new(G_VARIANT_TYPE("as"));
3169
3170         inner_builder = g_variant_builder_new(G_VARIANT_TYPE_ARRAY);
3171         for (i = 0; i < value_length; i++)
3172                 g_variant_builder_add(inner_builder, "y", att_value[i]);
3173
3174         update_value = g_variant_new("ay", inner_builder);
3175
3176         g_variant_builder_add(outer_builder, "{sv}", "Value",
3177                         update_value);
3178
3179         DBG("Updating characteristic value \n");
3180         ret = g_dbus_connection_emit_signal(g_conn, NULL,
3181                         char_path,
3182                         "org.freedesktop.DBus.Properties",
3183                         "PropertiesChanged",
3184                         g_variant_new("(sa{sv}as)",
3185                                 "org.bluez.GattCharacteristic1",
3186                                 outer_builder, invalidated_builder),
3187                         &error);
3188
3189         if (!ret) {
3190                 if (error != NULL) {
3191                         ERR("D-Bus API failure: errCode[%x], \
3192                                         message[%s]",
3193                                         error->code, error->message);
3194                         g_clear_error(&error);
3195                 }
3196                 err = BT_STATUS_FAIL;
3197         } else {
3198                 struct gatt_char_info *char_info = NULL;
3199
3200                 char_info = __bt_gatt_find_char_info_from_handle(attribute_handle);
3201                 if (char_info == NULL) {
3202                         g_free(serv_path);
3203                         g_strfreev(line_argv);
3204                         g_variant_builder_unref(inner_builder);
3205                         g_variant_builder_unref(outer_builder);
3206                         g_variant_builder_unref(invalidated_builder);
3207
3208                         return BT_STATUS_FAIL;
3209                 }
3210
3211                 char_info->value_length = value_length;
3212
3213                 char_info->char_value = (char *)realloc(char_info->char_value, value_length);
3214                 if (char_info->char_value) {
3215                         for (i = 0; i < value_length; i++)
3216                                 char_info->char_value[i] = att_value[i];
3217                 }
3218         }
3219
3220         /* Free data */
3221         g_free(serv_path);
3222         g_strfreev(line_argv);
3223         g_variant_builder_unref(inner_builder);
3224         g_variant_builder_unref(outer_builder);
3225         g_variant_builder_unref(invalidated_builder);
3226
3227         return err;
3228 }
3229
3230 static bt_status_t gatt_server_listen(int server_if, bool start)
3231 {
3232         CHECK_BTGATT_INIT();
3233         /* Send Data to LE Module */
3234         return _bt_hal_enable_advertising(server_if, start, FALSE);
3235 }
3236
3237 static bt_status_t gatt_server_set_adv_data(int server_if, bool set_scan_rsp, bool include_name,
3238                 bool include_txpower, int min_interval, int max_interval, int appearance,
3239                 uint16_t manufacturer_len, char* manufacturer_data,
3240                 uint16_t service_data_len, char* service_data,
3241                 uint16_t service_uuid_len, char* service_uuid)
3242 {
3243         CHECK_BTGATT_INIT();
3244         return BT_STATUS_SUCCESS;
3245 }
3246
3247 static bt_status_t gatt_server_multi_adv_enable(int server_if)
3248 {
3249         CHECK_BTGATT_INIT();
3250         /* Send Enable Advertising request to LE Module */
3251         return _bt_hal_enable_advertising(server_if, TRUE, TRUE);
3252 }
3253
3254 static bt_status_t gatt_server_multi_adv_update(int server_if, int min_interval, int max_interval, int adv_type,
3255                 int chnl_map, int tx_power, int timeout_s)
3256 {
3257         CHECK_BTGATT_INIT();
3258         DBG("+");
3259         /* Send Advertising parameters to LE Module */
3260         return _bt_hal_set_advertising_params(server_if, min_interval, max_interval, adv_type,
3261                         chnl_map, tx_power, timeout_s);
3262 }
3263
3264 static bt_status_t gatt_server_multi_adv_set_inst_data(btgatt_adv_param_setup_t adv_param_setup)
3265 {
3266         CHECK_BTGATT_INIT();
3267         DBG("+");
3268         /* Send Data to LE Module */
3269         return _bt_hal_set_advertising_data(adv_param_setup);
3270 }
3271
3272 static bt_status_t gatt_server_multi_adv_disable(int server_if)
3273 {
3274         CHECK_BTGATT_INIT();
3275         /* Send Data to LE Module */
3276         return _bt_hal_enable_advertising(server_if, FALSE, TRUE);
3277 }
3278
3279 static bt_status_t gatt_server_get_mtu_size(int conn_id, int *mtu_size)
3280 {
3281         CHECK_BTGATT_INIT();
3282         char *object_path = NULL;
3283
3284         GDBusProxy *device_proxy;
3285         GError *error = NULL;
3286         GVariant *value;
3287         GVariant *tmp_value;
3288         GDBusConnection *conn;
3289         GVariant *result = NULL;
3290         int ret = BT_STATUS_SUCCESS;
3291         struct gatt_client_info_t *conn_info = NULL;
3292         unsigned int mtu;
3293
3294         if (mtu_size == NULL)
3295                 return BT_STATUS_PARM_INVALID;
3296
3297         /* GDBUS Connection Info validate */
3298         conn = _bt_hal_get_system_gconn();
3299         if (conn == NULL) {
3300                 ERR("Could not get System DBUS Connection");
3301                 return  BT_STATUS_FAIL;
3302         }
3303
3304         /* Connection Info validate */
3305         conn_info = __bt_find_remote_gatt_client_info_from_conn(conn_id);
3306         if (conn_info == NULL) {
3307                 ERR("No Connection Inforamtion!!!");
3308                 return BT_STATUS_FAIL;
3309         }
3310
3311
3312         object_path = _bt_hal_get_device_object_path(conn_info->addr);
3313         if (object_path == NULL)
3314                 return BT_STATUS_FAIL;
3315
3316         device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
3317                         NULL, BT_HAL_BLUEZ_NAME, object_path,
3318                         BT_HAL_PROPERTIES_INTERFACE,  NULL, NULL);
3319
3320         g_free(object_path);
3321         if (device_proxy == NULL)
3322                 return BT_STATUS_FAIL;
3323
3324         result = g_dbus_proxy_call_sync(device_proxy, "GetAll",
3325                         g_variant_new("(s)", BT_HAL_DEVICE_INTERFACE),
3326                         G_DBUS_CALL_FLAGS_NONE,
3327                         -1,
3328                         NULL,
3329                         &error);
3330         if (result == NULL) {
3331                 if (error != NULL) {
3332                         ERR("Error occured in Proxy call [%s]\n", error->message);
3333                         g_error_free(error);
3334                 }
3335                 g_object_unref(device_proxy);
3336                 return BT_STATUS_FAIL;
3337         }
3338
3339         g_variant_get(result , "(@a{sv})", &value);
3340         g_variant_unref(result);
3341
3342         tmp_value = g_variant_lookup_value(value, "AttMtu", G_VARIANT_TYPE_UINT16);
3343         if (tmp_value == NULL) {
3344                 g_object_unref(device_proxy);
3345                 g_variant_unref(value);
3346                 return BT_STATUS_FAIL;
3347         }
3348
3349         mtu = g_variant_get_uint16(tmp_value);
3350
3351         DBG("ATT MTU : [%d]", mtu);
3352
3353         g_variant_unref(tmp_value);
3354         g_variant_unref(value);
3355         g_object_unref(device_proxy);
3356
3357         *mtu_size = (int) mtu;
3358
3359         return ret;
3360 }
3361
3362 const btgatt_server_interface_t btgatt_server_interface = {
3363         gatt_server_register_app,
3364         gatt_server_unregister_app,
3365         gatt_server_open,
3366         gatt_server_close,
3367         gatt_server_add_service,
3368         gatt_server_add_included_service,
3369         gatt_server_add_characteristic,
3370         gatt_server_add_descriptor,
3371         gatt_server_start_service,
3372         gatt_server_stop_service,
3373         gatt_server_delete_service,
3374         gatt_server_send_indication,
3375         gatt_server_send_response,
3376         gatt_server_update_att_value,
3377         gatt_server_listen,
3378         gatt_server_set_adv_data,
3379         gatt_server_multi_adv_enable,
3380         gatt_server_multi_adv_update,
3381         gatt_server_multi_adv_set_inst_data,
3382         gatt_server_multi_adv_disable,
3383         gatt_server_get_mtu_size,
3384         gatt_server_send_acquire_response
3385 };