upgraded bluez to 4.101
[profile/ivi/bluez.git] / network / connection.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel@holtmann.org>
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 <stdio.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <netinet/in.h>
32
33 #include <bluetooth/bluetooth.h>
34 #include <bluetooth/bnep.h>
35 #include <bluetooth/sdp.h>
36
37 #include <glib.h>
38 #include <gdbus.h>
39
40 #include "log.h"
41 #include "btio.h"
42 #include "dbus-common.h"
43 #include "adapter.h"
44 #include "device.h"
45
46 #include "error.h"
47 #include "common.h"
48 #include "connection.h"
49
50 #define NETWORK_PEER_INTERFACE "org.bluez.Network"
51 #define CON_SETUP_RETRIES      3
52 #define CON_SETUP_TO           9
53
54 typedef enum {
55         CONNECTED,
56         CONNECTING,
57         DISCONNECTED
58 } conn_state;
59
60 struct network_peer {
61         bdaddr_t        src;
62         bdaddr_t        dst;
63         char            *path;          /* D-Bus path */
64         struct btd_device *device;
65         GSList          *connections;
66 };
67
68 struct network_conn {
69         DBusMessage     *msg;
70         char            dev[16];        /* Interface name */
71         uint16_t        id;             /* Role: Service Class Identifier */
72         conn_state      state;
73         GIOChannel      *io;
74         guint           watch;          /* Disconnect watch */
75         guint           dc_id;
76         struct network_peer *peer;
77         guint           attempt_cnt;
78         guint           timeout_source;
79 };
80
81 struct __service_16 {
82         uint16_t dst;
83         uint16_t src;
84 } __attribute__ ((packed));
85
86 static DBusConnection *connection = NULL;
87 static GSList *peers = NULL;
88
89 static struct network_peer *find_peer(GSList *list, const char *path)
90 {
91         for (; list; list = list->next) {
92                 struct network_peer *peer = list->data;
93
94                 if (!strcmp(peer->path, path))
95                         return peer;
96         }
97
98         return NULL;
99 }
100
101 static struct network_conn *find_connection(GSList *list, uint16_t id)
102 {
103         for (; list; list = list->next) {
104                 struct network_conn *nc = list->data;
105
106                 if (nc->id == id)
107                         return nc;
108         }
109
110         return NULL;
111 }
112
113 static gboolean bnep_watchdog_cb(GIOChannel *chan, GIOCondition cond,
114                                 gpointer data)
115 {
116         struct network_conn *nc = data;
117
118         if (connection != NULL) {
119                 gboolean connected = FALSE;
120                 const char *property = "";
121                 emit_property_changed(connection, nc->peer->path,
122                                         NETWORK_PEER_INTERFACE, "Connected",
123                                         DBUS_TYPE_BOOLEAN, &connected);
124                 emit_property_changed(connection, nc->peer->path,
125                                         NETWORK_PEER_INTERFACE, "Interface",
126                                         DBUS_TYPE_STRING, &property);
127                 emit_property_changed(connection, nc->peer->path,
128                                         NETWORK_PEER_INTERFACE, "UUID",
129                                         DBUS_TYPE_STRING, &property);
130                 device_remove_disconnect_watch(nc->peer->device, nc->dc_id);
131                 nc->dc_id = 0;
132                 if (nc->watch) {
133                         g_dbus_remove_watch(connection, nc->watch);
134                         nc->watch = 0;
135                 }
136         }
137
138         info("%s disconnected", nc->dev);
139
140         bnep_if_down(nc->dev);
141         nc->state = DISCONNECTED;
142         memset(nc->dev, 0, sizeof(nc->dev));
143         strcpy(nc->dev, "bnep%d");
144
145         return FALSE;
146 }
147
148 static void cancel_connection(struct network_conn *nc, const char *err_msg)
149 {
150         DBusMessage *reply;
151
152         if (nc->timeout_source > 0) {
153                 g_source_remove(nc->timeout_source);
154                 nc->timeout_source = 0;
155         }
156
157         if (nc->watch) {
158                 g_dbus_remove_watch(connection, nc->watch);
159                 nc->watch = 0;
160         }
161
162         if (nc->msg && err_msg) {
163                 reply = btd_error_failed(nc->msg, err_msg);
164                 g_dbus_send_message(connection, reply);
165         }
166
167         g_io_channel_shutdown(nc->io, TRUE, NULL);
168         g_io_channel_unref(nc->io);
169         nc->io = NULL;
170
171         nc->state = DISCONNECTED;
172 }
173
174 static void connection_destroy(DBusConnection *conn, void *user_data)
175 {
176         struct network_conn *nc = user_data;
177
178         if (nc->state == CONNECTED) {
179                 bnep_if_down(nc->dev);
180                 bnep_kill_connection(&nc->peer->dst);
181         } else if (nc->io)
182                 cancel_connection(nc, NULL);
183 }
184
185 static void disconnect_cb(struct btd_device *device, gboolean removal,
186                                 void *user_data)
187 {
188         struct network_conn *nc = user_data;
189
190         info("Network: disconnect %s", nc->peer->path);
191
192         connection_destroy(NULL, user_data);
193 }
194
195 static gboolean bnep_setup_cb(GIOChannel *chan, GIOCondition cond,
196                                                         gpointer data)
197 {
198         struct network_conn *nc = data;
199         struct bnep_control_rsp *rsp;
200         struct timeval timeo;
201         char pkt[BNEP_MTU];
202         ssize_t r;
203         int sk;
204         const char *pdev, *uuid;
205         gboolean connected;
206
207         if (cond & G_IO_NVAL)
208                 return FALSE;
209
210         g_source_remove(nc->timeout_source);
211         nc->timeout_source = 0;
212
213         if (cond & (G_IO_HUP | G_IO_ERR)) {
214                 error("Hangup or error on l2cap server socket");
215                 goto failed;
216         }
217
218         sk = g_io_channel_unix_get_fd(chan);
219
220         memset(pkt, 0, BNEP_MTU);
221         r = read(sk, pkt, sizeof(pkt) -1);
222         if (r < 0) {
223                 error("IO Channel read error");
224                 goto failed;
225         }
226
227         if (r == 0) {
228                 error("No packet received on l2cap socket");
229                 goto failed;
230         }
231
232         errno = EPROTO;
233
234         if ((size_t) r < sizeof(*rsp)) {
235                 error("Packet received is not bnep type");
236                 goto failed;
237         }
238
239         rsp = (void *) pkt;
240         if (rsp->type != BNEP_CONTROL) {
241                 error("Packet received is not bnep type");
242                 goto failed;
243         }
244
245         if (rsp->ctrl != BNEP_SETUP_CONN_RSP)
246                 return TRUE;
247
248         r = ntohs(rsp->resp);
249
250         if (r != BNEP_SUCCESS) {
251                 error("bnep failed");
252                 goto failed;
253         }
254
255         memset(&timeo, 0, sizeof(timeo));
256         timeo.tv_sec = 0;
257
258         setsockopt(sk, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(timeo));
259
260         if (bnep_connadd(sk, BNEP_SVC_PANU, nc->dev)) {
261                 error("%s could not be added", nc->dev);
262                 goto failed;
263         }
264
265         bnep_if_up(nc->dev);
266         pdev = nc->dev;
267         uuid = bnep_uuid(nc->id);
268
269         g_dbus_send_reply(connection, nc->msg,
270                         DBUS_TYPE_STRING, &pdev,
271                         DBUS_TYPE_INVALID);
272
273         connected = TRUE;
274         emit_property_changed(connection, nc->peer->path,
275                                 NETWORK_PEER_INTERFACE, "Connected",
276                                 DBUS_TYPE_BOOLEAN, &connected);
277         emit_property_changed(connection, nc->peer->path,
278                                 NETWORK_PEER_INTERFACE, "Interface",
279                                 DBUS_TYPE_STRING, &pdev);
280         emit_property_changed(connection, nc->peer->path,
281                                 NETWORK_PEER_INTERFACE, "UUID",
282                                 DBUS_TYPE_STRING, &uuid);
283
284         nc->state = CONNECTED;
285         nc->dc_id = device_add_disconnect_watch(nc->peer->device, disconnect_cb,
286                                                 nc, NULL);
287
288         info("%s connected", nc->dev);
289         /* Start watchdog */
290         g_io_add_watch(chan, G_IO_ERR | G_IO_HUP | G_IO_NVAL,
291                         (GIOFunc) bnep_watchdog_cb, nc);
292         g_io_channel_unref(nc->io);
293         nc->io = NULL;
294
295         return FALSE;
296
297 failed:
298         cancel_connection(nc, "bnep setup failed");
299
300         return FALSE;
301 }
302
303 static int bnep_send_conn_req(struct network_conn *nc)
304 {
305         struct bnep_setup_conn_req *req;
306         struct __service_16 *s;
307         unsigned char pkt[BNEP_MTU];
308         int fd;
309
310         /* Send request */
311         req = (void *) pkt;
312         req->type = BNEP_CONTROL;
313         req->ctrl = BNEP_SETUP_CONN_REQ;
314         req->uuid_size = 2;     /* 16bit UUID */
315         s = (void *) req->service;
316         s->dst = htons(nc->id);
317         s->src = htons(BNEP_SVC_PANU);
318
319         fd = g_io_channel_unix_get_fd(nc->io);
320         if (write(fd, pkt, sizeof(*req) + sizeof(*s)) < 0) {
321                 int err = -errno;
322                 error("bnep connection req send failed: %s", strerror(errno));
323                 return err;
324         }
325
326         nc->attempt_cnt++;
327
328         return 0;
329 }
330
331 static gboolean bnep_conn_req_to(gpointer user_data)
332 {
333         struct network_conn *nc;
334
335         nc = user_data;
336         if (nc->attempt_cnt == CON_SETUP_RETRIES) {
337                 error("Too many bnep connection attempts");
338         } else {
339                 error("bnep connection setup TO, retrying...");
340                 if (!bnep_send_conn_req(nc))
341                         return TRUE;
342         }
343
344         cancel_connection(nc, "bnep setup failed");
345
346         return FALSE;
347 }
348
349 static int bnep_connect(struct network_conn *nc)
350 {
351         int err;
352
353         nc->attempt_cnt = 0;
354         if ((err = bnep_send_conn_req(nc)))
355                 return err;
356
357         nc->timeout_source = g_timeout_add_seconds(CON_SETUP_TO,
358                                                         bnep_conn_req_to, nc);
359
360         g_io_add_watch(nc->io, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
361                         (GIOFunc) bnep_setup_cb, nc);
362
363         return 0;
364 }
365
366 static void connect_cb(GIOChannel *chan, GError *err, gpointer data)
367 {
368         struct network_conn *nc = data;
369         const char *err_msg;
370         int perr;
371
372         if (err) {
373                 error("%s", err->message);
374                 err_msg = err->message;
375                 goto failed;
376         }
377
378         perr = bnep_connect(nc);
379         if (perr < 0) {
380                 err_msg = strerror(-perr);
381                 error("bnep connect(): %s (%d)", err_msg, -perr);
382                 goto failed;
383         }
384
385         return;
386
387 failed:
388         cancel_connection(nc, err_msg);
389 }
390
391 /* Connect and initiate BNEP session */
392 static DBusMessage *connection_connect(DBusConnection *conn,
393                                                 DBusMessage *msg, void *data)
394 {
395         struct network_peer *peer = data;
396         struct network_conn *nc;
397         const char *svc;
398         uint16_t id;
399         GError *err = NULL;
400
401         if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &svc,
402                                                 DBUS_TYPE_INVALID) == FALSE)
403                 return NULL;
404
405         id = bnep_service_id(svc);
406         nc = find_connection(peer->connections, id);
407         if (!nc)
408                 return btd_error_not_supported(msg);
409
410         if (nc->state != DISCONNECTED)
411                 return btd_error_already_connected(msg);
412
413         nc->io = bt_io_connect(BT_IO_L2CAP, connect_cb, nc,
414                                 NULL, &err,
415                                 BT_IO_OPT_SOURCE_BDADDR, &peer->src,
416                                 BT_IO_OPT_DEST_BDADDR, &peer->dst,
417                                 BT_IO_OPT_PSM, BNEP_PSM,
418                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
419                                 BT_IO_OPT_OMTU, BNEP_MTU,
420                                 BT_IO_OPT_IMTU, BNEP_MTU,
421                                 BT_IO_OPT_INVALID);
422         if (!nc->io) {
423                 DBusMessage *reply;
424                 error("%s", err->message);
425                 reply = btd_error_failed(msg, err->message);
426                 g_error_free(err);
427                 return reply;
428         }
429
430         nc->state = CONNECTING;
431         nc->msg = dbus_message_ref(msg);
432         nc->watch = g_dbus_add_disconnect_watch(conn,
433                                                 dbus_message_get_sender(msg),
434                                                 connection_destroy,
435                                                 nc, NULL);
436
437         return NULL;
438 }
439
440 static DBusMessage *connection_cancel(DBusConnection *conn,
441                                                 DBusMessage *msg, void *data)
442 {
443         struct network_conn *nc = data;
444         const char *owner = dbus_message_get_sender(nc->msg);
445         const char *caller = dbus_message_get_sender(msg);
446
447         if (!g_str_equal(owner, caller))
448                 return btd_error_not_authorized(msg);
449
450         connection_destroy(conn, nc);
451
452         return g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
453 }
454
455 static DBusMessage *connection_disconnect(DBusConnection *conn,
456                                         DBusMessage *msg, void *data)
457 {
458         struct network_peer *peer = data;
459         GSList *l;
460
461         for (l = peer->connections; l; l = l->next) {
462                 struct network_conn *nc = l->data;
463
464                 if (nc->state == DISCONNECTED)
465                         continue;
466
467                 return connection_cancel(conn, msg, nc);
468         }
469
470         return btd_error_not_connected(msg);
471 }
472
473 static DBusMessage *connection_get_properties(DBusConnection *conn,
474                                         DBusMessage *msg, void *data)
475 {
476         struct network_peer *peer = data;
477         struct network_conn *nc = NULL;
478         DBusMessage *reply;
479         DBusMessageIter iter;
480         DBusMessageIter dict;
481         dbus_bool_t connected;
482         const char *property;
483         GSList *l;
484
485         reply = dbus_message_new_method_return(msg);
486         if (!reply)
487                 return NULL;
488
489         dbus_message_iter_init_append(reply, &iter);
490
491         dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
492                         DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
493                         DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
494                         DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
495
496         /* Connected */
497         for (l = peer->connections; l; l = l->next) {
498                 struct network_conn *tmp = l->data;
499
500                 if (tmp->state != CONNECTED)
501                         continue;
502
503                 nc = tmp;
504                 break;
505         }
506
507         connected = nc ? TRUE : FALSE;
508         dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &connected);
509
510         /* Interface */
511         property = nc ? nc->dev : "";
512         dict_append_entry(&dict, "Interface", DBUS_TYPE_STRING, &property);
513
514         /* UUID */
515         property = nc ? bnep_uuid(nc->id) : "";
516         dict_append_entry(&dict, "UUID", DBUS_TYPE_STRING, &property);
517
518         dbus_message_iter_close_container(&iter, &dict);
519
520         return reply;
521 }
522
523 static void connection_free(void *data)
524 {
525         struct network_conn *nc = data;
526
527         if (nc->dc_id)
528                 device_remove_disconnect_watch(nc->peer->device, nc->dc_id);
529
530         connection_destroy(connection, nc);
531
532         g_free(nc);
533         nc = NULL;
534 }
535
536 static void peer_free(struct network_peer *peer)
537 {
538         g_slist_free_full(peer->connections, connection_free);
539         btd_device_unref(peer->device);
540         g_free(peer->path);
541         g_free(peer);
542 }
543
544 static void path_unregister(void *data)
545 {
546         struct network_peer *peer = data;
547
548         DBG("Unregistered interface %s on path %s",
549                 NETWORK_PEER_INTERFACE, peer->path);
550
551         peers = g_slist_remove(peers, peer);
552         peer_free(peer);
553 }
554
555 static const GDBusMethodTable connection_methods[] = {
556         { GDBUS_ASYNC_METHOD("Connect",
557                         NULL, NULL, connection_connect) },
558         { GDBUS_METHOD("Disconnect",
559                         NULL, NULL, connection_disconnect) },
560         { GDBUS_METHOD("GetProperties",
561                         NULL, GDBUS_ARGS({ "properties", "a{sv}" }),
562                         connection_get_properties) },
563         { }
564 };
565
566 static const GDBusSignalTable connection_signals[] = {
567         { GDBUS_SIGNAL("PropertyChanged",
568                         GDBUS_ARGS({ "name", "s" }, { "value", "v" })) },
569         { }
570 };
571
572 void connection_unregister(const char *path, uint16_t id)
573 {
574         struct network_peer *peer;
575         struct network_conn *nc;
576
577         peer = find_peer(peers, path);
578         if (!peer)
579                 return;
580
581         nc = find_connection(peer->connections, id);
582         if (!nc)
583                 return;
584
585         peer->connections = g_slist_remove(peer->connections, nc);
586         connection_free(nc);
587         if (peer->connections)
588                 return;
589
590         g_dbus_unregister_interface(connection, path, NETWORK_PEER_INTERFACE);
591 }
592
593 static struct network_peer *create_peer(struct btd_device *device,
594                                         const char *path, bdaddr_t *src,
595                                         bdaddr_t *dst)
596 {
597         struct network_peer *peer;
598
599         peer = g_new0(struct network_peer, 1);
600         peer->device = btd_device_ref(device);
601         peer->path = g_strdup(path);
602         bacpy(&peer->src, src);
603         bacpy(&peer->dst, dst);
604
605         if (g_dbus_register_interface(connection, path,
606                                         NETWORK_PEER_INTERFACE,
607                                         connection_methods,
608                                         connection_signals, NULL,
609                                         peer, path_unregister) == FALSE) {
610                 error("D-Bus failed to register %s interface",
611                         NETWORK_PEER_INTERFACE);
612                 peer_free(peer);
613                 return NULL;
614         }
615
616         DBG("Registered interface %s on path %s",
617                 NETWORK_PEER_INTERFACE, path);
618
619         return peer;
620 }
621
622 int connection_register(struct btd_device *device, const char *path,
623                         bdaddr_t *src, bdaddr_t *dst, uint16_t id)
624 {
625         struct network_peer *peer;
626         struct network_conn *nc;
627
628         if (!path)
629                 return -EINVAL;
630
631         peer = find_peer(peers, path);
632         if (!peer) {
633                 peer = create_peer(device, path, src, dst);
634                 if (!peer)
635                         return -1;
636                 peers = g_slist_append(peers, peer);
637         }
638
639         nc = find_connection(peer->connections, id);
640         if (nc)
641                 return 0;
642
643         nc = g_new0(struct network_conn, 1);
644         nc->id = id;
645         memset(nc->dev, 0, sizeof(nc->dev));
646         strcpy(nc->dev, "bnep%d");
647         nc->state = DISCONNECTED;
648         nc->peer = peer;
649
650         peer->connections = g_slist_append(peer->connections, nc);
651
652         return 0;
653 }
654
655 int connection_init(DBusConnection *conn)
656 {
657         connection = dbus_connection_ref(conn);
658
659         return 0;
660 }
661
662 void connection_exit(void)
663 {
664         dbus_connection_unref(connection);
665         connection = NULL;
666 }