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