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