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