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