Upgrade bluez5_37 :Merge the code from private
[platform/upstream/bluez.git] / attrib / interactive.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2011  Nokia Corporation
6  *
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <signal.h>
35 #include <sys/signalfd.h>
36 #include <glib.h>
37
38 #include <readline/readline.h>
39 #include <readline/history.h>
40
41 #include "lib/bluetooth.h"
42 #include "lib/sdp.h"
43 #include "lib/uuid.h"
44
45 #include "src/shared/util.h"
46 #include "btio/btio.h"
47 #include "att.h"
48 #include "gattrib.h"
49 #include "gatt.h"
50 #include "gatttool.h"
51 #include "client/display.h"
52
53 static GIOChannel *iochannel = NULL;
54 static GAttrib *attrib = NULL;
55 static GMainLoop *event_loop;
56 static GString *prompt;
57
58 static char *opt_src = NULL;
59 static char *opt_dst = NULL;
60 static char *opt_dst_type = NULL;
61 static char *opt_sec_level = NULL;
62 static int opt_psm = 0;
63 static int opt_mtu = 0;
64 static int start;
65 static int end;
66
67 static void cmd_help(int argcp, char **argvp);
68
69 static enum state {
70         STATE_DISCONNECTED,
71         STATE_CONNECTING,
72         STATE_CONNECTED
73 } conn_state;
74
75 #define error(fmt, arg...) \
76         rl_printf(COLOR_RED "Error: " COLOR_OFF fmt, ## arg)
77
78 #define failed(fmt, arg...) \
79         rl_printf(COLOR_RED "Command Failed: " COLOR_OFF fmt, ## arg)
80
81 static char *get_prompt(void)
82 {
83         if (conn_state == STATE_CONNECTED)
84                 g_string_assign(prompt, COLOR_BLUE);
85         else
86                 g_string_assign(prompt, "");
87
88         if (opt_dst)
89                 g_string_append_printf(prompt, "[%17s]", opt_dst);
90         else
91                 g_string_append_printf(prompt, "[%17s]", "");
92
93         if (conn_state == STATE_CONNECTED)
94                 g_string_append(prompt, COLOR_OFF);
95
96         if (opt_psm)
97                 g_string_append(prompt, "[BR]");
98         else
99                 g_string_append(prompt, "[LE]");
100
101         g_string_append(prompt, "> ");
102
103         return prompt->str;
104 }
105
106
107 static void set_state(enum state st)
108 {
109         conn_state = st;
110         rl_set_prompt(get_prompt());
111 }
112
113 static void events_handler(const uint8_t *pdu, uint16_t len, gpointer user_data)
114 {
115         uint8_t *opdu;
116         uint16_t handle, i, olen;
117         size_t plen;
118         GString *s;
119
120         handle = get_le16(&pdu[1]);
121
122         switch (pdu[0]) {
123         case ATT_OP_HANDLE_NOTIFY:
124                 s = g_string_new(NULL);
125                 g_string_printf(s, "Notification handle = 0x%04x value: ",
126                                                                         handle);
127                 break;
128         case ATT_OP_HANDLE_IND:
129                 s = g_string_new(NULL);
130                 g_string_printf(s, "Indication   handle = 0x%04x value: ",
131                                                                         handle);
132                 break;
133         default:
134                 error("Invalid opcode\n");
135                 return;
136         }
137
138         for (i = 3; i < len; i++)
139                 g_string_append_printf(s, "%02x ", pdu[i]);
140
141         rl_printf("%s\n", s->str);
142         g_string_free(s, TRUE);
143
144         if (pdu[0] == ATT_OP_HANDLE_NOTIFY)
145                 return;
146
147         opdu = g_attrib_get_buffer(attrib, &plen);
148         olen = enc_confirmation(opdu, plen);
149
150         if (olen > 0)
151                 g_attrib_send(attrib, 0, opdu, olen, NULL, NULL, NULL);
152 }
153
154 static void connect_cb(GIOChannel *io, GError *err, gpointer user_data)
155 {
156         uint16_t mtu;
157         uint16_t cid;
158
159         if (err) {
160                 set_state(STATE_DISCONNECTED);
161                 error("%s\n", err->message);
162                 return;
163         }
164
165         bt_io_get(io, &err, BT_IO_OPT_IMTU, &mtu,
166                                 BT_IO_OPT_CID, &cid, BT_IO_OPT_INVALID);
167
168         if (err) {
169                 g_printerr("Can't detect MTU, using default: %s", err->message);
170                 g_error_free(err);
171                 mtu = ATT_DEFAULT_LE_MTU;
172         }
173
174         if (cid == ATT_CID)
175                 mtu = ATT_DEFAULT_LE_MTU;
176
177         attrib = g_attrib_new(iochannel, mtu, false);
178         g_attrib_register(attrib, ATT_OP_HANDLE_NOTIFY, GATTRIB_ALL_HANDLES,
179                                                 events_handler, attrib, NULL);
180         g_attrib_register(attrib, ATT_OP_HANDLE_IND, GATTRIB_ALL_HANDLES,
181                                                 events_handler, attrib, NULL);
182         set_state(STATE_CONNECTED);
183         rl_printf("Connection successful\n");
184 }
185
186 static void disconnect_io()
187 {
188         if (conn_state == STATE_DISCONNECTED)
189                 return;
190
191         g_attrib_unref(attrib);
192         attrib = NULL;
193         opt_mtu = 0;
194
195         g_io_channel_shutdown(iochannel, FALSE, NULL);
196         g_io_channel_unref(iochannel);
197         iochannel = NULL;
198
199         set_state(STATE_DISCONNECTED);
200 }
201
202 static void primary_all_cb(uint8_t status, GSList *services, void *user_data)
203 {
204         GSList *l;
205
206         if (status) {
207                 error("Discover all primary services failed: %s\n",
208                                                 att_ecode2str(status));
209                 return;
210         }
211
212         if (services == NULL) {
213                 error("No primary service found\n");
214                 return;
215         }
216
217         for (l = services; l; l = l->next) {
218                 struct gatt_primary *prim = l->data;
219                 rl_printf("attr handle: 0x%04x, end grp handle: 0x%04x uuid: %s\n",
220                                 prim->range.start, prim->range.end, prim->uuid);
221         }
222 }
223
224 static void primary_by_uuid_cb(uint8_t status, GSList *ranges, void *user_data)
225 {
226         GSList *l;
227
228         if (status) {
229                 error("Discover primary services by UUID failed: %s\n",
230                                                         att_ecode2str(status));
231                 return;
232         }
233
234         if (ranges == NULL) {
235                 error("No service UUID found\n");
236                 return;
237         }
238
239         for (l = ranges; l; l = l->next) {
240                 struct att_range *range = l->data;
241                 rl_printf("Starting handle: 0x%04x Ending handle: 0x%04x\n",
242                                                 range->start, range->end);
243         }
244 }
245
246 static void included_cb(uint8_t status, GSList *includes, void *user_data)
247 {
248         GSList *l;
249
250         if (status) {
251                 error("Find included services failed: %s\n",
252                                                         att_ecode2str(status));
253                 return;
254         }
255
256         if (includes == NULL) {
257                 rl_printf("No included services found for this range\n");
258                 return;
259         }
260
261         for (l = includes; l; l = l->next) {
262                 struct gatt_included *incl = l->data;
263                 rl_printf("handle: 0x%04x, start handle: 0x%04x, "
264                                         "end handle: 0x%04x uuid: %s\n",
265                                         incl->handle, incl->range.start,
266                                         incl->range.end, incl->uuid);
267         }
268 }
269
270 static void char_cb(uint8_t status, GSList *characteristics, void *user_data)
271 {
272         GSList *l;
273
274         if (status) {
275                 error("Discover all characteristics failed: %s\n",
276                                                         att_ecode2str(status));
277                 return;
278         }
279
280         for (l = characteristics; l; l = l->next) {
281                 struct gatt_char *chars = l->data;
282
283                 rl_printf("handle: 0x%04x, char properties: 0x%02x, char value "
284                                 "handle: 0x%04x, uuid: %s\n", chars->handle,
285                                 chars->properties, chars->value_handle,
286                                 chars->uuid);
287         }
288 }
289
290 static void char_desc_cb(uint8_t status, GSList *descriptors, void *user_data)
291 {
292         GSList *l;
293
294         if (status) {
295                 error("Discover descriptors failed: %s\n",
296                                                         att_ecode2str(status));
297                 return;
298         }
299
300         for (l = descriptors; l; l = l->next) {
301                 struct gatt_desc *desc = l->data;
302
303                 rl_printf("handle: 0x%04x, uuid: %s\n", desc->handle,
304                                                                 desc->uuid);
305         }
306 }
307
308 static void char_read_cb(guint8 status, const guint8 *pdu, guint16 plen,
309                                                         gpointer user_data)
310 {
311         uint8_t value[plen];
312         ssize_t vlen;
313         int i;
314         GString *s;
315
316         if (status != 0) {
317                 error("Characteristic value/descriptor read failed: %s\n",
318                                                         att_ecode2str(status));
319                 return;
320         }
321
322         vlen = dec_read_resp(pdu, plen, value, sizeof(value));
323         if (vlen < 0) {
324                 error("Protocol error\n");
325                 return;
326         }
327
328         s = g_string_new("Characteristic value/descriptor: ");
329         for (i = 0; i < vlen; i++)
330                 g_string_append_printf(s, "%02x ", value[i]);
331
332         rl_printf("%s\n", s->str);
333         g_string_free(s, TRUE);
334 }
335
336 static void char_read_by_uuid_cb(guint8 status, const guint8 *pdu,
337                                         guint16 plen, gpointer user_data)
338 {
339         struct att_data_list *list;
340         int i;
341         GString *s;
342
343         if (status != 0) {
344                 error("Read characteristics by UUID failed: %s\n",
345                                                         att_ecode2str(status));
346                 return;
347         }
348
349         list = dec_read_by_type_resp(pdu, plen);
350         if (list == NULL)
351                 return;
352
353         s = g_string_new(NULL);
354         for (i = 0; i < list->num; i++) {
355                 uint8_t *value = list->data[i];
356                 int j;
357
358                 g_string_printf(s, "handle: 0x%04x \t value: ",
359                                                         get_le16(value));
360                 value += 2;
361                 for (j = 0; j < list->len - 2; j++, value++)
362                         g_string_append_printf(s, "%02x ", *value);
363
364                 rl_printf("%s\n", s->str);
365         }
366
367         att_data_list_free(list);
368         g_string_free(s, TRUE);
369 }
370
371 static void cmd_exit(int argcp, char **argvp)
372 {
373         rl_callback_handler_remove();
374         g_main_loop_quit(event_loop);
375 }
376
377 static gboolean channel_watcher(GIOChannel *chan, GIOCondition cond,
378                                 gpointer user_data)
379 {
380         disconnect_io();
381
382         return FALSE;
383 }
384
385 static void cmd_connect(int argcp, char **argvp)
386 {
387         GError *gerr = NULL;
388
389         if (conn_state != STATE_DISCONNECTED)
390                 return;
391
392         if (argcp > 1) {
393                 g_free(opt_dst);
394                 opt_dst = g_strdup(argvp[1]);
395
396                 g_free(opt_dst_type);
397                 if (argcp > 2)
398                         opt_dst_type = g_strdup(argvp[2]);
399                 else
400                         opt_dst_type = g_strdup("public");
401         }
402
403         if (opt_dst == NULL) {
404                 error("Remote Bluetooth address required\n");
405                 return;
406         }
407
408         rl_printf("Attempting to connect to %s\n", opt_dst);
409         set_state(STATE_CONNECTING);
410         iochannel = gatt_connect(opt_src, opt_dst, opt_dst_type, opt_sec_level,
411                                         opt_psm, opt_mtu, connect_cb, &gerr);
412         if (iochannel == NULL) {
413                 set_state(STATE_DISCONNECTED);
414                 error("%s\n", gerr->message);
415                 g_error_free(gerr);
416         } else
417                 g_io_add_watch(iochannel, G_IO_HUP, channel_watcher, NULL);
418 }
419
420 static void cmd_disconnect(int argcp, char **argvp)
421 {
422         disconnect_io();
423 }
424
425 static void cmd_primary(int argcp, char **argvp)
426 {
427         bt_uuid_t uuid;
428
429         if (conn_state != STATE_CONNECTED) {
430                 failed("Disconnected\n");
431                 return;
432         }
433
434         if (argcp == 1) {
435                 gatt_discover_primary(attrib, NULL, primary_all_cb, NULL);
436                 return;
437         }
438
439         if (bt_string_to_uuid(&uuid, argvp[1]) < 0) {
440                 error("Invalid UUID\n");
441                 return;
442         }
443
444         gatt_discover_primary(attrib, &uuid, primary_by_uuid_cb, NULL);
445 }
446
447 static int strtohandle(const char *src)
448 {
449         char *e;
450         int dst;
451
452         errno = 0;
453         dst = strtoll(src, &e, 16);
454         if (errno != 0 || *e != '\0')
455                 return -EINVAL;
456
457         return dst;
458 }
459
460 static void cmd_included(int argcp, char **argvp)
461 {
462         int start = 0x0001;
463         int end = 0xffff;
464
465         if (conn_state != STATE_CONNECTED) {
466                 failed("Disconnected\n");
467                 return;
468         }
469
470         if (argcp > 1) {
471                 start = strtohandle(argvp[1]);
472                 if (start < 0) {
473                         error("Invalid start handle: %s\n", argvp[1]);
474                         return;
475                 }
476                 end = start;
477         }
478
479         if (argcp > 2) {
480                 end = strtohandle(argvp[2]);
481                 if (end < 0) {
482                         error("Invalid end handle: %s\n", argvp[2]);
483                         return;
484                 }
485         }
486
487         gatt_find_included(attrib, start, end, included_cb, NULL);
488 }
489
490 static void cmd_char(int argcp, char **argvp)
491 {
492         int start = 0x0001;
493         int end = 0xffff;
494
495         if (conn_state != STATE_CONNECTED) {
496                 failed("Disconnected\n");
497                 return;
498         }
499
500         if (argcp > 1) {
501                 start = strtohandle(argvp[1]);
502                 if (start < 0) {
503                         error("Invalid start handle: %s\n", argvp[1]);
504                         return;
505                 }
506         }
507
508         if (argcp > 2) {
509                 end = strtohandle(argvp[2]);
510                 if (end < 0) {
511                         error("Invalid end handle: %s\n", argvp[2]);
512                         return;
513                 }
514         }
515
516         if (argcp > 3) {
517                 bt_uuid_t uuid;
518
519                 if (bt_string_to_uuid(&uuid, argvp[3]) < 0) {
520                         error("Invalid UUID\n");
521                         return;
522                 }
523
524                 gatt_discover_char(attrib, start, end, &uuid, char_cb, NULL);
525                 return;
526         }
527
528         gatt_discover_char(attrib, start, end, NULL, char_cb, NULL);
529 }
530
531 static void cmd_char_desc(int argcp, char **argvp)
532 {
533         if (conn_state != STATE_CONNECTED) {
534                 failed("Disconnected\n");
535                 return;
536         }
537
538         if (argcp > 1) {
539                 start = strtohandle(argvp[1]);
540                 if (start < 0) {
541                         error("Invalid start handle: %s\n", argvp[1]);
542                         return;
543                 }
544         } else
545                 start = 0x0001;
546
547         if (argcp > 2) {
548                 end = strtohandle(argvp[2]);
549                 if (end < 0) {
550                         error("Invalid end handle: %s\n", argvp[2]);
551                         return;
552                 }
553         } else
554                 end = 0xffff;
555
556         gatt_discover_desc(attrib, start, end, NULL, char_desc_cb, NULL);
557 }
558
559 static void cmd_read_hnd(int argcp, char **argvp)
560 {
561         int handle;
562 #ifdef __TIZEN_PATCH__
563         int offset = 0;
564 #endif
565         if (conn_state != STATE_CONNECTED) {
566                 failed("Disconnected\n");
567                 return;
568         }
569
570         if (argcp < 2) {
571                 error("Missing argument: handle\n");
572                 return;
573         }
574
575         handle = strtohandle(argvp[1]);
576         if (handle < 0) {
577                 error("Invalid handle: %s\n", argvp[1]);
578                 return;
579         }
580 #ifdef __TIZEN_PATCH__
581         if (argcp > 2) {
582                 offset = strtohandle(argvp[2]);
583                 if (offset < 0) {
584                         error("Invalid Offset: %s\n", argvp[2]);
585                         return;
586                 }
587         }
588         gatt_read_char_by_offset(attrib, handle, offset, char_read_cb, attrib);
589 #else
590         gatt_read_char(attrib, handle, char_read_cb, attrib);
591 #endif
592 }
593
594 static void cmd_read_uuid(int argcp, char **argvp)
595 {
596         int start = 0x0001;
597         int end = 0xffff;
598         bt_uuid_t uuid;
599
600         if (conn_state != STATE_CONNECTED) {
601                 failed("Disconnected\n");
602                 return;
603         }
604
605         if (argcp < 2) {
606                 error("Missing argument: UUID\n");
607                 return;
608         }
609
610         if (bt_string_to_uuid(&uuid, argvp[1]) < 0) {
611                 error("Invalid UUID\n");
612                 return;
613         }
614
615         if (argcp > 2) {
616                 start = strtohandle(argvp[2]);
617                 if (start < 0) {
618                         error("Invalid start handle: %s\n", argvp[1]);
619                         return;
620                 }
621         }
622
623         if (argcp > 3) {
624                 end = strtohandle(argvp[3]);
625                 if (end < 0) {
626                         error("Invalid end handle: %s\n", argvp[2]);
627                         return;
628                 }
629         }
630
631         gatt_read_char_by_uuid(attrib, start, end, &uuid, char_read_by_uuid_cb,
632                                                                         NULL);
633 }
634
635 static void char_write_req_cb(guint8 status, const guint8 *pdu, guint16 plen,
636                                                         gpointer user_data)
637 {
638         if (status != 0) {
639                 error("Characteristic Write Request failed: "
640                                                 "%s\n", att_ecode2str(status));
641                 return;
642         }
643
644         if (!dec_write_resp(pdu, plen) && !dec_exec_write_resp(pdu, plen)) {
645                 error("Protocol error\n");
646                 return;
647         }
648
649         rl_printf("Characteristic value was written successfully\n");
650 }
651
652 static void cmd_char_write(int argcp, char **argvp)
653 {
654         uint8_t *value;
655         size_t plen;
656         int handle;
657
658         if (conn_state != STATE_CONNECTED) {
659                 failed("Disconnected\n");
660                 return;
661         }
662
663         if (argcp < 3) {
664                 rl_printf("Usage: %s <handle> <new value>\n", argvp[0]);
665                 return;
666         }
667
668         handle = strtohandle(argvp[1]);
669         if (handle <= 0) {
670                 error("A valid handle is required\n");
671                 return;
672         }
673
674         plen = gatt_attr_data_from_string(argvp[2], &value);
675         if (plen == 0) {
676                 error("Invalid value\n");
677                 return;
678         }
679
680         if (g_strcmp0("char-write-req", argvp[0]) == 0)
681                 gatt_write_char(attrib, handle, value, plen,
682                                         char_write_req_cb, NULL);
683         else
684                 gatt_write_cmd(attrib, handle, value, plen, NULL, NULL);
685
686         g_free(value);
687 }
688
689 static void cmd_sec_level(int argcp, char **argvp)
690 {
691         GError *gerr = NULL;
692         BtIOSecLevel sec_level;
693
694         if (argcp < 2) {
695                 rl_printf("sec-level: %s\n", opt_sec_level);
696                 return;
697         }
698
699         if (strcasecmp(argvp[1], "medium") == 0)
700                 sec_level = BT_IO_SEC_MEDIUM;
701         else if (strcasecmp(argvp[1], "high") == 0)
702                 sec_level = BT_IO_SEC_HIGH;
703         else if (strcasecmp(argvp[1], "low") == 0)
704                 sec_level = BT_IO_SEC_LOW;
705         else {
706                 rl_printf("Allowed values: low | medium | high\n");
707                 return;
708         }
709
710         g_free(opt_sec_level);
711         opt_sec_level = g_strdup(argvp[1]);
712
713         if (conn_state != STATE_CONNECTED)
714                 return;
715
716         if (opt_psm) {
717                 rl_printf("Change will take effect on reconnection\n");
718                 return;
719         }
720
721         bt_io_set(iochannel, &gerr,
722                         BT_IO_OPT_SEC_LEVEL, sec_level,
723                         BT_IO_OPT_INVALID);
724         if (gerr) {
725                 error("%s\n", gerr->message);
726                 g_error_free(gerr);
727         }
728 }
729
730 static void exchange_mtu_cb(guint8 status, const guint8 *pdu, guint16 plen,
731                                                         gpointer user_data)
732 {
733         uint16_t mtu;
734
735         if (status != 0) {
736                 error("Exchange MTU Request failed: %s\n",
737                                                 att_ecode2str(status));
738                 return;
739         }
740
741         if (!dec_mtu_resp(pdu, plen, &mtu)) {
742                 error("Protocol error\n");
743                 return;
744         }
745
746         mtu = MIN(mtu, opt_mtu);
747         /* Set new value for MTU in client */
748         if (g_attrib_set_mtu(attrib, mtu))
749                 rl_printf("MTU was exchanged successfully: %d\n", mtu);
750         else
751                 error("Error exchanging MTU\n");
752 }
753
754 static void cmd_mtu(int argcp, char **argvp)
755 {
756         if (conn_state != STATE_CONNECTED) {
757                 failed("Disconnected\n");
758                 return;
759         }
760
761         if (opt_psm) {
762                 failed("Operation is only available for LE transport.\n");
763                 return;
764         }
765
766         if (argcp < 2) {
767                 rl_printf("Usage: mtu <value>\n");
768                 return;
769         }
770
771         if (opt_mtu) {
772                 failed("MTU exchange can only occur once per connection.\n");
773                 return;
774         }
775
776         errno = 0;
777         opt_mtu = strtoll(argvp[1], NULL, 0);
778         if (errno != 0 || opt_mtu < ATT_DEFAULT_LE_MTU) {
779                 error("Invalid value. Minimum MTU size is %d\n",
780                                                         ATT_DEFAULT_LE_MTU);
781                 return;
782         }
783
784         gatt_exchange_mtu(attrib, opt_mtu, exchange_mtu_cb, NULL);
785 }
786
787 static struct {
788         const char *cmd;
789         void (*func)(int argcp, char **argvp);
790         const char *params;
791         const char *desc;
792 } commands[] = {
793         { "help",               cmd_help,       "",
794                 "Show this help"},
795         { "exit",               cmd_exit,       "",
796                 "Exit interactive mode" },
797         { "quit",               cmd_exit,       "",
798                 "Exit interactive mode" },
799         { "connect",            cmd_connect,    "[address [address type]]",
800                 "Connect to a remote device" },
801         { "disconnect",         cmd_disconnect, "",
802                 "Disconnect from a remote device" },
803         { "primary",            cmd_primary,    "[UUID]",
804                 "Primary Service Discovery" },
805         { "included",           cmd_included,   "[start hnd [end hnd]]",
806                 "Find Included Services" },
807         { "characteristics",    cmd_char,       "[start hnd [end hnd [UUID]]]",
808                 "Characteristics Discovery" },
809         { "char-desc",          cmd_char_desc,  "[start hnd] [end hnd]",
810                 "Characteristics Descriptor Discovery" },
811         { "char-read-hnd",      cmd_read_hnd,   "<handle>",
812                 "Characteristics Value/Descriptor Read by handle" },
813         { "char-read-uuid",     cmd_read_uuid,  "<UUID> [start hnd] [end hnd]",
814                 "Characteristics Value/Descriptor Read by UUID" },
815         { "char-write-req",     cmd_char_write, "<handle> <new value>",
816                 "Characteristic Value Write (Write Request)" },
817         { "char-write-cmd",     cmd_char_write, "<handle> <new value>",
818                 "Characteristic Value Write (No response)" },
819         { "sec-level",          cmd_sec_level,  "[low | medium | high]",
820                 "Set security level. Default: low" },
821         { "mtu",                cmd_mtu,        "<value>",
822                 "Exchange MTU for GATT/ATT" },
823         { NULL, NULL, NULL}
824 };
825
826 static void cmd_help(int argcp, char **argvp)
827 {
828         int i;
829
830         for (i = 0; commands[i].cmd; i++)
831                 rl_printf("%-15s %-30s %s\n", commands[i].cmd,
832                                 commands[i].params, commands[i].desc);
833 }
834
835 static void parse_line(char *line_read)
836 {
837         char **argvp;
838         int argcp;
839         int i;
840
841         if (line_read == NULL) {
842                 rl_printf("\n");
843                 cmd_exit(0, NULL);
844                 return;
845         }
846
847         line_read = g_strstrip(line_read);
848
849         if (*line_read == '\0')
850                 goto done;
851
852         add_history(line_read);
853
854         if (g_shell_parse_argv(line_read, &argcp, &argvp, NULL) == FALSE)
855                 goto done;
856
857         for (i = 0; commands[i].cmd; i++)
858                 if (strcasecmp(commands[i].cmd, argvp[0]) == 0)
859                         break;
860
861         if (commands[i].cmd)
862                 commands[i].func(argcp, argvp);
863         else
864                 error("%s: command not found\n", argvp[0]);
865
866         g_strfreev(argvp);
867
868 done:
869         free(line_read);
870 }
871
872 static gboolean prompt_read(GIOChannel *chan, GIOCondition cond,
873                                                         gpointer user_data)
874 {
875         if (cond & (G_IO_HUP | G_IO_ERR | G_IO_NVAL)) {
876                 g_io_channel_unref(chan);
877                 return FALSE;
878         }
879
880         rl_callback_read_char();
881
882         return TRUE;
883 }
884
885 static char *completion_generator(const char *text, int state)
886 {
887         static int index = 0, len = 0;
888         const char *cmd = NULL;
889
890         if (state == 0) {
891                 index = 0;
892                 len = strlen(text);
893         }
894
895         while ((cmd = commands[index].cmd) != NULL) {
896                 index++;
897                 if (strncmp(cmd, text, len) == 0)
898                         return strdup(cmd);
899         }
900
901         return NULL;
902 }
903
904 static char **commands_completion(const char *text, int start, int end)
905 {
906         if (start == 0)
907                 return rl_completion_matches(text, &completion_generator);
908         else
909                 return NULL;
910 }
911
912 static guint setup_standard_input(void)
913 {
914         GIOChannel *channel;
915         guint source;
916
917         channel = g_io_channel_unix_new(fileno(stdin));
918
919         source = g_io_add_watch(channel,
920                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
921                                 prompt_read, NULL);
922
923         g_io_channel_unref(channel);
924
925         return source;
926 }
927
928 static gboolean signal_handler(GIOChannel *channel, GIOCondition condition,
929                                                         gpointer user_data)
930 {
931         static unsigned int __terminated = 0;
932         struct signalfd_siginfo si;
933         ssize_t result;
934         int fd;
935
936         if (condition & (G_IO_NVAL | G_IO_ERR | G_IO_HUP)) {
937                 g_main_loop_quit(event_loop);
938                 return FALSE;
939         }
940
941         fd = g_io_channel_unix_get_fd(channel);
942
943         result = read(fd, &si, sizeof(si));
944         if (result != sizeof(si))
945                 return FALSE;
946
947         switch (si.ssi_signo) {
948         case SIGINT:
949                 rl_replace_line("", 0);
950                 rl_crlf();
951                 rl_on_new_line();
952                 rl_redisplay();
953                 break;
954         case SIGTERM:
955                 if (__terminated == 0) {
956                         rl_replace_line("", 0);
957                         rl_crlf();
958                         g_main_loop_quit(event_loop);
959                 }
960
961                 __terminated = 1;
962                 break;
963         }
964
965         return TRUE;
966 }
967
968 static guint setup_signalfd(void)
969 {
970         GIOChannel *channel;
971         guint source;
972         sigset_t mask;
973         int fd;
974
975         sigemptyset(&mask);
976         sigaddset(&mask, SIGINT);
977         sigaddset(&mask, SIGTERM);
978
979         if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) {
980                 perror("Failed to set signal mask");
981                 return 0;
982         }
983
984         fd = signalfd(-1, &mask, 0);
985         if (fd < 0) {
986                 perror("Failed to create signal descriptor");
987                 return 0;
988         }
989
990         channel = g_io_channel_unix_new(fd);
991
992         g_io_channel_set_close_on_unref(channel, TRUE);
993         g_io_channel_set_encoding(channel, NULL, NULL);
994         g_io_channel_set_buffered(channel, FALSE);
995
996         source = g_io_add_watch(channel,
997                                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL,
998                                 signal_handler, NULL);
999
1000         g_io_channel_unref(channel);
1001
1002         return source;
1003 }
1004
1005 int interactive(const char *src, const char *dst,
1006                 const char *dst_type, int psm)
1007 {
1008         guint input;
1009         guint signal;
1010
1011         opt_sec_level = g_strdup("low");
1012
1013         opt_src = g_strdup(src);
1014         opt_dst = g_strdup(dst);
1015         opt_dst_type = g_strdup(dst_type);
1016         opt_psm = psm;
1017
1018         prompt = g_string_new(NULL);
1019
1020         event_loop = g_main_loop_new(NULL, FALSE);
1021
1022         input = setup_standard_input();
1023         signal = setup_signalfd();
1024
1025         rl_attempted_completion_function = commands_completion;
1026         rl_erase_empty_line = 1;
1027         rl_callback_handler_install(get_prompt(), parse_line);
1028
1029         g_main_loop_run(event_loop);
1030
1031         rl_callback_handler_remove();
1032         cmd_disconnect(0, NULL);
1033         g_source_remove(input);
1034         g_source_remove(signal);
1035         g_main_loop_unref(event_loop);
1036         g_string_free(prompt, TRUE);
1037
1038         g_free(opt_src);
1039         g_free(opt_dst);
1040         g_free(opt_sec_level);
1041
1042         return 0;
1043 }