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