client/gatt: Fix using atoi
[platform/upstream/bluez.git] / client / gatt.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  BlueZ - Bluetooth protocol stack for Linux
5  *
6  *  Copyright (C) 2014  Intel Corporation. All rights reserved.
7  *
8  *
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include <config.h>
13 #endif
14
15 #include <stdio.h>
16 #include <errno.h>
17 #include <unistd.h>
18 #include <stdlib.h>
19 #include <stdbool.h>
20 #include <sys/uio.h>
21 #include <fcntl.h>
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/socket.h>
25
26 #include <glib.h>
27
28 #include "src/shared/util.h"
29 #include "src/shared/queue.h"
30 #include "src/shared/io.h"
31 #include "src/shared/shell.h"
32 #include "gdbus/gdbus.h"
33 #include "gatt.h"
34
35 #define APP_PATH "/org/bluez/app"
36 #define DEVICE_INTERFACE "org.bluez.Device1"
37 #define PROFILE_INTERFACE "org.bluez.GattProfile1"
38 #define SERVICE_INTERFACE "org.bluez.GattService1"
39 #define CHRC_INTERFACE "org.bluez.GattCharacteristic1"
40 #define DESC_INTERFACE "org.bluez.GattDescriptor1"
41
42 /* String display constants */
43 #define COLORED_NEW     COLOR_GREEN "NEW" COLOR_OFF
44 #define COLORED_CHG     COLOR_YELLOW "CHG" COLOR_OFF
45 #define COLORED_DEL     COLOR_RED "DEL" COLOR_OFF
46
47 #define MAX_ATTR_VAL_LEN        512
48
49 struct desc {
50         struct chrc *chrc;
51         char *path;
52         uint16_t handle;
53         char *uuid;
54         char **flags;
55         size_t value_len;
56         unsigned int max_val_len;
57         uint8_t *value;
58 };
59
60 struct chrc {
61         struct service *service;
62         GDBusProxy *proxy;
63         char *path;
64         uint16_t handle;
65         char *uuid;
66         char **flags;
67         bool notifying;
68         GList *descs;
69         size_t value_len;
70         unsigned int max_val_len;
71         uint8_t *value;
72         uint16_t mtu;
73         struct io *write_io;
74         struct io *notify_io;
75         bool authorization_req;
76 };
77
78 struct service {
79         DBusConnection *conn;
80         GDBusProxy *proxy;
81         char *path;
82         uint16_t handle;
83         char *uuid;
84         bool primary;
85         GList *chrcs;
86         GList *inc;
87 };
88
89 static GList *local_services;
90 static GList *services;
91 static GList *characteristics;
92 static GList *descriptors;
93 static GList *managers;
94 static GList *uuids;
95 static DBusMessage *pending_message = NULL;
96
97 struct sock_io {
98         GDBusProxy *proxy;
99         struct io *io;
100         uint16_t mtu;
101 };
102
103 static struct sock_io write_io;
104 static struct sock_io notify_io;
105
106 static void print_service(struct service *service, const char *description)
107 {
108         const char *text;
109
110         text = bt_uuidstr_to_str(service->uuid);
111         if (!text)
112                 bt_shell_printf("%s%s%s%s Service (Handle 0x%04x)\n\t%s\n\t"
113                                         "%s\n",
114                                         description ? "[" : "",
115                                         description ? : "",
116                                         description ? "] " : "",
117                                         service->primary ? "Primary" :
118                                         "Secondary",
119                                         service->handle, service->path,
120                                         service->uuid);
121         else
122                 bt_shell_printf("%s%s%s%s Service (Handle 0x%04x)\n\t%s\n\t%s"
123                                         "\n\t%s\n",
124                                         description ? "[" : "",
125                                         description ? : "",
126                                         description ? "] " : "",
127                                         service->primary ? "Primary" :
128                                         "Secondary",
129                                         service->handle, service->path,
130                                         service->uuid, text);
131 }
132
133 static void print_inc_service(struct service *service, const char *description)
134 {
135         const char *text;
136
137         text = bt_uuidstr_to_str(service->uuid);
138         if (!text)
139                 bt_shell_printf("%s%s%s%s Included Service (Handle 0x%04x)\n\t"
140                                         "%s\n\t%s\n",
141                                         description ? "[" : "",
142                                         description ? : "",
143                                         description ? "] " : "",
144                                         service->primary ? "Primary" :
145                                         "Secondary",
146                                         service->handle, service->path,
147                                         service->uuid);
148         else
149                 bt_shell_printf("%s%s%s%s Included Service (Handle 0x%04x)\n\t"
150                                         "%s\n\t%s\n\t%s\n",
151                                         description ? "[" : "",
152                                         description ? : "",
153                                         description ? "] " : "",
154                                         service->primary ? "Primary" :
155                                         "Secondary",
156                                         service->handle, service->path,
157                                         service->uuid, text);
158 }
159
160 static void print_service_proxy(GDBusProxy *proxy, const char *description)
161 {
162         struct service service;
163         DBusMessageIter iter;
164         const char *uuid;
165         dbus_bool_t primary;
166
167         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
168                 return;
169
170         dbus_message_iter_get_basic(&iter, &uuid);
171
172         if (g_dbus_proxy_get_property(proxy, "Primary", &iter) == FALSE)
173                 return;
174
175         dbus_message_iter_get_basic(&iter, &primary);
176
177         service.path = (char *) g_dbus_proxy_get_path(proxy);
178         service.uuid = (char *) uuid;
179         service.primary = primary;
180
181         print_service(&service, description);
182 }
183
184 void gatt_add_service(GDBusProxy *proxy)
185 {
186         services = g_list_append(services, proxy);
187
188         print_service_proxy(proxy, COLORED_NEW);
189 }
190
191 static struct service *remove_service_by_proxy(struct GDBusProxy *proxy)
192 {
193         GList *l;
194
195         for (l = local_services; l; l = g_list_next(l)) {
196                 struct service *service = l->data;
197
198                 if (service->proxy == proxy) {
199                         local_services = g_list_delete_link(local_services, l);
200                         return service;
201                 }
202         }
203
204         return NULL;
205 }
206
207 void gatt_remove_service(GDBusProxy *proxy)
208 {
209         struct service *service;
210         GList *l;
211
212         l = g_list_find(services, proxy);
213         if (!l)
214                 return;
215
216         services = g_list_delete_link(services, l);
217
218         print_service_proxy(proxy, COLORED_DEL);
219
220         service = remove_service_by_proxy(proxy);
221         if (service)
222                 g_dbus_unregister_interface(service->conn, service->path,
223                                                 SERVICE_INTERFACE);
224 }
225
226 static void print_chrc(struct chrc *chrc, const char *description)
227 {
228         const char *text;
229
230         text = bt_uuidstr_to_str(chrc->uuid);
231         if (!text)
232                 bt_shell_printf("%s%s%sCharacteristic (Handle 0x%04x)\n\t%s\n\t"
233                                         "%s\n",
234                                         description ? "[" : "",
235                                         description ? : "",
236                                         description ? "] " : "",
237                                         chrc->handle, chrc->path, chrc->uuid);
238         else
239                 bt_shell_printf("%s%s%sCharacteristic (Handle 0x%04x)\n\t%s\n\t"
240                                         "%s\n\t%s\n",
241                                         description ? "[" : "",
242                                         description ? : "",
243                                         description ? "] " : "",
244                                         chrc->handle, chrc->path, chrc->uuid,
245                                         text);
246 }
247
248 static void print_characteristic(GDBusProxy *proxy, const char *description)
249 {
250         struct chrc chrc;
251         DBusMessageIter iter;
252         const char *uuid;
253
254         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
255                 return;
256
257         dbus_message_iter_get_basic(&iter, &uuid);
258
259         chrc.path = (char *) g_dbus_proxy_get_path(proxy);
260         chrc.uuid = (char *) uuid;
261
262         print_chrc(&chrc, description);
263 }
264
265 static gboolean chrc_is_child(GDBusProxy *characteristic)
266 {
267         DBusMessageIter iter;
268         const char *service;
269
270         if (!g_dbus_proxy_get_property(characteristic, "Service", &iter))
271                 return FALSE;
272
273         dbus_message_iter_get_basic(&iter, &service);
274
275         return g_dbus_proxy_lookup(services, NULL, service,
276                                         "org.bluez.GattService1") != NULL;
277 }
278
279 void gatt_add_characteristic(GDBusProxy *proxy)
280 {
281         if (!chrc_is_child(proxy))
282                 return;
283
284         characteristics = g_list_append(characteristics, proxy);
285
286         print_characteristic(proxy, COLORED_NEW);
287 }
288
289 static void notify_io_destroy(void)
290 {
291         io_destroy(notify_io.io);
292         memset(&notify_io, 0, sizeof(notify_io));
293 }
294
295 static void write_io_destroy(void)
296 {
297         io_destroy(write_io.io);
298         memset(&write_io, 0, sizeof(write_io));
299 }
300
301 void gatt_remove_characteristic(GDBusProxy *proxy)
302 {
303         GList *l;
304
305         l = g_list_find(characteristics, proxy);
306         if (!l)
307                 return;
308
309         characteristics = g_list_delete_link(characteristics, l);
310
311         print_characteristic(proxy, COLORED_DEL);
312
313         if (write_io.proxy == proxy)
314                 write_io_destroy();
315         else if (notify_io.proxy == proxy)
316                 notify_io_destroy();
317 }
318
319 static void print_desc(struct desc *desc, const char *description)
320 {
321         const char *text;
322
323         text = bt_uuidstr_to_str(desc->uuid);
324         if (!text)
325                 bt_shell_printf("%s%s%sDescriptor (Handle 0x%04x)\n\t%s\n\t"
326                                         "%s\n",
327                                         description ? "[" : "",
328                                         description ? : "",
329                                         description ? "] " : "",
330                                         desc->handle, desc->path, desc->uuid);
331         else
332                 bt_shell_printf("%s%s%sDescriptor (Handle 0x%04x)\n\t%s\n\t"
333                                         "%s\n\t%s\n",
334                                         description ? "[" : "",
335                                         description ? : "",
336                                         description ? "] " : "",
337                                         desc->handle, desc->path, desc->uuid,
338                                         text);
339 }
340
341 static void print_descriptor(GDBusProxy *proxy, const char *description)
342 {
343         struct desc desc;
344         DBusMessageIter iter;
345         const char *uuid;
346
347         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
348                 return;
349
350         dbus_message_iter_get_basic(&iter, &uuid);
351
352         desc.path = (char *) g_dbus_proxy_get_path(proxy);
353         desc.uuid = (char *) uuid;
354
355         print_desc(&desc, description);
356 }
357
358 static gboolean descriptor_is_child(GDBusProxy *characteristic)
359 {
360         GList *l;
361         DBusMessageIter iter;
362         const char *service, *path;
363
364         if (!g_dbus_proxy_get_property(characteristic, "Characteristic", &iter))
365                 return FALSE;
366
367         dbus_message_iter_get_basic(&iter, &service);
368
369         for (l = characteristics; l; l = g_list_next(l)) {
370                 GDBusProxy *proxy = l->data;
371
372                 path = g_dbus_proxy_get_path(proxy);
373
374                 if (!strcmp(path, service))
375                         return TRUE;
376         }
377
378         return FALSE;
379 }
380
381 void gatt_add_descriptor(GDBusProxy *proxy)
382 {
383         if (!descriptor_is_child(proxy))
384                 return;
385
386         descriptors = g_list_append(descriptors, proxy);
387
388         print_descriptor(proxy, COLORED_NEW);
389 }
390
391 void gatt_remove_descriptor(GDBusProxy *proxy)
392 {
393         GList *l;
394
395         l = g_list_find(descriptors, proxy);
396         if (!l)
397                 return;
398
399         descriptors = g_list_delete_link(descriptors, l);
400
401         print_descriptor(proxy, COLORED_DEL);
402 }
403
404 static void list_attributes(const char *path, GList *source)
405 {
406         GList *l;
407
408         for (l = source; l; l = g_list_next(l)) {
409                 GDBusProxy *proxy = l->data;
410                 const char *proxy_path;
411
412                 proxy_path = g_dbus_proxy_get_path(proxy);
413
414                 if (!g_str_has_prefix(proxy_path, path))
415                         continue;
416
417                 if (source == services) {
418                         print_service_proxy(proxy, NULL);
419                         list_attributes(proxy_path, characteristics);
420                 } else if (source == characteristics) {
421                         print_characteristic(proxy, NULL);
422                         list_attributes(proxy_path, descriptors);
423                 } else if (source == descriptors)
424                         print_descriptor(proxy, NULL);
425         }
426 }
427
428 static void list_descs(GList *descs)
429 {
430         GList *l;
431
432         for (l = descs; l; l = g_list_next(l)) {
433                 struct desc *desc = l->data;
434
435                 print_desc(desc, NULL);
436         }
437 }
438
439 static void list_chrcs(GList *chrcs)
440 {
441         GList *l;
442
443         for (l = chrcs; l; l = g_list_next(l)) {
444                 struct chrc *chrc = l->data;
445
446                 print_chrc(chrc, NULL);
447
448                 list_descs(chrc->descs);
449         }
450 }
451
452 static void list_services(void)
453 {
454         GList *l;
455
456         for (l = local_services; l; l = g_list_next(l)) {
457                 struct service *service = l->data;
458
459                 print_service(service, NULL);
460
461                 list_chrcs(service->chrcs);
462         }
463 }
464
465 void gatt_list_attributes(const char *path)
466 {
467         if (path && !strcmp(path, "local")) {
468                 list_services();
469                 return bt_shell_noninteractive_quit(EXIT_SUCCESS);
470         }
471
472         list_attributes(path, services);
473         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
474 }
475
476 static GDBusProxy *select_attribute(const char *path)
477 {
478         GDBusProxy *proxy;
479
480         proxy = g_dbus_proxy_lookup(services, NULL, path,
481                                         "org.bluez.GattService1");
482         if (proxy)
483                 return proxy;
484
485         proxy = g_dbus_proxy_lookup(characteristics, NULL, path,
486                                         "org.bluez.GattCharacteristic1");
487         if (proxy)
488                 return proxy;
489
490         return g_dbus_proxy_lookup(descriptors, NULL, path,
491                                         "org.bluez.GattDescriptor1");
492 }
493
494 static GDBusProxy *select_proxy_by_uuid(GDBusProxy *parent, const char *uuid,
495                                         GList *source)
496 {
497         GList *l;
498         const char *value;
499         DBusMessageIter iter;
500
501         for (l = source; l; l = g_list_next(l)) {
502                 GDBusProxy *proxy = l->data;
503
504                 if (parent && !g_str_has_prefix(g_dbus_proxy_get_path(proxy),
505                                                 g_dbus_proxy_get_path(parent)))
506                         continue;
507
508                 if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
509                         continue;
510
511                 dbus_message_iter_get_basic(&iter, &value);
512
513                 if (strcasecmp(uuid, value) == 0)
514                         return proxy;
515
516                 if (strlen(uuid) == 4 && !strncasecmp(value + 4, uuid, 4))
517                         return proxy;
518         }
519
520         return NULL;
521 }
522
523 static GDBusProxy *select_attribute_by_uuid(GDBusProxy *parent,
524                                                         const char *uuid)
525 {
526         GDBusProxy *proxy;
527
528         proxy = select_proxy_by_uuid(parent, uuid, services);
529         if (proxy)
530                 return proxy;
531
532         proxy = select_proxy_by_uuid(parent, uuid, characteristics);
533         if (proxy)
534                 return proxy;
535
536         return select_proxy_by_uuid(parent, uuid, descriptors);
537 }
538
539 GDBusProxy *gatt_select_attribute(GDBusProxy *parent, const char *arg)
540 {
541         if (arg[0] == '/')
542                 return select_attribute(arg);
543
544         if (parent) {
545                 GDBusProxy *proxy = select_attribute_by_uuid(parent, arg);
546                 if (proxy)
547                         return proxy;
548         }
549
550         return select_attribute_by_uuid(NULL, arg);
551 }
552
553 static char *attribute_generator(const char *text, int state, GList *source)
554 {
555         static int index;
556
557         if (!state) {
558                 index = 0;
559         }
560
561         return g_dbus_proxy_path_lookup(source, &index, text);
562 }
563
564 char *gatt_attribute_generator(const char *text, int state)
565 {
566         static GList *list = NULL;
567
568         if (!state) {
569                 GList *list1;
570
571                 if (list) {
572                         g_list_free(list);
573                         list = NULL;
574                 }
575
576                 list1 = g_list_copy(characteristics);
577                 list1 = g_list_concat(list1, g_list_copy(descriptors));
578
579                 list = g_list_copy(services);
580                 list = g_list_concat(list, list1);
581         }
582
583         return attribute_generator(text, state, list);
584 }
585
586 static void read_reply(DBusMessage *message, void *user_data)
587 {
588         DBusError error;
589         DBusMessageIter iter, array;
590         uint8_t *value;
591         int len;
592
593         dbus_error_init(&error);
594
595         if (dbus_set_error_from_message(&error, message) == TRUE) {
596                 bt_shell_printf("Failed to read: %s\n", error.name);
597                 dbus_error_free(&error);
598                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
599         }
600
601         dbus_message_iter_init(message, &iter);
602
603         if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
604                 bt_shell_printf("Invalid response to read\n");
605                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
606         }
607
608         dbus_message_iter_recurse(&iter, &array);
609         dbus_message_iter_get_fixed_array(&array, &value, &len);
610
611         if (len < 0) {
612                 bt_shell_printf("Unable to parse value\n");
613                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
614         }
615
616         bt_shell_hexdump(value, len);
617
618         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
619 }
620
621 static void read_setup(DBusMessageIter *iter, void *user_data)
622 {
623         DBusMessageIter dict;
624         uint16_t *offset = user_data;
625
626         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
627                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
628                                         DBUS_TYPE_STRING_AS_STRING
629                                         DBUS_TYPE_VARIANT_AS_STRING
630                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
631                                         &dict);
632
633         g_dbus_dict_append_entry(&dict, "offset", DBUS_TYPE_UINT16, offset);
634
635         dbus_message_iter_close_container(iter, &dict);
636 }
637
638 static void read_attribute(GDBusProxy *proxy, uint16_t offset)
639 {
640         if (g_dbus_proxy_method_call(proxy, "ReadValue", read_setup, read_reply,
641                                                 &offset, NULL) == FALSE) {
642                 bt_shell_printf("Failed to read\n");
643                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
644         }
645
646         bt_shell_printf("Attempting to read %s\n", g_dbus_proxy_get_path(proxy));
647 }
648
649 static int parse_offset(const char *arg)
650 {
651         char *endptr = NULL;
652         unsigned long offset;
653
654         offset = strtoul(arg, &endptr, 0);
655         if (!endptr || *endptr != '\0' || offset > UINT16_MAX) {
656                 bt_shell_printf("Invalid offload: %s", arg);
657                 return -EINVAL;
658         }
659
660         return offset;
661 }
662
663 void gatt_read_attribute(GDBusProxy *proxy, int argc, char *argv[])
664 {
665         const char *iface;
666         int offset = 0;
667
668         iface = g_dbus_proxy_get_interface(proxy);
669         if (!strcmp(iface, "org.bluez.GattCharacteristic1") ||
670                                 !strcmp(iface, "org.bluez.GattDescriptor1")) {
671
672                 if (argc == 2) {
673                         offset = parse_offset(argv[1]);
674                         if (offset < 0)
675                                 goto fail;
676                 }
677
678                 read_attribute(proxy, offset);
679                 return;
680         }
681
682 fail:
683         bt_shell_printf("Unable to read attribute %s\n",
684                                                 g_dbus_proxy_get_path(proxy));
685         return bt_shell_noninteractive_quit(EXIT_FAILURE);
686 }
687
688 static void write_reply(DBusMessage *message, void *user_data)
689 {
690         DBusError error;
691
692         dbus_error_init(&error);
693
694         if (dbus_set_error_from_message(&error, message) == TRUE) {
695                 bt_shell_printf("Failed to write: %s\n", error.name);
696                 dbus_error_free(&error);
697                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
698         }
699
700         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
701 }
702
703 struct write_attribute_data {
704         DBusMessage *msg;
705         struct iovec iov;
706         char *type;
707         uint16_t offset;
708 };
709
710 static void write_setup(DBusMessageIter *iter, void *user_data)
711 {
712         struct write_attribute_data *wd = user_data;
713         DBusMessageIter array, dict;
714
715         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "y", &array);
716         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
717                                                 &wd->iov.iov_base,
718                                                 wd->iov.iov_len);
719         dbus_message_iter_close_container(iter, &array);
720
721         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
722                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
723                                         DBUS_TYPE_STRING_AS_STRING
724                                         DBUS_TYPE_VARIANT_AS_STRING
725                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
726                                         &dict);
727
728         if (wd->type)
729                 g_dbus_dict_append_entry(&dict, "type", DBUS_TYPE_STRING,
730                                                                 &wd->type);
731
732         g_dbus_dict_append_entry(&dict, "offset", DBUS_TYPE_UINT16,
733                                                                 &wd->offset);
734
735         dbus_message_iter_close_container(iter, &dict);
736 }
737
738 static int sock_send(struct io *io, struct iovec *iov, size_t iovlen)
739 {
740         struct msghdr msg;
741         int ret;
742
743         memset(&msg, 0, sizeof(msg));
744         msg.msg_iov = iov;
745         msg.msg_iovlen = iovlen;
746
747         ret = sendmsg(io_get_fd(io), &msg, MSG_NOSIGNAL);
748         if (ret < 0) {
749                 ret = -errno;
750                 bt_shell_printf("sendmsg: %s", strerror(-ret));
751         }
752
753         return ret;
754 }
755
756 static void write_attribute(GDBusProxy *proxy,
757                                 struct write_attribute_data *data)
758 {
759         /* Write using the fd if it has been acquired and fit the MTU */
760         if (proxy == write_io.proxy &&
761                         (write_io.io && write_io.mtu >= data->iov.iov_len)) {
762                 bt_shell_printf("Attempting to write fd %d\n",
763                                                 io_get_fd(write_io.io));
764                 if (sock_send(write_io.io, &data->iov, 1) < 0) {
765                         bt_shell_printf("Failed to write: %s", strerror(errno));
766                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
767                 }
768                 return;
769         }
770
771         if (g_dbus_proxy_method_call(proxy, "WriteValue", write_setup,
772                                         write_reply, data, NULL) == FALSE) {
773                 bt_shell_printf("Failed to write\n");
774                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
775         }
776
777         bt_shell_printf("Attempting to write %s\n",
778                                         g_dbus_proxy_get_path(proxy));
779 }
780
781 static uint8_t *str2bytearray(char *arg, size_t *val_len)
782 {
783         uint8_t value[MAX_ATTR_VAL_LEN];
784         char *entry;
785         unsigned int i;
786
787         for (i = 0; (entry = strsep(&arg, " \t")) != NULL; i++) {
788                 long int val;
789                 char *endptr = NULL;
790
791                 if (*entry == '\0')
792                         continue;
793
794                 if (i >= G_N_ELEMENTS(value)) {
795                         bt_shell_printf("Too much data\n");
796                         return NULL;
797                 }
798
799                 val = strtol(entry, &endptr, 0);
800                 if (!endptr || *endptr != '\0' || val > UINT8_MAX) {
801                         bt_shell_printf("Invalid value at index %d\n", i);
802                         return NULL;
803                 }
804
805                 value[i] = val;
806         }
807
808         *val_len = i;
809
810         return g_memdup(value, i);
811 }
812
813 void gatt_write_attribute(GDBusProxy *proxy, int argc, char *argv[])
814 {
815         const char *iface;
816         struct write_attribute_data data;
817
818         memset(&data, 0, sizeof(data));
819
820         iface = g_dbus_proxy_get_interface(proxy);
821         if (!strcmp(iface, "org.bluez.GattCharacteristic1") ||
822                                 !strcmp(iface, "org.bluez.GattDescriptor1")) {
823                 data.iov.iov_base = str2bytearray(argv[1], &data.iov.iov_len);
824
825                 if (argc > 2) {
826                         int offset;
827
828                         offset = parse_offset(argv[2]);
829                         if (offset < 0)
830                                 goto fail;
831
832                         data.offset = offset;
833                 }
834
835                 if (argc > 3)
836                         data.type = argv[3];
837
838                 write_attribute(proxy, &data);
839                 return;
840         }
841
842 fail:
843         bt_shell_printf("Unable to write attribute %s\n",
844                                                 g_dbus_proxy_get_path(proxy));
845
846         return bt_shell_noninteractive_quit(EXIT_FAILURE);
847 }
848
849 static bool sock_read(struct io *io, void *user_data)
850 {
851         struct chrc *chrc = user_data;
852         struct msghdr msg;
853         struct iovec iov;
854         uint8_t buf[MAX_ATTR_VAL_LEN];
855         int fd = io_get_fd(io);
856         ssize_t bytes_read;
857
858         if (io != notify_io.io && !chrc)
859                 return true;
860
861         iov.iov_base = buf;
862         iov.iov_len = sizeof(buf);
863
864         memset(&msg, 0, sizeof(msg));
865         msg.msg_iov = &iov;
866         msg.msg_iovlen = 1;
867
868         bytes_read = recvmsg(fd, &msg, MSG_DONTWAIT);
869         if (bytes_read < 0) {
870                 bt_shell_printf("recvmsg: %s", strerror(errno));
871                 return false;
872         }
873
874         if (!bytes_read)
875                 return false;
876
877         if (chrc)
878                 bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) "
879                                 "written:\n", chrc->path,
880                                 bt_uuidstr_to_str(chrc->uuid));
881         else
882                 bt_shell_printf("[" COLORED_CHG "] %s Notification:\n",
883                                 g_dbus_proxy_get_path(notify_io.proxy));
884
885         bt_shell_hexdump(buf, bytes_read);
886
887         return true;
888 }
889
890 static bool sock_hup(struct io *io, void *user_data)
891 {
892         struct chrc *chrc = user_data;
893
894         if (chrc) {
895                 bt_shell_printf("Attribute %s %s sock closed\n", chrc->path,
896                                 io == chrc->write_io ? "Write" : "Notify");
897
898                 if (io == chrc->write_io) {
899                         io_destroy(chrc->write_io);
900                         chrc->write_io = NULL;
901                 } else {
902                         io_destroy(chrc->notify_io);
903                         chrc->notify_io = NULL;
904                 }
905
906                 return false;
907         }
908
909         bt_shell_printf("%s closed\n", io == notify_io.io ? "Notify" : "Write");
910
911         if (io == notify_io.io)
912                 notify_io_destroy();
913         else
914                 write_io_destroy();
915
916         return false;
917 }
918
919 static struct io *sock_io_new(int fd, void *user_data)
920 {
921         struct io *io;
922
923         io = io_new(fd);
924
925         io_set_close_on_destroy(io, true);
926
927         io_set_read_handler(io, sock_read, user_data, NULL);
928
929         io_set_disconnect_handler(io, sock_hup, user_data, NULL);
930
931         return io;
932 }
933
934 static void acquire_write_reply(DBusMessage *message, void *user_data)
935 {
936         DBusError error;
937         int fd;
938
939         dbus_error_init(&error);
940
941         if (dbus_set_error_from_message(&error, message) == TRUE) {
942                 bt_shell_printf("Failed to acquire write: %s\n", error.name);
943                 dbus_error_free(&error);
944                 write_io.proxy = NULL;
945                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
946         }
947
948         if (write_io.io)
949                 write_io_destroy();
950
951         if ((dbus_message_get_args(message, NULL, DBUS_TYPE_UNIX_FD, &fd,
952                                         DBUS_TYPE_UINT16, &write_io.mtu,
953                                         DBUS_TYPE_INVALID) == false)) {
954                 bt_shell_printf("Invalid AcquireWrite response\n");
955                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
956         }
957
958         bt_shell_printf("AcquireWrite success: fd %d MTU %u\n", fd,
959                                                                 write_io.mtu);
960
961         write_io.io = sock_io_new(fd, NULL);
962         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
963 }
964
965 static void acquire_setup(DBusMessageIter *iter, void *user_data)
966 {
967         DBusMessageIter dict;
968
969         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
970                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
971                                         DBUS_TYPE_STRING_AS_STRING
972                                         DBUS_TYPE_VARIANT_AS_STRING
973                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
974                                         &dict);
975
976         dbus_message_iter_close_container(iter, &dict);
977 }
978
979 void gatt_acquire_write(GDBusProxy *proxy, const char *arg)
980 {
981         const char *iface;
982
983         iface = g_dbus_proxy_get_interface(proxy);
984         if (strcmp(iface, "org.bluez.GattCharacteristic1")) {
985                 bt_shell_printf("Unable to acquire write: %s not a"
986                                 " characteristic\n",
987                                 g_dbus_proxy_get_path(proxy));
988                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
989         }
990
991         if (g_dbus_proxy_method_call(proxy, "AcquireWrite", acquire_setup,
992                                 acquire_write_reply, NULL, NULL) == FALSE) {
993                 bt_shell_printf("Failed to AcquireWrite\n");
994                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
995         }
996
997         write_io.proxy = proxy;
998 }
999
1000 void gatt_release_write(GDBusProxy *proxy, const char *arg)
1001 {
1002         if (proxy != write_io.proxy || !write_io.io) {
1003                 bt_shell_printf("Write not acquired\n");
1004                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1005         }
1006
1007         write_io_destroy();
1008
1009         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1010 }
1011
1012 static void acquire_notify_reply(DBusMessage *message, void *user_data)
1013 {
1014         DBusError error;
1015         int fd;
1016
1017         dbus_error_init(&error);
1018
1019         if (dbus_set_error_from_message(&error, message) == TRUE) {
1020                 bt_shell_printf("Failed to acquire notify: %s\n", error.name);
1021                 dbus_error_free(&error);
1022                 write_io.proxy = NULL;
1023                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1024         }
1025
1026         if (notify_io.io) {
1027                 io_destroy(notify_io.io);
1028                 notify_io.io = NULL;
1029         }
1030
1031         notify_io.mtu = 0;
1032
1033         if ((dbus_message_get_args(message, NULL, DBUS_TYPE_UNIX_FD, &fd,
1034                                         DBUS_TYPE_UINT16, &notify_io.mtu,
1035                                         DBUS_TYPE_INVALID) == false)) {
1036                 bt_shell_printf("Invalid AcquireNotify response\n");
1037                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1038         }
1039
1040         bt_shell_printf("AcquireNotify success: fd %d MTU %u\n", fd,
1041                                                                 notify_io.mtu);
1042
1043         notify_io.io = sock_io_new(fd, NULL);
1044
1045         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1046 }
1047
1048 void gatt_acquire_notify(GDBusProxy *proxy, const char *arg)
1049 {
1050         const char *iface;
1051
1052         iface = g_dbus_proxy_get_interface(proxy);
1053         if (strcmp(iface, "org.bluez.GattCharacteristic1")) {
1054                 bt_shell_printf("Unable to acquire notify: %s not a"
1055                                 " characteristic\n",
1056                                 g_dbus_proxy_get_path(proxy));
1057                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1058         }
1059
1060         if (g_dbus_proxy_method_call(proxy, "AcquireNotify", acquire_setup,
1061                                 acquire_notify_reply, NULL, NULL) == FALSE) {
1062                 bt_shell_printf("Failed to AcquireNotify\n");
1063                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1064         }
1065
1066         notify_io.proxy = proxy;
1067 }
1068
1069 void gatt_release_notify(GDBusProxy *proxy, const char *arg)
1070 {
1071         if (proxy != notify_io.proxy || !notify_io.io) {
1072                 bt_shell_printf("Notify not acquired\n");
1073                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1074         }
1075
1076         notify_io_destroy();
1077
1078         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1079 }
1080
1081 static void notify_reply(DBusMessage *message, void *user_data)
1082 {
1083         bool enable = GPOINTER_TO_UINT(user_data);
1084         DBusError error;
1085
1086         dbus_error_init(&error);
1087
1088         if (dbus_set_error_from_message(&error, message) == TRUE) {
1089                 bt_shell_printf("Failed to %s notify: %s\n",
1090                                 enable ? "start" : "stop", error.name);
1091                 dbus_error_free(&error);
1092                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1093         }
1094
1095         bt_shell_printf("Notify %s\n", enable == TRUE ? "started" : "stopped");
1096
1097         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1098 }
1099
1100 static void notify_attribute(GDBusProxy *proxy, bool enable)
1101 {
1102         const char *method;
1103
1104         if (enable == TRUE)
1105                 method = "StartNotify";
1106         else
1107                 method = "StopNotify";
1108
1109         if (g_dbus_proxy_method_call(proxy, method, NULL, notify_reply,
1110                                 GUINT_TO_POINTER(enable), NULL) == FALSE) {
1111                 bt_shell_printf("Failed to %s notify\n",
1112                                 enable ? "start" : "stop");
1113                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1114         }
1115
1116         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1117 }
1118
1119 void gatt_notify_attribute(GDBusProxy *proxy, bool enable)
1120 {
1121         const char *iface;
1122
1123         iface = g_dbus_proxy_get_interface(proxy);
1124         if (!strcmp(iface, "org.bluez.GattCharacteristic1")) {
1125                 notify_attribute(proxy, enable);
1126                 return;
1127         }
1128
1129         bt_shell_printf("Unable to notify attribute %s\n",
1130                                                 g_dbus_proxy_get_path(proxy));
1131
1132         return bt_shell_noninteractive_quit(EXIT_FAILURE);
1133 }
1134
1135 static void register_app_setup(DBusMessageIter *iter, void *user_data)
1136 {
1137         DBusMessageIter opt;
1138         const char *path = "/";
1139
1140         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &path);
1141
1142         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1143                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
1144                                         DBUS_TYPE_STRING_AS_STRING
1145                                         DBUS_TYPE_VARIANT_AS_STRING
1146                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
1147                                         &opt);
1148         dbus_message_iter_close_container(iter, &opt);
1149
1150 }
1151
1152 static void register_app_reply(DBusMessage *message, void *user_data)
1153 {
1154         DBusError error;
1155
1156         dbus_error_init(&error);
1157
1158         if (dbus_set_error_from_message(&error, message) == TRUE) {
1159                 bt_shell_printf("Failed to register application: %s\n",
1160                                 error.name);
1161                 dbus_error_free(&error);
1162                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1163         }
1164
1165         bt_shell_printf("Application registered\n");
1166
1167         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1168 }
1169
1170 void gatt_add_manager(GDBusProxy *proxy)
1171 {
1172         managers = g_list_append(managers, proxy);
1173 }
1174
1175 void gatt_remove_manager(GDBusProxy *proxy)
1176 {
1177         managers = g_list_remove(managers, proxy);
1178 }
1179
1180 static int match_proxy(const void *a, const void *b)
1181 {
1182         GDBusProxy *proxy1 = (void *) a;
1183         GDBusProxy *proxy2 = (void *) b;
1184
1185         return strcmp(g_dbus_proxy_get_path(proxy1),
1186                                                 g_dbus_proxy_get_path(proxy2));
1187 }
1188
1189 static DBusMessage *release_profile(DBusConnection *conn,
1190                                         DBusMessage *msg, void *user_data)
1191 {
1192         g_dbus_unregister_interface(conn, APP_PATH, PROFILE_INTERFACE);
1193
1194         return dbus_message_new_method_return(msg);
1195 }
1196
1197 static const GDBusMethodTable methods[] = {
1198         { GDBUS_METHOD("Release", NULL, NULL, release_profile) },
1199         { }
1200 };
1201
1202 static gboolean get_uuids(const GDBusPropertyTable *property,
1203                                         DBusMessageIter *iter, void *data)
1204 {
1205         DBusMessageIter entry;
1206         GList *uuid;
1207
1208         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1209                                 DBUS_TYPE_STRING_AS_STRING, &entry);
1210
1211         for (uuid = uuids; uuid; uuid = g_list_next(uuid->next))
1212                 dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING,
1213                                                         &uuid->data);
1214
1215         dbus_message_iter_close_container(iter, &entry);
1216
1217         return TRUE;
1218 }
1219
1220 static const GDBusPropertyTable properties[] = {
1221         { "UUIDs", "as", get_uuids },
1222         { }
1223 };
1224
1225 void gatt_register_app(DBusConnection *conn, GDBusProxy *proxy,
1226                                         int argc, char *argv[])
1227 {
1228         GList *l;
1229         int i;
1230
1231         l = g_list_find_custom(managers, proxy, match_proxy);
1232         if (!l) {
1233                 bt_shell_printf("Unable to find GattManager proxy\n");
1234                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1235         }
1236
1237         for (i = 0; i < argc; i++)
1238                 uuids = g_list_append(uuids, g_strdup(argv[i]));
1239
1240         if (uuids) {
1241                 if (g_dbus_register_interface(conn, APP_PATH,
1242                                                 PROFILE_INTERFACE, methods,
1243                                                 NULL, properties, NULL,
1244                                                 NULL) == FALSE) {
1245                         bt_shell_printf("Failed to register application"
1246                                         " object\n");
1247                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
1248                 }
1249         }
1250
1251         if (g_dbus_proxy_method_call(l->data, "RegisterApplication",
1252                                                 register_app_setup,
1253                                                 register_app_reply, NULL,
1254                                                 NULL) == FALSE) {
1255                 bt_shell_printf("Failed register application\n");
1256                 g_dbus_unregister_interface(conn, APP_PATH, PROFILE_INTERFACE);
1257                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1258         }
1259 }
1260
1261 static void unregister_app_reply(DBusMessage *message, void *user_data)
1262 {
1263         DBusConnection *conn = user_data;
1264         DBusError error;
1265
1266         dbus_error_init(&error);
1267
1268         if (dbus_set_error_from_message(&error, message) == TRUE) {
1269                 bt_shell_printf("Failed to unregister application: %s\n",
1270                                 error.name);
1271                 dbus_error_free(&error);
1272                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1273         }
1274
1275         bt_shell_printf("Application unregistered\n");
1276
1277         if (!uuids)
1278                 return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1279
1280         g_list_free_full(uuids, g_free);
1281         uuids = NULL;
1282
1283         g_dbus_unregister_interface(conn, APP_PATH, PROFILE_INTERFACE);
1284
1285         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1286 }
1287
1288 static void unregister_app_setup(DBusMessageIter *iter, void *user_data)
1289 {
1290         const char *path = "/";
1291
1292         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &path);
1293 }
1294
1295 void gatt_unregister_app(DBusConnection *conn, GDBusProxy *proxy)
1296 {
1297         GList *l;
1298
1299         l = g_list_find_custom(managers, proxy, match_proxy);
1300         if (!l) {
1301                 bt_shell_printf("Unable to find GattManager proxy\n");
1302                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1303         }
1304
1305         if (g_dbus_proxy_method_call(l->data, "UnregisterApplication",
1306                                                 unregister_app_setup,
1307                                                 unregister_app_reply, conn,
1308                                                 NULL) == FALSE) {
1309                 bt_shell_printf("Failed unregister profile\n");
1310                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1311         }
1312 }
1313
1314 static void desc_free(void *data)
1315 {
1316         struct desc *desc = data;
1317
1318         g_free(desc->path);
1319         g_free(desc->uuid);
1320         g_strfreev(desc->flags);
1321         g_free(desc->value);
1322         g_free(desc);
1323 }
1324
1325 static void desc_unregister(void *data)
1326 {
1327         struct desc *desc = data;
1328
1329         print_desc(desc, COLORED_DEL);
1330
1331         g_dbus_unregister_interface(desc->chrc->service->conn, desc->path,
1332                                                 DESC_INTERFACE);
1333 }
1334
1335 static void chrc_free(void *data)
1336 {
1337         struct chrc *chrc = data;
1338
1339         g_list_free_full(chrc->descs, desc_unregister);
1340         g_free(chrc->path);
1341         g_free(chrc->uuid);
1342         g_strfreev(chrc->flags);
1343         g_free(chrc->value);
1344         g_free(chrc);
1345 }
1346
1347 static void chrc_unregister(void *data)
1348 {
1349         struct chrc *chrc = data;
1350
1351         print_chrc(chrc, COLORED_DEL);
1352
1353         g_dbus_unregister_interface(chrc->service->conn, chrc->path,
1354                                                 CHRC_INTERFACE);
1355 }
1356
1357 static void inc_unregister(void *data)
1358 {
1359         char *path = data;
1360
1361         g_free(path);
1362 }
1363
1364 static void service_free(void *data)
1365 {
1366         struct service *service = data;
1367
1368         g_list_free_full(service->chrcs, chrc_unregister);
1369         g_list_free_full(service->inc, inc_unregister);
1370         g_free(service->path);
1371         g_free(service->uuid);
1372         g_free(service);
1373 }
1374
1375 static gboolean service_get_handle(const GDBusPropertyTable *property,
1376                                         DBusMessageIter *iter, void *data)
1377 {
1378         struct service *service = data;
1379
1380         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16,
1381                                                 &service->handle);
1382
1383         return TRUE;
1384 }
1385
1386 static void service_set_handle(const GDBusPropertyTable *property,
1387                         DBusMessageIter *value, GDBusPendingPropertySet id,
1388                         void *data)
1389 {
1390         struct service *service = data;
1391
1392         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_UINT16) {
1393                 g_dbus_pending_property_error(id, "org.bluez.InvalidArguments",
1394                                         "Invalid arguments in method call");
1395                 return;
1396         }
1397
1398         dbus_message_iter_get_basic(value, &service->handle);
1399
1400         print_service(service, COLORED_CHG);
1401
1402         g_dbus_pending_property_success(id);
1403 }
1404
1405 static gboolean service_get_uuid(const GDBusPropertyTable *property,
1406                                         DBusMessageIter *iter, void *data)
1407 {
1408         struct service *service = data;
1409
1410         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &service->uuid);
1411
1412         return TRUE;
1413 }
1414
1415 static gboolean service_get_primary(const GDBusPropertyTable *property,
1416                                         DBusMessageIter *iter, void *data)
1417 {
1418         struct service *service = data;
1419         dbus_bool_t primary;
1420
1421         primary = service->primary ? TRUE : FALSE;
1422
1423         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &primary);
1424
1425         return TRUE;
1426 }
1427
1428
1429 static gboolean service_get_includes(const GDBusPropertyTable *property,
1430                                         DBusMessageIter *iter, void *data)
1431 {
1432         DBusMessageIter array;
1433         struct service *service = data;
1434         char *inc  = NULL;
1435         GList *l;
1436
1437         if (service->inc) {
1438                 for (l =  service->inc ; l; l = g_list_next(l)) {
1439
1440                         inc = l->data;
1441                         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1442                                 DBUS_TYPE_OBJECT_PATH_AS_STRING, &array);
1443
1444                         dbus_message_iter_append_basic(&array,
1445                                 DBUS_TYPE_OBJECT_PATH, &inc);
1446
1447                 }
1448
1449                 dbus_message_iter_close_container(iter, &array);
1450
1451                 return TRUE;
1452         }
1453
1454         return FALSE;
1455
1456 }
1457
1458 static gboolean service_exist_includes(const GDBusPropertyTable *property,
1459                                                         void *data)
1460 {
1461         struct service *service = data;
1462
1463         if (service->inc)
1464                 return TRUE;
1465         else
1466                 return FALSE;
1467
1468 }
1469
1470
1471 static const GDBusPropertyTable service_properties[] = {
1472         { "Handle", "q", service_get_handle, service_set_handle },
1473         { "UUID", "s", service_get_uuid },
1474         { "Primary", "b", service_get_primary },
1475         { "Includes", "ao", service_get_includes,
1476                 NULL,   service_exist_includes },
1477         { }
1478 };
1479
1480 static void service_set_primary(const char *input, void *user_data)
1481 {
1482         struct service *service = user_data;
1483
1484         if (!strcmp(input, "yes"))
1485                 service->primary = true;
1486         else if (!strcmp(input, "no")) {
1487                 service->primary = false;
1488         } else {
1489                 bt_shell_printf("Invalid option: %s\n", input);
1490                 local_services = g_list_remove(local_services, service);
1491                 print_service(service, COLORED_DEL);
1492                 g_dbus_unregister_interface(service->conn, service->path,
1493                                                 SERVICE_INTERFACE);
1494         }
1495 }
1496
1497 static uint16_t parse_handle(const char *arg)
1498 {
1499         char *endptr = NULL;
1500         unsigned long handle;
1501
1502         handle = strtoul(arg, &endptr, 0);
1503         if (!endptr || *endptr != '\0' || !handle || handle > UINT16_MAX) {
1504                 bt_shell_printf("Invalid handle: %s", arg);
1505                 return 0;
1506         }
1507
1508         return handle;
1509 }
1510
1511 void gatt_register_service(DBusConnection *conn, GDBusProxy *proxy,
1512                                                 int argc, char *argv[])
1513 {
1514         struct service *service;
1515         bool primary = true;
1516
1517         service = g_new0(struct service, 1);
1518         service->conn = conn;
1519         service->uuid = g_strdup(argv[1]);
1520         service->path = g_strdup_printf("%s/service%u", APP_PATH,
1521                                         g_list_length(local_services));
1522         service->primary = primary;
1523
1524         if (argc > 2) {
1525                 service->handle = parse_handle(argv[2]);
1526                 if (!service->handle)
1527                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
1528         }
1529
1530         if (g_dbus_register_interface(conn, service->path,
1531                                         SERVICE_INTERFACE, NULL, NULL,
1532                                         service_properties, service,
1533                                         service_free) == FALSE) {
1534                 bt_shell_printf("Failed to register service object\n");
1535                 service_free(service);
1536                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1537         }
1538
1539         print_service(service, COLORED_NEW);
1540
1541         local_services = g_list_append(local_services, service);
1542
1543         bt_shell_prompt_input(service->path, "Primary (yes/no):",
1544                  service_set_primary, service);
1545
1546         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1547 }
1548
1549 static struct service *service_find(const char *pattern)
1550 {
1551         GList *l;
1552
1553         for (l = local_services; l; l = g_list_next(l)) {
1554                 struct service *service = l->data;
1555
1556                 /* match object path */
1557                 if (!strcmp(service->path, pattern))
1558                         return service;
1559
1560                 /* match UUID */
1561                 if (!strcmp(service->uuid, pattern))
1562                         return service;
1563         }
1564
1565         return NULL;
1566 }
1567
1568 void gatt_unregister_service(DBusConnection *conn, GDBusProxy *proxy,
1569                                                 int argc, char *argv[])
1570 {
1571         struct service *service;
1572
1573         service = service_find(argv[1]);
1574         if (!service) {
1575                 bt_shell_printf("Failed to unregister service object\n");
1576                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1577         }
1578
1579         local_services = g_list_remove(local_services, service);
1580
1581         print_service(service, COLORED_DEL);
1582
1583         g_dbus_unregister_interface(service->conn, service->path,
1584                                                 SERVICE_INTERFACE);
1585
1586         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1587 }
1588
1589 static char *inc_find(struct service  *serv, char *path)
1590 {
1591         GList *lc;
1592
1593         for (lc = serv->inc; lc; lc =  g_list_next(lc)) {
1594                 char *incp = lc->data;
1595                 /* match object path */
1596                 if (!strcmp(incp, path))
1597                         return incp;
1598         }
1599
1600         return NULL;
1601 }
1602
1603 void gatt_register_include(DBusConnection *conn, GDBusProxy *proxy,
1604                                         int argc, char *argv[])
1605 {
1606         struct service *service, *inc_service;
1607         char *inc_path;
1608
1609         if (!local_services) {
1610                 bt_shell_printf("No service registered\n");
1611                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1612         }
1613
1614         service = g_list_last(local_services)->data;
1615
1616
1617         inc_service = service_find(argv[1]);
1618         if (!inc_service) {
1619                 bt_shell_printf("Failed to find  service object\n");
1620                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1621         }
1622
1623         inc_path = g_strdup(service->path);
1624
1625         inc_service->inc = g_list_append(inc_service->inc, inc_path);
1626
1627         print_service(inc_service, COLORED_NEW);
1628         print_inc_service(service, COLORED_NEW);
1629
1630         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1631 }
1632
1633 void gatt_unregister_include(DBusConnection *conn, GDBusProxy *proxy,
1634                                                 int argc, char *argv[])
1635 {
1636         struct service *ser_inc, *service;
1637         char *path = NULL;
1638
1639         service = service_find(argv[1]);
1640         if (!service) {
1641                 bt_shell_printf("Failed to unregister include service"
1642                                                         " object\n");
1643                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1644         }
1645
1646         ser_inc = service_find(argv[2]);
1647         if (!ser_inc) {
1648                 bt_shell_printf("Failed to find include service object\n");
1649                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
1650         }
1651
1652         path = inc_find(service, ser_inc->path);
1653         if (path) {
1654                 service->inc = g_list_remove(service->inc, path);
1655                 inc_unregister(path);
1656         }
1657
1658         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
1659 }
1660
1661 static gboolean chrc_get_handle(const GDBusPropertyTable *property,
1662                                         DBusMessageIter *iter, void *data)
1663 {
1664         struct chrc *chrc = data;
1665
1666         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &chrc->handle);
1667
1668         return TRUE;
1669 }
1670
1671 static void chrc_set_handle(const GDBusPropertyTable *property,
1672                         DBusMessageIter *value, GDBusPendingPropertySet id,
1673                         void *data)
1674 {
1675         struct chrc *chrc = data;
1676
1677         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_UINT16) {
1678                 g_dbus_pending_property_error(id, "org.bluez.InvalidArguments",
1679                                         "Invalid arguments in method call");
1680                 return;
1681         }
1682
1683         dbus_message_iter_get_basic(value, &chrc->handle);
1684
1685         print_chrc(chrc, COLORED_CHG);
1686
1687         g_dbus_pending_property_success(id);
1688 }
1689
1690 static gboolean chrc_get_uuid(const GDBusPropertyTable *property,
1691                                         DBusMessageIter *iter, void *data)
1692 {
1693         struct chrc *chrc = data;
1694
1695         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &chrc->uuid);
1696
1697         return TRUE;
1698 }
1699
1700 static gboolean chrc_get_service(const GDBusPropertyTable *property,
1701                                         DBusMessageIter *iter, void *data)
1702 {
1703         struct chrc *chrc = data;
1704
1705         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH,
1706                                                 &chrc->service->path);
1707
1708         return TRUE;
1709 }
1710
1711 static gboolean chrc_get_value(const GDBusPropertyTable *property,
1712                                         DBusMessageIter *iter, void *data)
1713 {
1714         struct chrc *chrc = data;
1715         DBusMessageIter array;
1716
1717         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "y", &array);
1718
1719         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
1720                                                 &chrc->value, chrc->value_len);
1721
1722         dbus_message_iter_close_container(iter, &array);
1723
1724         return TRUE;
1725 }
1726
1727 static gboolean chrc_get_notifying(const GDBusPropertyTable *property,
1728                                         DBusMessageIter *iter, void *data)
1729 {
1730         struct chrc *chrc = data;
1731         dbus_bool_t value;
1732
1733         value = chrc->notifying ? TRUE : FALSE;
1734
1735         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &value);
1736
1737         return TRUE;
1738 }
1739
1740 static gboolean chrc_get_flags(const GDBusPropertyTable *property,
1741                                         DBusMessageIter *iter, void *data)
1742 {
1743         struct chrc *chrc = data;
1744         int i;
1745         DBusMessageIter array;
1746
1747         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "s", &array);
1748
1749         for (i = 0; chrc->flags[i]; i++)
1750                 dbus_message_iter_append_basic(&array, DBUS_TYPE_STRING,
1751                                                         &chrc->flags[i]);
1752
1753         dbus_message_iter_close_container(iter, &array);
1754
1755         return TRUE;
1756 }
1757
1758 static gboolean chrc_get_write_acquired(const GDBusPropertyTable *property,
1759                                         DBusMessageIter *iter, void *data)
1760 {
1761         struct chrc *chrc = data;
1762         dbus_bool_t value;
1763
1764         value = chrc->write_io ? TRUE : FALSE;
1765
1766         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &value);
1767
1768         return TRUE;
1769 }
1770
1771 static gboolean chrc_write_acquired_exists(const GDBusPropertyTable *property,
1772                                                                 void *data)
1773 {
1774         struct chrc *chrc = data;
1775         int i;
1776
1777         if (chrc->proxy)
1778                 return FALSE;
1779
1780         for (i = 0; chrc->flags[i]; i++) {
1781                 if (!strcmp("write-without-response", chrc->flags[i]))
1782                         return TRUE;
1783         }
1784
1785         return FALSE;
1786 }
1787
1788 static gboolean chrc_get_notify_acquired(const GDBusPropertyTable *property,
1789                                         DBusMessageIter *iter, void *data)
1790 {
1791         struct chrc *chrc = data;
1792         dbus_bool_t value;
1793
1794         value = chrc->notify_io ? TRUE : FALSE;
1795
1796         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &value);
1797
1798         return TRUE;
1799 }
1800
1801 static gboolean chrc_notify_acquired_exists(const GDBusPropertyTable *property,
1802                                                                 void *data)
1803 {
1804         struct chrc *chrc = data;
1805         int i;
1806
1807         if (chrc->proxy)
1808                 return FALSE;
1809
1810         for (i = 0; chrc->flags[i]; i++) {
1811                 if (!strcmp("notify", chrc->flags[i]))
1812                         return TRUE;
1813         }
1814
1815         return FALSE;
1816 }
1817
1818 static const GDBusPropertyTable chrc_properties[] = {
1819         { "Handle", "q", chrc_get_handle, chrc_set_handle, NULL },
1820         { "UUID", "s", chrc_get_uuid, NULL, NULL },
1821         { "Service", "o", chrc_get_service, NULL, NULL },
1822         { "Value", "ay", chrc_get_value, NULL, NULL },
1823         { "Notifying", "b", chrc_get_notifying, NULL, NULL },
1824         { "Flags", "as", chrc_get_flags, NULL, NULL },
1825         { "WriteAcquired", "b", chrc_get_write_acquired, NULL,
1826                                         chrc_write_acquired_exists },
1827         { "NotifyAcquired", "b", chrc_get_notify_acquired, NULL,
1828                                         chrc_notify_acquired_exists },
1829         { }
1830 };
1831
1832 static const char *path_to_address(const char *path)
1833 {
1834         GDBusProxy *proxy;
1835         DBusMessageIter iter;
1836         const char *address = path;
1837
1838         proxy = bt_shell_get_env(path);
1839
1840         if (g_dbus_proxy_get_property(proxy, "Address", &iter))
1841                 dbus_message_iter_get_basic(&iter, &address);
1842
1843         return address;
1844 }
1845
1846 static int parse_options(DBusMessageIter *iter, uint16_t *offset, uint16_t *mtu,
1847                                                 char **device, char **link,
1848                                                 bool *prep_authorize)
1849 {
1850         DBusMessageIter dict;
1851
1852         if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
1853                 return -EINVAL;
1854
1855         dbus_message_iter_recurse(iter, &dict);
1856
1857         while (dbus_message_iter_get_arg_type(&dict) == DBUS_TYPE_DICT_ENTRY) {
1858                 const char *key;
1859                 DBusMessageIter value, entry;
1860                 int var;
1861
1862                 dbus_message_iter_recurse(&dict, &entry);
1863                 dbus_message_iter_get_basic(&entry, &key);
1864
1865                 dbus_message_iter_next(&entry);
1866                 dbus_message_iter_recurse(&entry, &value);
1867
1868                 var = dbus_message_iter_get_arg_type(&value);
1869                 if (strcasecmp(key, "offset") == 0) {
1870                         if (var != DBUS_TYPE_UINT16)
1871                                 return -EINVAL;
1872                         if (offset)
1873                                 dbus_message_iter_get_basic(&value, offset);
1874                 } else if (strcasecmp(key, "MTU") == 0) {
1875                         if (var != DBUS_TYPE_UINT16)
1876                                 return -EINVAL;
1877                         if (mtu)
1878                                 dbus_message_iter_get_basic(&value, mtu);
1879                 } else if (strcasecmp(key, "device") == 0) {
1880                         if (var != DBUS_TYPE_OBJECT_PATH)
1881                                 return -EINVAL;
1882                         if (device)
1883                                 dbus_message_iter_get_basic(&value, device);
1884                 } else if (strcasecmp(key, "link") == 0) {
1885                         if (var != DBUS_TYPE_STRING)
1886                                 return -EINVAL;
1887                         if (link)
1888                                 dbus_message_iter_get_basic(&value, link);
1889                 } else if (strcasecmp(key, "prepare-authorize") == 0) {
1890                         if (var != DBUS_TYPE_BOOLEAN)
1891                                 return -EINVAL;
1892                         if (prep_authorize) {
1893                                 int tmp;
1894
1895                                 dbus_message_iter_get_basic(&value, &tmp);
1896                                 *prep_authorize = !!tmp;
1897                         }
1898                 }
1899
1900                 dbus_message_iter_next(&dict);
1901         }
1902
1903         return 0;
1904 }
1905
1906 static DBusMessage *read_value(DBusMessage *msg, uint8_t *value,
1907                                                 uint16_t value_len)
1908 {
1909         DBusMessage *reply;
1910         DBusMessageIter iter, array;
1911
1912         reply = g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
1913
1914         dbus_message_iter_init_append(reply, &iter);
1915         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "y", &array);
1916         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
1917                                                 &value, value_len);
1918         dbus_message_iter_close_container(&iter, &array);
1919
1920         return reply;
1921 }
1922
1923 struct authorize_attribute_data {
1924         DBusConnection *conn;
1925         void *attribute;
1926         uint16_t offset;
1927 };
1928
1929 static void authorize_read_response(const char *input, void *user_data)
1930 {
1931         struct authorize_attribute_data *aad = user_data;
1932         struct chrc *chrc = aad->attribute;
1933         DBusMessage *reply;
1934         char *err;
1935
1936         if (!strcmp(input, "no")) {
1937                 err = "org.bluez.Error.NotAuthorized";
1938
1939                 goto error;
1940         }
1941
1942         if (aad->offset > chrc->value_len) {
1943                 err = "org.bluez.Error.InvalidOffset";
1944
1945                 goto error;
1946         }
1947
1948         reply = read_value(pending_message, &chrc->value[aad->offset],
1949                                                 chrc->value_len - aad->offset);
1950
1951         g_dbus_send_message(aad->conn, reply);
1952
1953         g_free(aad);
1954
1955         return;
1956
1957 error:
1958         g_dbus_send_error(aad->conn, pending_message, err, NULL);
1959         g_free(aad);
1960 }
1961
1962 static bool is_device_trusted(const char *path)
1963 {
1964         GDBusProxy *proxy;
1965         DBusMessageIter iter;
1966         bool trusted = false;
1967
1968         proxy = bt_shell_get_env(path);
1969
1970         if (g_dbus_proxy_get_property(proxy, "Trusted", &iter))
1971                 dbus_message_iter_get_basic(&iter, &trusted);
1972
1973         return trusted;
1974 }
1975
1976 struct read_attribute_data {
1977         DBusMessage *msg;
1978         uint16_t offset;
1979 };
1980
1981 static void proxy_read_reply(DBusMessage *message, void *user_data)
1982 {
1983         struct read_attribute_data *data = user_data;
1984         DBusConnection *conn = bt_shell_get_env("DBUS_CONNECTION");
1985         DBusError error;
1986         DBusMessageIter iter, array;
1987         DBusMessage *reply;
1988         uint8_t *value;
1989         int len;
1990
1991         dbus_error_init(&error);
1992
1993         if (dbus_set_error_from_message(&error, message) == TRUE) {
1994                 bt_shell_printf("Failed to read: %s\n", error.name);
1995                 dbus_error_free(&error);
1996                 g_dbus_send_error(conn, data->msg, error.name, "%s",
1997                                                         error.message);
1998                 goto done;
1999         }
2000
2001         dbus_message_iter_init(message, &iter);
2002
2003         if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY) {
2004                 bt_shell_printf("Invalid response to read\n");
2005                 g_dbus_send_error(conn, data->msg,
2006                                 "org.bluez.Error.InvalidArguments", NULL);
2007                 goto done;
2008         }
2009
2010         dbus_message_iter_recurse(&iter, &array);
2011         dbus_message_iter_get_fixed_array(&array, &value, &len);
2012
2013         if (len < 0) {
2014                 bt_shell_printf("Unable to parse value\n");
2015                 g_dbus_send_error(conn, data->msg,
2016                                 "org.bluez.Error.InvalidArguments", NULL);
2017         }
2018
2019         reply = read_value(data->msg, value, len);
2020
2021         g_dbus_send_message(conn, reply);
2022
2023 done:
2024         dbus_message_unref(data->msg);
2025         free(data);
2026 }
2027
2028 static void proxy_read_setup(DBusMessageIter *iter, void *user_data)
2029 {
2030         DBusMessageIter dict;
2031         struct read_attribute_data *data = user_data;
2032
2033         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
2034                                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
2035                                         DBUS_TYPE_STRING_AS_STRING
2036                                         DBUS_TYPE_VARIANT_AS_STRING
2037                                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
2038                                         &dict);
2039
2040         g_dbus_dict_append_entry(&dict, "offset", DBUS_TYPE_UINT16,
2041                                                 &data->offset);
2042
2043         dbus_message_iter_close_container(iter, &dict);
2044 }
2045
2046 static DBusMessage *proxy_read_value(struct GDBusProxy *proxy, DBusMessage *msg,
2047                                                         uint16_t offset)
2048 {
2049         struct read_attribute_data *data;
2050
2051         data = new0(struct read_attribute_data, 1);
2052         data->msg = dbus_message_ref(msg);
2053         data->offset = offset;
2054
2055         if (g_dbus_proxy_method_call(proxy, "ReadValue", proxy_read_setup,
2056                                         proxy_read_reply, data, NULL))
2057                 return NULL;
2058
2059         bt_shell_printf("Failed to read\n");
2060
2061         return g_dbus_create_error(msg, "org.bluez.Error.InvalidArguments",
2062                                                                 NULL);
2063 }
2064
2065 static DBusMessage *chrc_read_value(DBusConnection *conn, DBusMessage *msg,
2066                                                         void *user_data)
2067 {
2068         struct chrc *chrc = user_data;
2069         DBusMessageIter iter;
2070         uint16_t offset = 0;
2071         char *device, *link;
2072         char *str;
2073
2074         dbus_message_iter_init(msg, &iter);
2075
2076         if (parse_options(&iter, &offset, NULL, &device, &link, NULL))
2077                 return g_dbus_create_error(msg,
2078                                         "org.bluez.Error.InvalidArguments",
2079                                         NULL);
2080
2081         bt_shell_printf("[%s (%s)] ReadValue: %s offset %u link %s\n",
2082                         chrc->path, bt_uuidstr_to_str(chrc->uuid),
2083                         path_to_address(device), offset, link);
2084
2085         if (chrc->proxy) {
2086                 return proxy_read_value(chrc->proxy, msg, offset);
2087         }
2088
2089         if (!is_device_trusted(device) && chrc->authorization_req) {
2090                 struct authorize_attribute_data *aad;
2091
2092                 aad = g_new0(struct authorize_attribute_data, 1);
2093                 aad->conn = conn;
2094                 aad->attribute = chrc;
2095                 aad->offset = offset;
2096
2097                 str = g_strdup_printf("Authorize attribute(%s) read (yes/no):",
2098                                                                 chrc->path);
2099
2100                 bt_shell_prompt_input("gatt", str, authorize_read_response,
2101                                                                         aad);
2102                 g_free(str);
2103
2104                 pending_message = dbus_message_ref(msg);
2105
2106                 return NULL;
2107         }
2108
2109         if (offset > chrc->value_len)
2110                 return g_dbus_create_error(msg, "org.bluez.Error.InvalidOffset",
2111                                                                         NULL);
2112
2113         return read_value(msg, &chrc->value[offset], chrc->value_len - offset);
2114 }
2115
2116 static int parse_value_arg(DBusMessageIter *iter, uint8_t **value, int *len)
2117 {
2118         DBusMessageIter array;
2119
2120         if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY)
2121                 return -EINVAL;
2122
2123         dbus_message_iter_recurse(iter, &array);
2124         dbus_message_iter_get_fixed_array(&array, value, len);
2125
2126         return 0;
2127 }
2128
2129 static int write_value(size_t *dst_len, uint8_t **dst_value, uint8_t *src_val,
2130                         size_t src_len, uint16_t offset, uint16_t max_len)
2131 {
2132         if ((offset + src_len) > max_len)
2133                 return -EOVERFLOW;
2134
2135         if ((offset + src_len) != *dst_len) {
2136                 *dst_len = offset + src_len;
2137                 *dst_value = g_realloc(*dst_value, *dst_len);
2138         }
2139
2140         memcpy(*dst_value + offset, src_val, src_len);
2141
2142         return 0;
2143 }
2144
2145 static void authorize_write_response(const char *input, void *user_data)
2146 {
2147         struct authorize_attribute_data *aad = user_data;
2148         struct chrc *chrc = aad->attribute;
2149         bool prep_authorize = false;
2150         DBusMessageIter iter;
2151         DBusMessage *reply;
2152         int value_len;
2153         uint8_t *value;
2154         char *err;
2155
2156         dbus_message_iter_init(pending_message, &iter);
2157         if (parse_value_arg(&iter, &value, &value_len)) {
2158                 err = "org.bluez.Error.InvalidArguments";
2159
2160                 goto error;
2161         }
2162
2163         dbus_message_iter_next(&iter);
2164         if (parse_options(&iter, NULL, NULL, NULL, NULL, &prep_authorize)) {
2165                 err = "org.bluez.Error.InvalidArguments";
2166
2167                 goto error;
2168         }
2169
2170         if (!strcmp(input, "no")) {
2171                 err = "org.bluez.Error.NotAuthorized";
2172
2173                 goto error;
2174         }
2175
2176         if (aad->offset > chrc->value_len) {
2177                 err = "org.bluez.Error.InvalidOffset";
2178
2179                 goto error;
2180         }
2181
2182         /* Authorization check of prepare writes */
2183         if (prep_authorize) {
2184                 reply = g_dbus_create_reply(pending_message, DBUS_TYPE_INVALID);
2185                 g_dbus_send_message(aad->conn, reply);
2186                 g_free(aad);
2187
2188                 return;
2189         }
2190
2191         if (write_value(&chrc->value_len, &chrc->value, value, value_len,
2192                                         aad->offset, chrc->max_val_len)) {
2193                 err = "org.bluez.Error.InvalidValueLength";
2194
2195                 goto error;
2196         }
2197
2198         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) written",
2199                         chrc->path, bt_uuidstr_to_str(chrc->uuid));
2200
2201         g_dbus_emit_property_changed(aad->conn, chrc->path, CHRC_INTERFACE,
2202                                                                 "Value");
2203
2204         reply = g_dbus_create_reply(pending_message, DBUS_TYPE_INVALID);
2205         g_dbus_send_message(aad->conn, reply);
2206
2207         g_free(aad);
2208
2209         return;
2210
2211 error:
2212         g_dbus_send_error(aad->conn, pending_message, err, NULL);
2213         g_free(aad);
2214 }
2215
2216 static void proxy_write_reply(DBusMessage *message, void *user_data)
2217 {
2218         struct write_attribute_data *data = user_data;
2219         DBusConnection *conn = bt_shell_get_env("DBUS_CONNECTION");
2220         DBusError error;
2221
2222         dbus_error_init(&error);
2223
2224         if (dbus_set_error_from_message(&error, message)) {
2225                 bt_shell_printf("Failed to write: %s\n", error.name);
2226                 g_dbus_send_error(conn, data->msg, error.name, "%s",
2227                                                         error.message);
2228         } else
2229                 g_dbus_send_reply(conn, data->msg, DBUS_TYPE_INVALID);
2230
2231         dbus_message_unref(data->msg);
2232         free(data);
2233 }
2234
2235 static DBusMessage *proxy_write_value(struct GDBusProxy *proxy,
2236                                         DBusMessage *msg, uint8_t *value,
2237                                         int value_len, uint16_t offset)
2238 {
2239         struct write_attribute_data *data;
2240
2241
2242         data = new0(struct write_attribute_data, 1);
2243         data->msg = dbus_message_ref(msg);
2244         data->iov.iov_base = (void *) value;
2245         data->iov.iov_len = value_len;
2246         data->offset = offset;
2247
2248         if (g_dbus_proxy_method_call(proxy, "WriteValue", write_setup,
2249                                         proxy_write_reply, data, NULL))
2250                 return NULL;
2251
2252
2253         bt_shell_printf("Failed to write\n");
2254
2255         return g_dbus_create_error(msg, "org.bluez.Error.InvalidArguments",
2256                                                                 NULL);
2257 }
2258
2259 static DBusMessage *chrc_write_value(DBusConnection *conn, DBusMessage *msg,
2260                                                         void *user_data)
2261 {
2262         struct chrc *chrc = user_data;
2263         uint16_t offset = 0;
2264         bool prep_authorize = false;
2265         char *device = NULL, *link = NULL;
2266         DBusMessageIter iter;
2267         int value_len;
2268         uint8_t *value;
2269         char *str;
2270
2271         dbus_message_iter_init(msg, &iter);
2272
2273         if (parse_value_arg(&iter, &value, &value_len))
2274                 return g_dbus_create_error(msg,
2275                                 "org.bluez.Error.InvalidArguments", NULL);
2276
2277         dbus_message_iter_next(&iter);
2278         if (parse_options(&iter, &offset, NULL, &device, &link,
2279                                                 &prep_authorize))
2280                 return g_dbus_create_error(msg,
2281                                 "org.bluez.Error.InvalidArguments", NULL);
2282
2283         bt_shell_printf("[%s (%s)] WriteValue: %s offset %u link %s\n",
2284                         chrc->path, bt_uuidstr_to_str(chrc->uuid),
2285                         path_to_address(device), offset, link);
2286
2287         bt_shell_hexdump(value, value_len);
2288
2289         if (chrc->proxy)
2290                 return proxy_write_value(chrc->proxy, msg, value, value_len,
2291                                                                 offset);
2292
2293         if (!is_device_trusted(device) && chrc->authorization_req) {
2294                 struct authorize_attribute_data *aad;
2295
2296                 aad = g_new0(struct authorize_attribute_data, 1);
2297                 aad->conn = conn;
2298                 aad->attribute = chrc;
2299                 aad->offset = offset;
2300
2301                 str = g_strdup_printf("Authorize attribute(%s) write (yes/no):",
2302                                                                 chrc->path);
2303
2304                 bt_shell_prompt_input("gatt", str, authorize_write_response,
2305                                                                         aad);
2306                 g_free(str);
2307
2308                 pending_message = dbus_message_ref(msg);
2309
2310                 return NULL;
2311         }
2312
2313         if (offset > chrc->value_len)
2314                 return g_dbus_create_error(msg,
2315                                 "org.bluez.Error.InvalidOffset", NULL);
2316
2317
2318         /* Authorization check of prepare writes */
2319         if (prep_authorize)
2320                 return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2321
2322         if (write_value(&chrc->value_len, &chrc->value, value, value_len,
2323                                                 offset, chrc->max_val_len))
2324                 return g_dbus_create_error(msg,
2325                                 "org.bluez.Error.InvalidValueLength", NULL);
2326
2327         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) written",
2328                         chrc->path, bt_uuidstr_to_str(chrc->uuid));
2329
2330         g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE, "Value");
2331
2332         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2333 }
2334
2335 static DBusMessage *create_sock(struct chrc *chrc, DBusMessage *msg)
2336 {
2337         int fds[2];
2338         struct io *io;
2339         bool dir;
2340         DBusMessage *reply;
2341
2342         if (socketpair(AF_LOCAL, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC,
2343                                                                 0, fds) < 0)
2344                 return g_dbus_create_error(msg, "org.bluez.Error.Failed", "%s",
2345                                                         strerror(errno));
2346
2347         dir = dbus_message_has_member(msg, "AcquireWrite");
2348
2349         io = sock_io_new(fds[!dir], chrc);
2350         if (!io) {
2351                 close(fds[0]);
2352                 close(fds[1]);
2353                 return g_dbus_create_error(msg, "org.bluez.Error.Failed", "%s",
2354                                                         strerror(errno));
2355         }
2356
2357         reply = g_dbus_create_reply(msg, DBUS_TYPE_UNIX_FD, &fds[dir],
2358                                         DBUS_TYPE_UINT16, &chrc->mtu,
2359                                         DBUS_TYPE_INVALID);
2360
2361         close(fds[dir]);
2362
2363         if (dir)
2364                 chrc->write_io = io;
2365         else
2366                 chrc->notify_io = io;
2367
2368         bt_shell_printf("[" COLORED_CHG "] Attribute %s %s sock acquired\n",
2369                                         chrc->path, dir ? "Write" : "Notify");
2370
2371         return reply;
2372 }
2373
2374 static DBusMessage *chrc_acquire_write(DBusConnection *conn, DBusMessage *msg,
2375                                                         void *user_data)
2376 {
2377         struct chrc *chrc = user_data;
2378         DBusMessageIter iter;
2379         DBusMessage *reply;
2380         char *device = NULL, *link= NULL;
2381
2382         dbus_message_iter_init(msg, &iter);
2383
2384         if (chrc->write_io)
2385                 return g_dbus_create_error(msg,
2386                                         "org.bluez.Error.NotPermitted",
2387                                         NULL);
2388
2389         if (parse_options(&iter, NULL, &chrc->mtu, &device, &link, NULL))
2390                 return g_dbus_create_error(msg,
2391                                         "org.bluez.Error.InvalidArguments",
2392                                         NULL);
2393
2394         bt_shell_printf("AcquireWrite: %s link %s\n", path_to_address(device),
2395                                                                         link);
2396
2397         reply = create_sock(chrc, msg);
2398
2399         if (chrc->write_io)
2400                 g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE,
2401                                                         "WriteAcquired");
2402
2403         return reply;
2404 }
2405
2406 static DBusMessage *chrc_acquire_notify(DBusConnection *conn, DBusMessage *msg,
2407                                                         void *user_data)
2408 {
2409         struct chrc *chrc = user_data;
2410         DBusMessageIter iter;
2411         DBusMessage *reply;
2412         char *device = NULL, *link = NULL;
2413
2414         dbus_message_iter_init(msg, &iter);
2415
2416         if (chrc->notify_io)
2417                 return g_dbus_create_error(msg,
2418                                         "org.bluez.Error.NotPermitted",
2419                                         NULL);
2420
2421         if (parse_options(&iter, NULL, &chrc->mtu, &device, &link, NULL))
2422                 return g_dbus_create_error(msg,
2423                                         "org.bluez.Error.InvalidArguments",
2424                                         NULL);
2425
2426         bt_shell_printf("AcquireNotify: %s link %s\n", path_to_address(device),
2427                                                                         link);
2428
2429         reply = create_sock(chrc, msg);
2430
2431         if (chrc->notify_io)
2432                 g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE,
2433                                                         "NotifyAcquired");
2434
2435         return reply;
2436 }
2437
2438 struct notify_attribute_data {
2439         struct chrc *chrc;
2440         DBusMessage *msg;
2441         bool enable;
2442 };
2443
2444 static void proxy_notify_reply(DBusMessage *message, void *user_data)
2445 {
2446         struct notify_attribute_data *data = user_data;
2447         DBusConnection *conn = bt_shell_get_env("DBUS_CONNECTION");
2448         DBusError error;
2449
2450         dbus_error_init(&error);
2451
2452         if (dbus_set_error_from_message(&error, message) == TRUE) {
2453                 bt_shell_printf("Failed to %s: %s\n",
2454                                 data->enable ? "StartNotify" : "StopNotify",
2455                                 error.name);
2456                 dbus_error_free(&error);
2457                 g_dbus_send_error(conn, data->msg, error.name, "%s",
2458                                                         error.message);
2459                 goto done;
2460         }
2461
2462         g_dbus_send_reply(conn, data->msg, DBUS_TYPE_INVALID);
2463
2464         data->chrc->notifying = data->enable;
2465         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) "
2466                                 "notifications %s\n",
2467                                 data->chrc->path,
2468                                 bt_uuidstr_to_str(data->chrc->uuid),
2469                                 data->enable ? "enabled" : "disabled");
2470         g_dbus_emit_property_changed(conn, data->chrc->path, CHRC_INTERFACE,
2471                                                         "Notifying");
2472
2473 done:
2474         dbus_message_unref(data->msg);
2475         free(data);
2476 }
2477
2478 static DBusMessage *proxy_notify(struct chrc *chrc, DBusMessage *msg,
2479                                                         bool enable)
2480 {
2481         struct notify_attribute_data *data;
2482         const char *method;
2483
2484         if (enable == TRUE)
2485                 method = "StartNotify";
2486         else
2487                 method = "StopNotify";
2488
2489         data = new0(struct notify_attribute_data, 1);
2490         data->chrc = chrc;
2491         data->msg = dbus_message_ref(msg);
2492         data->enable = enable;
2493
2494         if (g_dbus_proxy_method_call(chrc->proxy, method, NULL,
2495                                         proxy_notify_reply, data, NULL))
2496                 return NULL;
2497
2498         return g_dbus_create_error(msg, "org.bluez.Error.InvalidArguments",
2499                                                                 NULL);
2500 }
2501
2502 static DBusMessage *chrc_start_notify(DBusConnection *conn, DBusMessage *msg,
2503                                                         void *user_data)
2504 {
2505         struct chrc *chrc = user_data;
2506
2507         if (chrc->notifying)
2508                 return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2509
2510         if (chrc->proxy)
2511                 return proxy_notify(chrc, msg, true);
2512
2513         chrc->notifying = true;
2514         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) notifications "
2515                         "enabled", chrc->path, bt_uuidstr_to_str(chrc->uuid));
2516         g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE,
2517                                                         "Notifying");
2518
2519         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2520 }
2521
2522 static DBusMessage *chrc_stop_notify(DBusConnection *conn, DBusMessage *msg,
2523                                                         void *user_data)
2524 {
2525         struct chrc *chrc = user_data;
2526
2527         if (!chrc->notifying)
2528                 return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2529
2530         if (chrc->proxy)
2531                 return proxy_notify(chrc, msg, false);
2532
2533         chrc->notifying = false;
2534         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) notifications "
2535                         "disabled", chrc->path, bt_uuidstr_to_str(chrc->uuid));
2536         g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE,
2537                                                         "Notifying");
2538
2539         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2540 }
2541
2542 static DBusMessage *chrc_confirm(DBusConnection *conn, DBusMessage *msg,
2543                                                         void *user_data)
2544 {
2545         struct chrc *chrc = user_data;
2546
2547         bt_shell_printf("Attribute %s (%s) indication confirm received",
2548                         chrc->path, bt_uuidstr_to_str(chrc->uuid));
2549
2550         return dbus_message_new_method_return(msg);
2551 }
2552
2553 static const GDBusMethodTable chrc_methods[] = {
2554         { GDBUS_ASYNC_METHOD("ReadValue", GDBUS_ARGS({ "options", "a{sv}" }),
2555                                         GDBUS_ARGS({ "value", "ay" }),
2556                                         chrc_read_value) },
2557         { GDBUS_ASYNC_METHOD("WriteValue", GDBUS_ARGS({ "value", "ay" },
2558                                                 { "options", "a{sv}" }),
2559                                         NULL, chrc_write_value) },
2560         { GDBUS_METHOD("AcquireWrite", GDBUS_ARGS({ "options", "a{sv}" }),
2561                                         NULL, chrc_acquire_write) },
2562         { GDBUS_METHOD("AcquireNotify", GDBUS_ARGS({ "options", "a{sv}" }),
2563                                         NULL, chrc_acquire_notify) },
2564         { GDBUS_ASYNC_METHOD("StartNotify", NULL, NULL, chrc_start_notify) },
2565         { GDBUS_METHOD("StopNotify", NULL, NULL, chrc_stop_notify) },
2566         { GDBUS_METHOD("Confirm", NULL, NULL, chrc_confirm) },
2567         { }
2568 };
2569
2570 static void chrc_set_value(const char *input, void *user_data)
2571 {
2572         struct chrc *chrc = user_data;
2573
2574         g_free(chrc->value);
2575
2576         chrc->value = str2bytearray((char *) input, &chrc->value_len);
2577
2578         if (!chrc->value) {
2579                 print_chrc(chrc, COLORED_DEL);
2580                 chrc_unregister(chrc);
2581         }
2582
2583         chrc->max_val_len = chrc->value_len;
2584 }
2585
2586 static gboolean attr_authorization_flag_exists(char **flags)
2587 {
2588         int i;
2589
2590         for (i = 0; flags[i]; i++) {
2591                 if (!strcmp("authorize", flags[i]))
2592                         return TRUE;
2593         }
2594
2595         return FALSE;
2596 }
2597
2598 void gatt_register_chrc(DBusConnection *conn, GDBusProxy *proxy,
2599                                         int argc, char *argv[])
2600 {
2601         struct service *service;
2602         struct chrc *chrc;
2603
2604         if (!local_services) {
2605                 bt_shell_printf("No service registered\n");
2606                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2607         }
2608
2609         service = g_list_last(local_services)->data;
2610
2611         chrc = g_new0(struct chrc, 1);
2612         chrc->service = service;
2613         chrc->uuid = g_strdup(argv[1]);
2614         chrc->path = g_strdup_printf("%s/chrc%u", service->path,
2615                                         g_list_length(service->chrcs));
2616         chrc->flags = g_strsplit(argv[2], ",", -1);
2617         chrc->authorization_req = attr_authorization_flag_exists(chrc->flags);
2618
2619         if (argc > 3) {
2620                 chrc->handle = parse_handle(argv[3]);
2621                 if (!chrc->handle)
2622                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
2623         }
2624
2625         if (g_dbus_register_interface(conn, chrc->path, CHRC_INTERFACE,
2626                                         chrc_methods, NULL, chrc_properties,
2627                                         chrc, chrc_free) == FALSE) {
2628                 bt_shell_printf("Failed to register characteristic object\n");
2629                 chrc_free(chrc);
2630                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2631         }
2632
2633         service->chrcs = g_list_append(service->chrcs, chrc);
2634
2635         print_chrc(chrc, COLORED_NEW);
2636
2637         bt_shell_prompt_input(chrc->path, "Enter value:", chrc_set_value, chrc);
2638
2639         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
2640 }
2641
2642 static struct chrc *chrc_find(const char *pattern)
2643 {
2644         GList *l, *lc;
2645         struct service *service;
2646         struct chrc *chrc;
2647
2648         for (l = local_services; l; l = g_list_next(l)) {
2649                 service = l->data;
2650
2651                 for (lc = service->chrcs; lc; lc =  g_list_next(lc)) {
2652                         chrc = lc->data;
2653
2654                         /* match object path */
2655                         if (!strcmp(chrc->path, pattern))
2656                                 return chrc;
2657
2658                         /* match UUID */
2659                         if (!strcmp(chrc->uuid, pattern))
2660                                 return chrc;
2661                 }
2662         }
2663
2664         return NULL;
2665 }
2666
2667 void gatt_unregister_chrc(DBusConnection *conn, GDBusProxy *proxy,
2668                                                 int argc, char *argv[])
2669 {
2670         struct chrc *chrc;
2671
2672         chrc = chrc_find(argv[1]);
2673         if (!chrc) {
2674                 bt_shell_printf("Failed to unregister characteristic object\n");
2675                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2676         }
2677
2678         chrc->service->chrcs = g_list_remove(chrc->service->chrcs, chrc);
2679
2680         chrc_unregister(chrc);
2681
2682         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
2683 }
2684
2685 static DBusMessage *desc_read_value(DBusConnection *conn, DBusMessage *msg,
2686                                                         void *user_data)
2687 {
2688         struct desc *desc = user_data;
2689         DBusMessageIter iter;
2690         uint16_t offset = 0;
2691         char *device = NULL, *link = NULL;
2692
2693         dbus_message_iter_init(msg, &iter);
2694
2695         if (parse_options(&iter, &offset, NULL, &device, &link, NULL))
2696                 return g_dbus_create_error(msg,
2697                                         "org.bluez.Error.InvalidArguments",
2698                                         NULL);
2699
2700         bt_shell_printf("[%s (%s)] ReadValue: %s offset %u link %s\n",
2701                         desc->path, bt_uuidstr_to_str(desc->uuid),
2702                         path_to_address(device), offset, link);
2703
2704         if (offset > desc->value_len)
2705                 return g_dbus_create_error(msg, "org.bluez.Error.InvalidOffset",
2706                                                                         NULL);
2707
2708         return read_value(msg, &desc->value[offset], desc->value_len - offset);
2709 }
2710
2711 static DBusMessage *desc_write_value(DBusConnection *conn, DBusMessage *msg,
2712                                                         void *user_data)
2713 {
2714         struct desc *desc = user_data;
2715         DBusMessageIter iter;
2716         uint16_t offset = 0;
2717         char *device = NULL, *link = NULL;
2718         int value_len;
2719         uint8_t *value;
2720
2721         dbus_message_iter_init(msg, &iter);
2722
2723         if (parse_value_arg(&iter, &value, &value_len))
2724                 return g_dbus_create_error(msg,
2725                                 "org.bluez.Error.InvalidArguments", NULL);
2726
2727         dbus_message_iter_next(&iter);
2728         if (parse_options(&iter, &offset, NULL, &device, &link, NULL))
2729                 return g_dbus_create_error(msg,
2730                                 "org.bluez.Error.InvalidArguments", NULL);
2731
2732         if (offset > desc->value_len)
2733                 return g_dbus_create_error(msg,
2734                                 "org.bluez.Error.InvalidOffset", NULL);
2735
2736         if (write_value(&desc->value_len, &desc->value, value,
2737                                         value_len, offset, desc->max_val_len))
2738                 return g_dbus_create_error(msg,
2739                                 "org.bluez.Error.InvalidValueLength", NULL);
2740
2741         bt_shell_printf("[%s (%s)] WriteValue: %s offset %u link %s\n",
2742                         desc->path, bt_uuidstr_to_str(desc->uuid),
2743                         path_to_address(device), offset, link);
2744
2745         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) written",
2746                         desc->path, bt_uuidstr_to_str(desc->uuid));
2747
2748         g_dbus_emit_property_changed(conn, desc->path, CHRC_INTERFACE, "Value");
2749
2750         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
2751 }
2752
2753 static const GDBusMethodTable desc_methods[] = {
2754         { GDBUS_ASYNC_METHOD("ReadValue", GDBUS_ARGS({ "options", "a{sv}" }),
2755                                         GDBUS_ARGS({ "value", "ay" }),
2756                                         desc_read_value) },
2757         { GDBUS_ASYNC_METHOD("WriteValue", GDBUS_ARGS({ "value", "ay" },
2758                                                 { "options", "a{sv}" }),
2759                                         NULL, desc_write_value) },
2760         { }
2761 };
2762
2763 static gboolean desc_get_handle(const GDBusPropertyTable *property,
2764                                         DBusMessageIter *iter, void *data)
2765 {
2766         struct desc *desc = data;
2767
2768         dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT16, &desc->handle);
2769
2770         return TRUE;
2771 }
2772
2773 static void desc_set_handle(const GDBusPropertyTable *property,
2774                         DBusMessageIter *value, GDBusPendingPropertySet id,
2775                         void *data)
2776 {
2777         struct desc *desc = data;
2778
2779         if (dbus_message_iter_get_arg_type(value) != DBUS_TYPE_UINT16) {
2780                 g_dbus_pending_property_error(id, "org.bluez.InvalidArguments",
2781                                         "Invalid arguments in method call");
2782                 return;
2783         }
2784
2785         dbus_message_iter_get_basic(value, &desc->handle);
2786
2787         print_desc(desc, COLORED_CHG);
2788
2789         g_dbus_pending_property_success(id);
2790 }
2791
2792 static gboolean desc_get_uuid(const GDBusPropertyTable *property,
2793                                         DBusMessageIter *iter, void *data)
2794 {
2795         struct desc *desc = data;
2796
2797         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &desc->uuid);
2798
2799         return TRUE;
2800 }
2801
2802 static gboolean desc_get_chrc(const GDBusPropertyTable *property,
2803                                         DBusMessageIter *iter, void *data)
2804 {
2805         struct desc *desc = data;
2806
2807         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH,
2808                                                 &desc->chrc->path);
2809
2810         return TRUE;
2811 }
2812
2813 static gboolean desc_get_value(const GDBusPropertyTable *property,
2814                                         DBusMessageIter *iter, void *data)
2815 {
2816         struct desc *desc = data;
2817         DBusMessageIter array;
2818
2819         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "y", &array);
2820
2821         if (desc->value)
2822                 dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE,
2823                                                         &desc->value,
2824                                                         desc->value_len);
2825
2826         dbus_message_iter_close_container(iter, &array);
2827
2828         return TRUE;
2829 }
2830
2831 static gboolean desc_get_flags(const GDBusPropertyTable *property,
2832                                         DBusMessageIter *iter, void *data)
2833 {
2834         struct desc *desc = data;
2835         int i;
2836         DBusMessageIter array;
2837
2838         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "s", &array);
2839
2840         for (i = 0; desc->flags[i]; i++)
2841                 dbus_message_iter_append_basic(&array, DBUS_TYPE_STRING,
2842                                                         &desc->flags[i]);
2843
2844         dbus_message_iter_close_container(iter, &array);
2845
2846         return TRUE;
2847 }
2848
2849 static const GDBusPropertyTable desc_properties[] = {
2850         { "Handle", "q", desc_get_handle, desc_set_handle, NULL },
2851         { "UUID", "s", desc_get_uuid, NULL, NULL },
2852         { "Characteristic", "o", desc_get_chrc, NULL, NULL },
2853         { "Value", "ay", desc_get_value, NULL, NULL },
2854         { "Flags", "as", desc_get_flags, NULL, NULL },
2855         { }
2856 };
2857
2858 static void desc_set_value(const char *input, void *user_data)
2859 {
2860         struct desc *desc = user_data;
2861
2862         g_free(desc->value);
2863
2864         desc->value = str2bytearray((char *) input, &desc->value_len);
2865
2866         if (!desc->value) {
2867                 print_desc(desc, COLORED_DEL);
2868                 desc_unregister(desc);
2869         }
2870
2871         desc->max_val_len = desc->value_len;
2872 }
2873
2874 void gatt_register_desc(DBusConnection *conn, GDBusProxy *proxy,
2875                                                 int argc, char *argv[])
2876 {
2877         struct service *service;
2878         struct desc *desc;
2879
2880         if (!local_services) {
2881                 bt_shell_printf("No service registered\n");
2882                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2883         }
2884
2885         service = g_list_last(local_services)->data;
2886
2887         if (!service->chrcs) {
2888                 bt_shell_printf("No characteristic registered\n");
2889                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2890         }
2891
2892         desc = g_new0(struct desc, 1);
2893         desc->chrc = g_list_last(service->chrcs)->data;
2894         desc->uuid = g_strdup(argv[1]);
2895         desc->path = g_strdup_printf("%s/desc%u", desc->chrc->path,
2896                                         g_list_length(desc->chrc->descs));
2897         desc->flags = g_strsplit(argv[2], ",", -1);
2898
2899         if (argc > 3) {
2900                 desc->handle = parse_handle(argv[3]);
2901                 if (!desc->handle)
2902                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
2903         }
2904
2905         if (g_dbus_register_interface(conn, desc->path, DESC_INTERFACE,
2906                                         desc_methods, NULL, desc_properties,
2907                                         desc, desc_free) == FALSE) {
2908                 bt_shell_printf("Failed to register descriptor object\n");
2909                 desc_free(desc);
2910                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2911         }
2912
2913         desc->chrc->descs = g_list_append(desc->chrc->descs, desc);
2914
2915         print_desc(desc, COLORED_NEW);
2916
2917         bt_shell_prompt_input(desc->path, "Enter value:", desc_set_value, desc);
2918
2919         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
2920 }
2921
2922 static struct desc *desc_find(const char *pattern)
2923 {
2924         GList *l, *lc, *ld;
2925         struct service *service;
2926         struct chrc *chrc;
2927         struct desc *desc;
2928
2929         for (l = local_services; l; l = g_list_next(l)) {
2930                 service = l->data;
2931
2932                 for (lc = service->chrcs; lc; lc = g_list_next(lc)) {
2933                         chrc = lc->data;
2934
2935                         for (ld = chrc->descs; ld; ld = g_list_next(ld)) {
2936                                 desc = ld->data;
2937
2938                                 /* match object path */
2939                                 if (!strcmp(desc->path, pattern))
2940                                         return desc;
2941
2942                                 /* match UUID */
2943                                 if (!strcmp(desc->uuid, pattern))
2944                                         return desc;
2945                         }
2946                 }
2947         }
2948
2949         return NULL;
2950 }
2951
2952 void gatt_unregister_desc(DBusConnection *conn, GDBusProxy *proxy,
2953                                                 int argc, char *argv[])
2954 {
2955         struct desc *desc;
2956
2957         desc = desc_find(argv[1]);
2958         if (!desc) {
2959                 bt_shell_printf("Failed to unregister descriptor object\n");
2960                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
2961         }
2962
2963         desc->chrc->descs = g_list_remove(desc->chrc->descs, desc);
2964
2965         desc_unregister(desc);
2966
2967         return bt_shell_noninteractive_quit(EXIT_SUCCESS);
2968 }
2969
2970 static GDBusProxy *select_service(GDBusProxy *proxy)
2971 {
2972         GList *l;
2973
2974         for (l = services; l; l = g_list_next(l)) {
2975                 GDBusProxy *p = l->data;
2976
2977                 if (proxy == p || g_str_has_prefix(g_dbus_proxy_get_path(proxy),
2978                                                 g_dbus_proxy_get_path(p)))
2979                         return p;
2980         }
2981
2982         return NULL;
2983 }
2984
2985 static void proxy_property_changed(GDBusProxy *proxy, const char *name,
2986                                         DBusMessageIter *iter, void *user_data)
2987 {
2988         DBusConnection *conn = bt_shell_get_env("DBUS_CONNECTION");
2989         struct chrc *chrc = user_data;
2990
2991         bt_shell_printf("[" COLORED_CHG "] Attribute %s (%s) %s:\n",
2992                         chrc->path, bt_uuidstr_to_str(chrc->uuid), name);
2993
2994         if (!strcmp(name, "Value")) {
2995                 DBusMessageIter array;
2996                 uint8_t *value;
2997                 int len;
2998
2999                 if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_ARRAY) {
3000                         dbus_message_iter_recurse(iter, &array);
3001                         dbus_message_iter_get_fixed_array(&array, &value, &len);
3002                         write_value(&chrc->value_len, &chrc->value, value, len,
3003                                         0, chrc->max_val_len);
3004                         bt_shell_hexdump(value, len);
3005                 }
3006         }
3007
3008         g_dbus_emit_property_changed(conn, chrc->path, CHRC_INTERFACE, name);
3009 }
3010
3011 static void clone_chrc(struct GDBusProxy *proxy)
3012 {
3013         struct service *service;
3014         struct chrc *chrc;
3015         DBusMessageIter iter;
3016         DBusMessageIter array;
3017         const char *uuid;
3018         char *flags[17];
3019         int i;
3020
3021         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
3022                 return;
3023
3024         dbus_message_iter_get_basic(&iter, &uuid);
3025
3026         if (g_dbus_proxy_get_property(proxy, "Flags", &iter) == FALSE)
3027                 return;
3028
3029         dbus_message_iter_recurse(&iter, &array);
3030
3031         for (i = 0; dbus_message_iter_get_arg_type(&array) == DBUS_TYPE_STRING;
3032                                                                         i++) {
3033                 dbus_message_iter_get_basic(&array, &flags[i]);
3034                 dbus_message_iter_next(&array);
3035         }
3036
3037         flags[i] = NULL;
3038
3039         service = g_list_last(local_services)->data;
3040
3041         chrc = g_new0(struct chrc, 1);
3042         chrc->service = service;
3043         chrc->proxy = proxy;
3044         chrc->uuid = g_strdup(uuid);
3045         chrc->path = g_strdup_printf("%s/chrc%u", service->path,
3046                                         g_list_length(service->chrcs));
3047         chrc->flags = g_strdupv(flags);
3048
3049         if (g_dbus_register_interface(service->conn, chrc->path, CHRC_INTERFACE,
3050                                         chrc_methods, NULL, chrc_properties,
3051                                         chrc, chrc_free) == FALSE) {
3052                 bt_shell_printf("Failed to register characteristic object\n");
3053                 chrc_free(chrc);
3054                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
3055         }
3056
3057         g_dbus_proxy_set_property_watch(proxy, proxy_property_changed, chrc);
3058
3059         service->chrcs = g_list_append(service->chrcs, chrc);
3060
3061         print_chrc(chrc, COLORED_NEW);
3062 }
3063
3064 static void clone_chrcs(struct GDBusProxy *proxy)
3065 {
3066         GList *l;
3067
3068         for (l = characteristics; l; l = g_list_next(l)) {
3069                 GDBusProxy *p = l->data;
3070
3071                 if (g_str_has_prefix(g_dbus_proxy_get_path(p),
3072                                                 g_dbus_proxy_get_path(proxy)))
3073                         clone_chrc(p);
3074         }
3075 }
3076
3077 static void clone_service(struct GDBusProxy *proxy)
3078 {
3079         struct service *service;
3080         DBusMessageIter iter;
3081         const char *uuid;
3082         dbus_bool_t primary;
3083
3084         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
3085                 return;
3086
3087         dbus_message_iter_get_basic(&iter, &uuid);
3088
3089         if (g_dbus_proxy_get_property(proxy, "Primary", &iter) == FALSE)
3090                 return;
3091
3092         dbus_message_iter_get_basic(&iter, &primary);
3093
3094         if (!strcmp(uuid, "00001800-0000-1000-8000-00805f9b34fb") ||
3095                         !strcmp(uuid, "00001801-0000-1000-8000-00805f9b34fb"))
3096                 return;
3097
3098         service = g_new0(struct service, 1);
3099         service->conn = bt_shell_get_env("DBUS_CONNECTION");
3100         service->proxy = proxy;
3101         service->path = g_strdup_printf("%s/service%u", APP_PATH,
3102                                         g_list_length(local_services));
3103         service->uuid = g_strdup(uuid);
3104         service->primary = primary;
3105
3106         if (g_dbus_register_interface(service->conn, service->path,
3107                                         SERVICE_INTERFACE, NULL, NULL,
3108                                         service_properties, service,
3109                                         service_free) == FALSE) {
3110                 bt_shell_printf("Failed to register service object\n");
3111                 service_free(service);
3112                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
3113         }
3114
3115         print_service(service, COLORED_NEW);
3116
3117         local_services = g_list_append(local_services, service);
3118
3119         clone_chrcs(proxy);
3120 }
3121
3122 static void clone_device(struct GDBusProxy *proxy)
3123 {
3124         GList *l;
3125
3126         for (l = services; l; l = g_list_next(l)) {
3127                 struct GDBusProxy *p = l->data;
3128
3129                 if (g_str_has_prefix(g_dbus_proxy_get_path(p),
3130                                                 g_dbus_proxy_get_path(proxy)))
3131                         clone_service(p);
3132         }
3133 }
3134
3135 static void service_clone(const char *input, void *user_data)
3136 {
3137         struct GDBusProxy *proxy = user_data;
3138
3139         if (!strcmp(input, "yes"))
3140                 return clone_service(proxy);
3141         else if (!strcmp(input, "no"))
3142                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
3143         else if (!strcmp(input, "all"))
3144                 return clone_device(proxy);
3145
3146         bt_shell_printf("Invalid option: %s\n", input);
3147
3148         return bt_shell_noninteractive_quit(EXIT_FAILURE);
3149 }
3150
3151 static void device_clone(const char *input, void *user_data)
3152 {
3153         struct GDBusProxy *proxy = user_data;
3154
3155         if (!strcmp(input, "yes"))
3156                 return clone_device(proxy);
3157         else if (!strcmp(input, "no"))
3158                 return bt_shell_noninteractive_quit(EXIT_FAILURE);
3159
3160         bt_shell_printf("Invalid option: %s\n", input);
3161
3162         return bt_shell_noninteractive_quit(EXIT_FAILURE);
3163 }
3164
3165 static const char *proxy_get_name(struct GDBusProxy *proxy)
3166 {
3167         DBusMessageIter iter;
3168         const char *uuid;
3169         const char *str;
3170
3171         if (g_dbus_proxy_get_property(proxy, "UUID", &iter) == FALSE)
3172                 return NULL;
3173
3174         dbus_message_iter_get_basic(&iter, &uuid);
3175
3176         str = bt_uuidstr_to_str(uuid);
3177
3178         return str ? str : uuid;
3179 }
3180
3181 static const char *proxy_get_alias(struct GDBusProxy *proxy)
3182 {
3183         DBusMessageIter iter;
3184         const char *alias;
3185
3186         if (g_dbus_proxy_get_property(proxy, "Alias", &iter) == FALSE)
3187                 return NULL;
3188
3189         dbus_message_iter_get_basic(&iter, &alias);
3190
3191         return alias;
3192 }
3193
3194 void gatt_clone_attribute(GDBusProxy *proxy, int argc, char *argv[])
3195 {
3196         GDBusProxy *service = NULL;
3197
3198         if (argc > 1) {
3199                 proxy = gatt_select_attribute(proxy, argv[1]);
3200                 if (!proxy) {
3201                         bt_shell_printf("Unable to find attribute %s\n",
3202                                                                 argv[1]);
3203                         return bt_shell_noninteractive_quit(EXIT_FAILURE);
3204                 }
3205         }
3206
3207         if (!strcmp(g_dbus_proxy_get_interface(proxy), DEVICE_INTERFACE)) {
3208                 bt_shell_prompt_input(proxy_get_alias(proxy),
3209                                         "Clone (yes/no):",
3210                                         device_clone, proxy);
3211         }
3212
3213         /* Only clone services */
3214         service = select_service(proxy);
3215         if (service) {
3216                 bt_shell_prompt_input(proxy_get_name(proxy),
3217                                         "Clone (yes/no/all):",
3218                                         service_clone, service);
3219                 return;
3220         }
3221
3222         return bt_shell_noninteractive_quit(EXIT_FAILURE);
3223 }