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