hciemu.c revision 607695ed109340f4b7a5628420e0a8e8aee34f4e
1/*
2 *
3 *  BlueZ - Bluetooth protocol stack for Linux
4 *
5 *  Copyright (C) 2000-2002  Maxim Krasnyansky <maxk@qualcomm.com>
6 *  Copyright (C) 2003-2007  Marcel Holtmann <marcel@holtmann.org>
7 *
8 *
9 *  This program is free software; you can redistribute it and/or modify
10 *  it under the terms of the GNU General Public License as published by
11 *  the Free Software Foundation; either version 2 of the License, or
12 *  (at your option) any later version.
13 *
14 *  This program is distributed in the hope that it will be useful,
15 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 *  GNU General Public License for more details.
18 *
19 *  You should have received a copy of the GNU General Public License
20 *  along with this program; if not, write to the Free Software
21 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22 *
23 */
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include <stdio.h>
30#include <errno.h>
31#include <ctype.h>
32#include <fcntl.h>
33#include <unistd.h>
34#include <stdlib.h>
35#include <stdint.h>
36#include <string.h>
37#include <signal.h>
38#include <getopt.h>
39#include <syslog.h>
40#include <sys/time.h>
41#include <sys/stat.h>
42#include <sys/poll.h>
43#include <sys/ioctl.h>
44#include <sys/socket.h>
45#include <sys/resource.h>
46
47#include <bluetooth/bluetooth.h>
48#include <bluetooth/hci.h>
49#include <bluetooth/hci_lib.h>
50
51#include <netdb.h>
52
53#include "glib-ectomy.h"
54
55#if __BYTE_ORDER == __LITTLE_ENDIAN
56static inline uint64_t ntoh64(uint64_t n)
57{
58	uint64_t h;
59	uint64_t tmp = ntohl(n & 0x00000000ffffffff);
60	h = ntohl(n >> 32);
61	h |= tmp << 32;
62	return h;
63}
64#elif __BYTE_ORDER == __BIG_ENDIAN
65#define ntoh64(x) (x)
66#else
67#error "Unknown byte order"
68#endif
69#define hton64(x) ntoh64(x)
70
71#define GHCI_DEV		"/dev/ghci"
72
73#define VHCI_DEV		"/dev/vhci"
74#define VHCI_UDEV		"/dev/hci_vhci"
75
76#define VHCI_MAX_CONN		12
77
78#define VHCI_ACL_MTU		192
79#define VHCI_ACL_MAX_PKT	8
80
81struct vhci_device {
82	uint8_t		features[8];
83	uint8_t		name[248];
84	uint8_t		dev_class[3];
85	uint8_t		inq_mode;
86	uint8_t		eir_fec;
87	uint8_t		eir_data[240];
88	uint16_t	acl_cnt;
89	bdaddr_t	bdaddr;
90	int		fd;
91	int		dd;
92	GIOChannel	*scan;
93};
94
95struct vhci_conn {
96	bdaddr_t	dest;
97	uint16_t	handle;
98	GIOChannel	*chan;
99};
100
101struct vhci_link_info {
102	bdaddr_t	bdaddr;
103	uint8_t		dev_class[3];
104	uint8_t		link_type;
105	uint8_t		role;
106} __attribute__ ((packed));
107
108static struct vhci_device vdev;
109static struct vhci_conn *vconn[VHCI_MAX_CONN];
110
111struct btsnoop_hdr {
112	uint8_t		id[8];		/* Identification Pattern */
113	uint32_t	version;	/* Version Number = 1 */
114	uint32_t	type;		/* Datalink Type */
115} __attribute__ ((packed));
116#define BTSNOOP_HDR_SIZE (sizeof(struct btsnoop_hdr))
117
118struct btsnoop_pkt {
119	uint32_t	size;		/* Original Length */
120	uint32_t	len;		/* Included Length */
121	uint32_t	flags;		/* Packet Flags */
122	uint32_t	drops;		/* Cumulative Drops */
123	uint64_t	ts;		/* Timestamp microseconds */
124	uint8_t		data[0];	/* Packet Data */
125} __attribute__ ((packed));
126#define BTSNOOP_PKT_SIZE (sizeof(struct btsnoop_pkt))
127
128static uint8_t btsnoop_id[] = { 0x62, 0x74, 0x73, 0x6e, 0x6f, 0x6f, 0x70, 0x00 };
129
130static GMainLoop *event_loop;
131
132static volatile sig_atomic_t __io_canceled;
133
134static inline void io_init(void)
135{
136	__io_canceled = 0;
137}
138
139static inline void io_cancel(void)
140{
141	__io_canceled = 1;
142}
143
144static void sig_term(int sig)
145{
146	io_cancel();
147	g_main_quit(event_loop);
148}
149
150static gboolean io_acl_data(GIOChannel *chan, GIOCondition cond, gpointer data);
151static gboolean io_conn_ind(GIOChannel *chan, GIOCondition cond, gpointer data);
152static gboolean io_hci_data(GIOChannel *chan, GIOCondition cond, gpointer data);
153
154static inline int read_n(int fd, void *buf, int len)
155{
156	register int w, t = 0;
157
158	while (!__io_canceled && len > 0) {
159		if ((w = read(fd, buf, len)) < 0 ){
160			if( errno == EINTR || errno == EAGAIN )
161				continue;
162			return -1;
163		}
164		if (!w)
165			return 0;
166		len -= w; buf += w; t += w;
167	}
168	return t;
169}
170
171/* Write exactly len bytes (Signal safe)*/
172static inline int write_n(int fd, void *buf, int len)
173{
174	register int w, t = 0;
175
176	while (!__io_canceled && len > 0) {
177		if ((w = write(fd, buf, len)) < 0 ){
178			if( errno == EINTR || errno == EAGAIN )
179				continue;
180			return -1;
181		}
182		if (!w)
183			return 0;
184		len -= w; buf += w; t += w;
185	}
186	return t;
187}
188
189static int create_snoop(char *file)
190{
191	struct btsnoop_hdr hdr;
192	int fd, len;
193
194	fd = open(file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
195	if (fd < 0)
196		return fd;
197
198	memcpy(hdr.id, btsnoop_id, sizeof(btsnoop_id));
199	hdr.version = htonl(1);
200	hdr.type = htonl(1002);
201
202	len = write(fd, &hdr, BTSNOOP_HDR_SIZE);
203	if (len < 0) {
204		close(fd);
205		return -EIO;
206	}
207
208	if (len != BTSNOOP_HDR_SIZE) {
209		close(fd);
210		return -1;
211	}
212
213	return fd;
214}
215
216static int write_snoop(int fd, int type, int incoming, unsigned char *buf, int len)
217{
218	struct btsnoop_pkt pkt;
219	struct timeval tv;
220	uint32_t size = len;
221	uint64_t ts;
222	int err;
223
224	if (fd < 0)
225		return -1;
226
227	memset(&tv, 0, sizeof(tv));
228	gettimeofday(&tv, NULL);
229	ts = (tv.tv_sec - 946684800ll) * 1000000ll + tv.tv_usec;
230
231	pkt.size = htonl(size);
232	pkt.len  = pkt.size;
233	pkt.flags = ntohl(incoming & 0x01);
234	pkt.drops = htonl(0);
235	pkt.ts = hton64(ts + 0x00E03AB44A676000ll);
236
237	if (type == HCI_COMMAND_PKT || type == HCI_EVENT_PKT)
238		pkt.flags |= ntohl(0x02);
239
240	err = write(fd, &pkt, BTSNOOP_PKT_SIZE);
241	err = write(fd, buf, size);
242
243	return 0;
244}
245
246static struct vhci_conn *conn_get_by_bdaddr(bdaddr_t *ba)
247{
248	register int i;
249
250	for (i = 0; i < VHCI_MAX_CONN; i++)
251		if (!bacmp(&vconn[i]->dest, ba))
252			return vconn[i];
253
254	return NULL;
255}
256
257static void command_status(uint16_t ogf, uint16_t ocf, uint8_t status)
258{
259	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
260	evt_cmd_status *cs;
261	hci_event_hdr *he;
262
263	/* Packet type */
264	*ptr++ = HCI_EVENT_PKT;
265
266	/* Event header */
267	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
268
269	he->evt  = EVT_CMD_STATUS;
270	he->plen = EVT_CMD_STATUS_SIZE;
271
272	cs = (void *) ptr; ptr += EVT_CMD_STATUS_SIZE;
273
274	cs->status = status;
275	cs->ncmd   = 1;
276	cs->opcode = htobs(cmd_opcode_pack(ogf, ocf));
277
278	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
279
280	if (write(vdev.fd, buf, ptr - buf) < 0)
281		syslog(LOG_ERR, "Can't send event: %s(%d)",
282						strerror(errno), errno);
283}
284
285static void command_complete(uint16_t ogf, uint16_t ocf, int plen, void *data)
286{
287	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
288	evt_cmd_complete *cc;
289	hci_event_hdr *he;
290
291	/* Packet type */
292	*ptr++ = HCI_EVENT_PKT;
293
294	/* Event header */
295	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
296
297	he->evt  = EVT_CMD_COMPLETE;
298	he->plen = EVT_CMD_COMPLETE_SIZE + plen;
299
300	cc = (void *) ptr; ptr += EVT_CMD_COMPLETE_SIZE;
301
302	cc->ncmd = 1;
303	cc->opcode = htobs(cmd_opcode_pack(ogf, ocf));
304
305	if (plen) {
306		memcpy(ptr, data, plen);
307		ptr += plen;
308	}
309
310	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
311
312	if (write(vdev.fd, buf, ptr - buf) < 0)
313		syslog(LOG_ERR, "Can't send event: %s(%d)",
314						strerror(errno), errno);
315}
316
317static void connect_request(struct vhci_conn *conn)
318{
319	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
320	evt_conn_request *cr;
321	hci_event_hdr *he;
322
323	/* Packet type */
324	*ptr++ = HCI_EVENT_PKT;
325
326	/* Event header */
327	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
328
329	he->evt  = EVT_CONN_REQUEST;
330	he->plen = EVT_CONN_REQUEST_SIZE;
331
332	cr = (void *) ptr; ptr += EVT_CONN_REQUEST_SIZE;
333
334	bacpy(&cr->bdaddr, &conn->dest);
335	memset(&cr->dev_class, 0, sizeof(cr->dev_class));
336	cr->link_type = ACL_LINK;
337
338	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
339
340	if (write(vdev.fd, buf, ptr - buf) < 0)
341		syslog(LOG_ERR, "Can't send event: %s (%d)",
342						strerror(errno), errno);
343}
344
345static void connect_complete(struct vhci_conn *conn)
346{
347	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
348	evt_conn_complete *cc;
349	hci_event_hdr *he;
350
351	/* Packet type */
352	*ptr++ = HCI_EVENT_PKT;
353
354	/* Event header */
355	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
356
357	he->evt  = EVT_CONN_COMPLETE;
358	he->plen = EVT_CONN_COMPLETE_SIZE;
359
360	cc = (void *) ptr; ptr += EVT_CONN_COMPLETE_SIZE;
361
362	bacpy(&cc->bdaddr, &conn->dest);
363	cc->status = 0x00;
364	cc->handle = htobs(conn->handle);
365	cc->link_type = ACL_LINK;
366	cc->encr_mode = 0x00;
367
368	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
369
370	if (write(vdev.fd, buf, ptr - buf) < 0)
371		syslog(LOG_ERR, "Can't send event: %s (%d)",
372						strerror(errno), errno);
373}
374
375static void disconn_complete(struct vhci_conn *conn)
376{
377	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
378	evt_disconn_complete *dc;
379	hci_event_hdr *he;
380
381	/* Packet type */
382	*ptr++ = HCI_EVENT_PKT;
383
384	/* Event header */
385	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
386
387	he->evt  = EVT_DISCONN_COMPLETE;
388	he->plen = EVT_DISCONN_COMPLETE_SIZE;
389
390	dc = (void *) ptr; ptr += EVT_DISCONN_COMPLETE_SIZE;
391
392	dc->status = 0x00;
393	dc->handle = htobs(conn->handle);
394	dc->reason = 0x00;
395
396	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
397
398	if (write(vdev.fd, buf, ptr - buf) < 0)
399		syslog(LOG_ERR, "Can't send event: %s (%d)",
400						strerror(errno), errno);
401
402	vdev.acl_cnt = 0;
403}
404
405static void num_completed_pkts(struct vhci_conn *conn)
406{
407	uint8_t buf[HCI_MAX_FRAME_SIZE], *ptr = buf;
408	evt_num_comp_pkts *np;
409	hci_event_hdr *he;
410
411	/* Packet type */
412	*ptr++ = HCI_EVENT_PKT;
413
414	/* Event header */
415	he = (void *) ptr; ptr += HCI_EVENT_HDR_SIZE;
416
417	he->evt  = EVT_NUM_COMP_PKTS;
418	he->plen = EVT_NUM_COMP_PKTS_SIZE;
419
420	np = (void *) ptr; ptr += EVT_NUM_COMP_PKTS_SIZE;
421	np->num_hndl = 1;
422
423	*((uint16_t *) ptr) = htobs(conn->handle); ptr += 2;
424	*((uint16_t *) ptr) = htobs(vdev.acl_cnt); ptr += 2;
425
426	write_snoop(vdev.dd, HCI_EVENT_PKT, 1, buf, ptr - buf);
427
428	if (write(vdev.fd, buf, ptr - buf) < 0)
429		syslog(LOG_ERR, "Can't send event: %s (%d)",
430						strerror(errno), errno);
431}
432
433static int scan_enable(uint8_t *data)
434{
435	struct sockaddr_in sa;
436	GIOChannel *sk_io;
437	bdaddr_t ba;
438	int sk, opt;
439
440	if (!(*data & SCAN_PAGE)) {
441		if (vdev.scan) {
442			g_io_channel_close(vdev.scan);
443			vdev.scan = NULL;
444		}
445		return 0;
446	}
447
448	if (vdev.scan)
449		return 0;
450
451	if ((sk = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
452		syslog(LOG_ERR, "Can't create socket: %s (%d)",
453						strerror(errno), errno);
454		return 1;
455	}
456
457	opt = 1;
458	setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
459
460	baswap(&ba, &vdev.bdaddr);
461	sa.sin_family = AF_INET;
462	sa.sin_addr.s_addr = *(uint32_t *) &ba;
463	sa.sin_port = *(uint16_t *) &ba.b[4];
464	if (bind(sk, (struct sockaddr *) &sa, sizeof(sa))) {
465		syslog(LOG_ERR, "Can't bind socket: %s (%d)",
466						strerror(errno), errno);
467		goto failed;
468	}
469
470	if (listen(sk, 10)) {
471		syslog(LOG_ERR, "Can't listen on socket: %s (%d)",
472						strerror(errno), errno);
473		goto failed;
474	}
475
476	sk_io = g_io_channel_unix_new(sk);
477	g_io_add_watch(sk_io, G_IO_IN | G_IO_NVAL, io_conn_ind, NULL);
478	vdev.scan = sk_io;
479	return 0;
480
481failed:
482	close(sk);
483	return 1;
484}
485
486static void accept_connection(uint8_t *data)
487{
488	accept_conn_req_cp *cp = (void *) data;
489	struct vhci_conn *conn;
490
491	if (!(conn = conn_get_by_bdaddr(&cp->bdaddr)))
492		return;
493
494	connect_complete(conn);
495
496	g_io_add_watch(conn->chan, G_IO_IN | G_IO_NVAL | G_IO_HUP,
497			io_acl_data, (gpointer) conn);
498}
499
500static void close_connection(struct vhci_conn *conn)
501{
502	syslog(LOG_INFO, "Closing connection %s handle %d",
503					batostr(&conn->dest), conn->handle);
504
505	g_io_channel_close(conn->chan);
506	g_io_channel_unref(conn->chan);
507
508	vconn[conn->handle - 1] = NULL;
509	disconn_complete(conn);
510	free(conn);
511}
512
513static void disconnect(uint8_t *data)
514{
515	disconnect_cp *cp = (void *) data;
516	struct vhci_conn *conn;
517	uint16_t handle;
518
519	handle = btohs(cp->handle);
520
521	if (handle - 1 > VHCI_MAX_CONN)
522		return;
523
524	if (!(conn = vconn[handle-1]))
525		return;
526
527	close_connection(conn);
528}
529
530static void create_connection(uint8_t *data)
531{
532	create_conn_cp *cp = (void *) data;
533	struct vhci_link_info info;
534	struct vhci_conn *conn;
535	struct sockaddr_in sa;
536	int h, sk, opt;
537	bdaddr_t ba;
538
539	for (h = 0; h < VHCI_MAX_CONN; h++)
540		if (!vconn[h])
541			goto do_connect;
542
543	syslog(LOG_ERR, "Too many connections");
544	return;
545
546do_connect:
547	if ((sk = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
548		syslog(LOG_ERR, "Can't create socket: %s (%d)",
549						strerror(errno), errno);
550		return;
551	}
552
553	opt = 1;
554	setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
555
556	baswap(&ba, &vdev.bdaddr);
557	sa.sin_family = AF_INET;
558	sa.sin_addr.s_addr = INADDR_ANY;	// *(uint32_t *) &ba;
559	sa.sin_port = 0;			// *(uint16_t *) &ba.b[4];
560	if (bind(sk, (struct sockaddr *) &sa, sizeof(sa))) {
561		syslog(LOG_ERR, "Can't bind socket: %s (%d)",
562						strerror(errno), errno);
563		close(sk);
564		return;
565	}
566
567	baswap(&ba, &cp->bdaddr);
568	sa.sin_family = AF_INET;
569	sa.sin_addr.s_addr = *(uint32_t *) &ba;
570	sa.sin_port = *(uint16_t *) &ba.b[4];
571	if (connect(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
572		syslog(LOG_ERR, "Can't connect: %s (%d)",
573						strerror(errno), errno);
574		close(sk);
575		return;
576	}
577
578	/* Send info */
579	memset(&info, 0, sizeof(info));
580	bacpy(&info.bdaddr, &vdev.bdaddr);
581	info.link_type = ACL_LINK;
582	info.role = 1;
583	write_n(sk, (void *) &info, sizeof(info));
584
585	if (!(conn = malloc(sizeof(*conn)))) {
586		syslog(LOG_ERR, "Can't alloc new connection: %s (%d)",
587						strerror(errno), errno);
588		close(sk);
589		return;
590	}
591
592	memcpy((uint8_t *) &ba, (uint8_t *) &sa.sin_addr, 4);
593	memcpy((uint8_t *) &ba.b[4], (uint8_t *) &sa.sin_port, 2);
594	baswap(&conn->dest, &ba);
595
596	vconn[h] = conn;
597	conn->handle = h + 1;
598	conn->chan = g_io_channel_unix_new(sk);
599
600	connect_complete(conn);
601	g_io_add_watch(conn->chan, G_IO_IN | G_IO_NVAL | G_IO_HUP,
602				io_acl_data, (gpointer) conn);
603	return;
604}
605
606static void inline hci_link_control(uint16_t ocf, int plen, uint8_t *data)
607{
608	uint8_t status;
609
610	const uint16_t ogf = OGF_LINK_CTL;
611
612	switch (ocf) {
613	case OCF_CREATE_CONN:
614		command_status(ogf, ocf, 0x00);
615		create_connection(data);
616		break;
617
618	case OCF_ACCEPT_CONN_REQ:
619		command_status(ogf, ocf, 0x00);
620		accept_connection(data);
621		break;
622
623	case OCF_DISCONNECT:
624		command_status(ogf, ocf, 0x00);
625		disconnect(data);
626		break;
627
628	default:
629		status = 0x01;
630		command_complete(ogf, ocf, 1, &status);
631		break;
632	}
633}
634
635static void inline hci_link_policy(uint16_t ocf, int plen, uint8_t *data)
636{
637	uint8_t status;
638
639	const uint16_t ogf = OGF_INFO_PARAM;
640
641	switch (ocf) {
642	default:
643		status = 0x01;
644		command_complete(ogf, ocf, 1, &status);
645		break;
646	}
647}
648
649static void inline hci_host_control(uint16_t ocf, int plen, uint8_t *data)
650{
651	read_local_name_rp ln;
652	read_class_of_dev_rp cd;
653	read_inquiry_mode_rp im;
654	read_ext_inquiry_response_rp ir;
655	uint8_t status;
656
657	const uint16_t ogf = OGF_HOST_CTL;
658
659	switch (ocf) {
660	case OCF_RESET:
661		status = 0x00;
662		command_complete(ogf, ocf, 1, &status);
663		break;
664
665	case OCF_SET_EVENT_FLT:
666		status = 0x00;
667		command_complete(ogf, ocf, 1, &status);
668		break;
669
670	case OCF_CHANGE_LOCAL_NAME:
671		status = 0x00;
672		memcpy(vdev.name, data, sizeof(vdev.name));
673		command_complete(ogf, ocf, 1, &status);
674		break;
675
676	case OCF_READ_LOCAL_NAME:
677		ln.status = 0x00;
678		memcpy(ln.name, vdev.name, sizeof(ln.name));
679		command_complete(ogf, ocf, sizeof(ln), &ln);
680		break;
681
682	case OCF_WRITE_CONN_ACCEPT_TIMEOUT:
683	case OCF_WRITE_PAGE_TIMEOUT:
684		status = 0x00;
685		command_complete(ogf, ocf, 1, &status);
686		break;
687
688	case OCF_WRITE_SCAN_ENABLE:
689		status = scan_enable(data);
690		command_complete(ogf, ocf, 1, &status);
691		break;
692
693	case OCF_WRITE_AUTH_ENABLE:
694		status = 0x00;
695		command_complete(ogf, ocf, 1, &status);
696		break;
697
698	case OCF_WRITE_ENCRYPT_MODE:
699		status = 0x00;
700		command_complete(ogf, ocf, 1, &status);
701		break;
702
703	case OCF_READ_CLASS_OF_DEV:
704		cd.status = 0x00;
705		memcpy(cd.dev_class, vdev.dev_class, 3);
706		command_complete(ogf, ocf, sizeof(cd), &cd);
707		break;
708
709	case OCF_WRITE_CLASS_OF_DEV:
710		status = 0x00;
711		memcpy(vdev.dev_class, data, 3);
712		command_complete(ogf, ocf, 1, &status);
713		break;
714
715	case OCF_READ_INQUIRY_MODE:
716		im.status = 0x00;
717		im.mode = vdev.inq_mode;
718		command_complete(ogf, ocf, sizeof(im), &im);
719		break;
720
721	case OCF_WRITE_INQUIRY_MODE:
722		status = 0x00;
723		vdev.inq_mode = data[0];
724		command_complete(ogf, ocf, 1, &status);
725		break;
726
727	case OCF_READ_EXT_INQUIRY_RESPONSE:
728		ir.status = 0x00;
729		ir.fec = vdev.eir_fec;
730		memcpy(ir.data, vdev.eir_data, 240);
731		command_complete(ogf, ocf, sizeof(ir), &ir);
732		break;
733
734	case OCF_WRITE_EXT_INQUIRY_RESPONSE:
735		status = 0x00;
736		vdev.eir_fec = data[0];
737		memcpy(vdev.eir_data, data + 1, 240);
738		command_complete(ogf, ocf, 1, &status);
739		break;
740
741	default:
742		status = 0x01;
743		command_complete(ogf, ocf, 1, &status);
744		break;
745	}
746}
747
748static void inline hci_info_param(uint16_t ocf, int plen, uint8_t *data)
749{
750	read_local_version_rp lv;
751	read_local_features_rp lf;
752	read_local_ext_features_rp ef;
753	read_buffer_size_rp bs;
754	read_bd_addr_rp ba;
755	uint8_t status;
756
757	const uint16_t ogf = OGF_INFO_PARAM;
758
759	switch (ocf) {
760	case OCF_READ_LOCAL_VERSION:
761		lv.status = 0x00;
762		lv.hci_ver = 0x03;
763		lv.hci_rev = htobs(0x0000);
764		lv.lmp_ver = 0x03;
765		lv.manufacturer = htobs(29);
766		lv.lmp_subver = htobs(0x0000);
767		command_complete(ogf, ocf, sizeof(lv), &lv);
768		break;
769
770	case OCF_READ_LOCAL_FEATURES:
771		lf.status = 0x00;
772		memcpy(lf.features, vdev.features, 8);
773		command_complete(ogf, ocf, sizeof(lf), &lf);
774		break;
775
776	case OCF_READ_LOCAL_EXT_FEATURES:
777		ef.status = 0x00;
778		if (*data == 0) {
779			ef.page_num = 0;
780			ef.max_page_num = 0;
781			memcpy(ef.features, vdev.features, 8);
782		} else {
783			ef.page_num = *data;
784			ef.max_page_num = 0;
785			memset(ef.features, 0, 8);
786		}
787		command_complete(ogf, ocf, sizeof(ef), &ef);
788		break;
789
790	case OCF_READ_BUFFER_SIZE:
791		bs.status = 0x00;
792		bs.acl_mtu = htobs(VHCI_ACL_MTU);
793		bs.sco_mtu = 0;
794		bs.acl_max_pkt = htobs(VHCI_ACL_MAX_PKT);
795		bs.sco_max_pkt = htobs(0);
796		command_complete(ogf, ocf, sizeof(bs), &bs);
797		break;
798
799	case OCF_READ_BD_ADDR:
800		ba.status = 0x00;
801		bacpy(&ba.bdaddr, &vdev.bdaddr);
802		command_complete(ogf, ocf, sizeof(ba), &ba);
803		break;
804
805	default:
806		status = 0x01;
807		command_complete(ogf, ocf, 1, &status);
808		break;
809	}
810}
811
812static void hci_command(uint8_t *data)
813{
814	hci_command_hdr *ch;
815	uint8_t *ptr = data;
816	uint16_t ogf, ocf;
817
818	ch = (hci_command_hdr *) ptr;
819	ptr += HCI_COMMAND_HDR_SIZE;
820
821	ch->opcode = btohs(ch->opcode);
822	ogf = cmd_opcode_ogf(ch->opcode);
823	ocf = cmd_opcode_ocf(ch->opcode);
824
825	switch (ogf) {
826	case OGF_LINK_CTL:
827		hci_link_control(ocf, ch->plen, ptr);
828		break;
829
830	case OGF_LINK_POLICY:
831		hci_link_policy(ocf, ch->plen, ptr);
832		break;
833
834	case OGF_HOST_CTL:
835		hci_host_control(ocf, ch->plen, ptr);
836		break;
837
838	case OGF_INFO_PARAM:
839		hci_info_param(ocf, ch->plen, ptr);
840		break;
841	}
842}
843
844static void hci_acl_data(uint8_t *data)
845{
846	hci_acl_hdr *ah = (void *) data;
847	struct vhci_conn *conn;
848	uint16_t handle;
849	int fd;
850
851	handle = acl_handle(btohs(ah->handle));
852
853	if (handle > VHCI_MAX_CONN || !(conn = vconn[handle - 1])) {
854		syslog(LOG_ERR, "Bad connection handle %d", handle);
855		return;
856	}
857
858	fd = g_io_channel_unix_get_fd(conn->chan);
859	if (write_n(fd, data, btohs(ah->dlen) + HCI_ACL_HDR_SIZE) < 0) {
860		close_connection(conn);
861		return;
862	}
863
864	if (++vdev.acl_cnt > VHCI_ACL_MAX_PKT - 1) {
865		/* Send num of complete packets event */
866		num_completed_pkts(conn);
867		vdev.acl_cnt = 0;
868	}
869}
870
871static gboolean io_acl_data(GIOChannel *chan, GIOCondition cond, gpointer data)
872{
873	struct vhci_conn *conn = (struct vhci_conn *) data;
874	unsigned char buf[HCI_MAX_FRAME_SIZE], *ptr;
875	hci_acl_hdr *ah;
876	uint16_t flags;
877	int fd, err, len;
878
879	if (cond & G_IO_NVAL) {
880		g_io_channel_unref(chan);
881		return FALSE;
882	}
883
884	if (cond & G_IO_HUP) {
885		close_connection(conn);
886		return FALSE;
887	}
888
889	fd = g_io_channel_unix_get_fd(chan);
890
891	ptr = buf + 1;
892	if (read_n(fd, ptr, HCI_ACL_HDR_SIZE) <= 0) {
893		close_connection(conn);
894		return FALSE;
895	}
896
897	ah = (void *) ptr;
898	ptr += HCI_ACL_HDR_SIZE;
899
900	len = btohs(ah->dlen);
901	if (read_n(fd, ptr, len) <= 0) {
902		close_connection(conn);
903		return FALSE;
904	}
905
906	buf[0] = HCI_ACLDATA_PKT;
907
908	flags = acl_flags(btohs(ah->handle));
909	ah->handle = htobs(acl_handle_pack(conn->handle, flags));
910	len += HCI_ACL_HDR_SIZE + 1;
911
912	write_snoop(vdev.dd, HCI_ACLDATA_PKT, 1, buf, len);
913
914	err = write(vdev.fd, buf, len);
915
916	return TRUE;
917}
918
919static gboolean io_conn_ind(GIOChannel *chan, GIOCondition cond, gpointer data)
920{
921	struct vhci_link_info info;
922	struct vhci_conn *conn;
923	struct sockaddr_in sa;
924	socklen_t len;
925	int sk, nsk, h;
926
927	if (cond & G_IO_NVAL)
928		return FALSE;
929
930	sk = g_io_channel_unix_get_fd(chan);
931
932	len = sizeof(sa);
933	if ((nsk = accept(sk, (struct sockaddr *) &sa, &len)) < 0)
934		return TRUE;
935
936	if (read_n(nsk, &info, sizeof(info)) < 0) {
937		syslog(LOG_ERR, "Can't read link info");
938		return TRUE;
939	}
940
941	if (!(conn = malloc(sizeof(*conn)))) {
942		syslog(LOG_ERR, "Can't alloc new connection");
943		close(nsk);
944		return TRUE;
945	}
946
947	bacpy(&conn->dest, &info.bdaddr);
948
949	for (h = 0; h < VHCI_MAX_CONN; h++)
950		if (!vconn[h])
951			goto accepted;
952
953	syslog(LOG_ERR, "Too many connections");
954	free(conn);
955	close(nsk);
956	return TRUE;
957
958accepted:
959	vconn[h] = conn;
960	conn->handle = h + 1;
961	conn->chan = g_io_channel_unix_new(nsk);
962	connect_request(conn);
963
964	return TRUE;
965}
966
967static gboolean io_hci_data(GIOChannel *chan, GIOCondition cond, gpointer data)
968{
969	unsigned char buf[HCI_MAX_FRAME_SIZE], *ptr;
970	int type;
971	gsize len;
972	GIOError err;
973
974	ptr = buf;
975
976	if ((err = g_io_channel_read(chan, (gchar *) buf, sizeof(buf), &len))) {
977		if (err == G_IO_ERROR_AGAIN)
978			return TRUE;
979
980		syslog(LOG_ERR, "Read failed: %s (%d)", strerror(errno), errno);
981		g_io_channel_unref(chan);
982		g_main_quit(event_loop);
983		return FALSE;
984	}
985
986	type = *ptr++;
987
988	write_snoop(vdev.dd, type, 0, buf, len);
989
990	switch (type) {
991	case HCI_COMMAND_PKT:
992		hci_command(ptr);
993		break;
994
995	case HCI_ACLDATA_PKT:
996		hci_acl_data(ptr);
997		break;
998
999	default:
1000		syslog(LOG_ERR, "Unknown packet type 0x%2.2x", type);
1001		break;
1002	}
1003
1004	return TRUE;
1005}
1006
1007static int getbdaddrbyname(char *str, bdaddr_t *ba)
1008{
1009	int i, n, len;
1010
1011	len = strlen(str);
1012
1013	/* Check address format */
1014	for (i = 0, n = 0; i < len; i++)
1015		if (str[i] == ':')
1016			n++;
1017
1018	if (n == 5) {
1019		/* BD address */
1020		baswap(ba, strtoba(str));
1021		return 0;
1022	}
1023
1024	if (n == 1) {
1025		/* IP address + port */
1026		struct hostent *hent;
1027		bdaddr_t b;
1028		char *ptr;
1029
1030		ptr = strchr(str, ':');
1031		*ptr++ = 0;
1032
1033		if (!(hent = gethostbyname(str))) {
1034			fprintf(stderr, "Can't resolve %s\n", str);
1035			return -2;
1036		}
1037
1038		memcpy(&b, hent->h_addr, 4);
1039		*(uint16_t *) (&b.b[4]) = htons(atoi(ptr));
1040		baswap(ba, &b);
1041
1042		return 0;
1043	}
1044
1045	fprintf(stderr, "Invalid address format\n");
1046
1047	return -1;
1048}
1049
1050static void rewrite_bdaddr(unsigned char *buf, int len, bdaddr_t *bdaddr)
1051{
1052	hci_event_hdr *eh;
1053	unsigned char *ptr = buf;
1054	int type;
1055
1056	if (!bdaddr)
1057		return;
1058
1059	if (!bacmp(bdaddr, BDADDR_ANY))
1060		return;
1061
1062	type = *ptr++;
1063
1064	switch (type) {
1065	case HCI_EVENT_PKT:
1066		eh = (hci_event_hdr *) ptr;
1067		ptr += HCI_EVENT_HDR_SIZE;
1068
1069		if (eh->evt == EVT_CMD_COMPLETE) {
1070			evt_cmd_complete *cc = (void *) ptr;
1071
1072			ptr += EVT_CMD_COMPLETE_SIZE;
1073
1074			if (cc->opcode == htobs(cmd_opcode_pack(OGF_INFO_PARAM,
1075						OCF_READ_BD_ADDR))) {
1076				bacpy((bdaddr_t *) (ptr + 1), bdaddr);
1077			}
1078		}
1079		break;
1080	}
1081}
1082
1083static int run_proxy(int fd, int dev, bdaddr_t *bdaddr)
1084{
1085	unsigned char buf[HCI_MAX_FRAME_SIZE + 1];
1086	struct hci_dev_info di;
1087	struct hci_filter flt;
1088	struct pollfd p[2];
1089	int dd, err, len, need_raw;
1090
1091	dd = hci_open_dev(dev);
1092	if (dd < 0) {
1093		syslog(LOG_ERR, "Can't open device hci%d: %s (%d)",
1094						dev, strerror(errno), errno);
1095		return 1;
1096	}
1097
1098	if (hci_devinfo(dev, &di) < 0) {
1099		syslog(LOG_ERR, "Can't get device info for hci%d: %s (%d)",
1100						dev, strerror(errno), errno);
1101		hci_close_dev(dd);
1102		return 1;
1103	}
1104
1105	need_raw = !hci_test_bit(HCI_RAW, &di.flags);
1106
1107	hci_filter_clear(&flt);
1108	hci_filter_all_ptypes(&flt);
1109	hci_filter_all_events(&flt);
1110
1111	if (setsockopt(dd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
1112		syslog(LOG_ERR, "Can't set filter for hci%d: %s (%d)",
1113						dev, strerror(errno), errno);
1114		hci_close_dev(dd);
1115		return 1;
1116	}
1117
1118	if (need_raw) {
1119		if (ioctl(dd, HCISETRAW, 1) < 0) {
1120			syslog(LOG_ERR, "Can't set raw mode on hci%d: %s (%d)",
1121						dev, strerror(errno), errno);
1122			hci_close_dev(dd);
1123			return 1;
1124		}
1125	}
1126
1127	p[0].fd = fd;
1128	p[0].events = POLLIN;
1129	p[1].fd = dd;
1130	p[1].events = POLLIN;
1131
1132	while (!__io_canceled) {
1133		p[0].revents = 0;
1134		p[1].revents = 0;
1135		err = poll(p, 2, 500);
1136		if (err < 0)
1137			break;
1138		if (!err)
1139			continue;
1140
1141		if (p[0].revents & POLLIN) {
1142			len = read(fd, buf, sizeof(buf));
1143			if (len > 0) {
1144				rewrite_bdaddr(buf, len, bdaddr);
1145				err = write(dd, buf, len);
1146			}
1147		}
1148
1149		if (p[1].revents & POLLIN) {
1150			len = read(dd, buf, sizeof(buf));
1151			if (len > 0) {
1152				rewrite_bdaddr(buf, len, bdaddr);
1153				err = write(fd, buf, len);
1154			}
1155		}
1156	}
1157
1158	if (need_raw) {
1159		if (ioctl(dd, HCISETRAW, 0) < 0)
1160			syslog(LOG_ERR, "Can't clear raw mode on hci%d: %s (%d)",
1161						dev, strerror(errno), errno);
1162	}
1163
1164	hci_close_dev(dd);
1165
1166	syslog(LOG_INFO, "Exit");
1167
1168	return 0;
1169}
1170
1171static void usage(void)
1172{
1173	printf("hciemu - HCI emulator ver %s\n", VERSION);
1174	printf("Usage: \n");
1175	printf("\thciemu [-n] local_address\n");
1176}
1177
1178static struct option main_options[] = {
1179	{ "device",	1, 0, 'd' },
1180	{ "bdaddr",	1, 0, 'b' },
1181	{ "snoop",	1, 0, 's' },
1182	{ "nodetach",	0, 0, 'n' },
1183	{ "help",	0, 0, 'h' },
1184	{ 0 }
1185};
1186
1187int main(int argc, char *argv[])
1188{
1189	struct sigaction sa;
1190	GIOChannel *dev_io;
1191	char *device = NULL, *snoop = NULL;
1192	bdaddr_t bdaddr;
1193	int fd, dd, opt, detach = 1, dev = -1;
1194
1195	bacpy(&bdaddr, BDADDR_ANY);
1196
1197	while ((opt=getopt_long(argc, argv, "d:b:s:nh", main_options, NULL)) != EOF) {
1198		switch(opt) {
1199		case 'd':
1200			device = strdup(optarg);
1201			break;
1202
1203		case 'b':
1204			str2ba(optarg, &bdaddr);
1205			break;
1206
1207		case 's':
1208			snoop = strdup(optarg);
1209			break;
1210
1211		case 'n':
1212			detach = 0;
1213			break;
1214
1215		case 'h':
1216		default:
1217			usage();
1218			exit(0);
1219		}
1220	}
1221
1222	argc -= optind;
1223	argv += optind;
1224	optind = 0;
1225
1226	if (argc < 1) {
1227		usage();
1228		exit(1);
1229	}
1230
1231	if (strlen(argv[0]) > 3 && !strncasecmp(argv[0], "hci", 3)) {
1232		dev = hci_devid(argv[0]);
1233		if (dev < 0) {
1234			perror("Invalid device");
1235			exit(1);
1236		}
1237	} else {
1238		if (getbdaddrbyname(argv[0], &vdev.bdaddr) < 0)
1239			exit(1);
1240	}
1241
1242	if (detach) {
1243		if (daemon(0, 0)) {
1244			perror("Can't start daemon");
1245			exit(1);
1246		}
1247	}
1248
1249	/* Start logging to syslog and stderr */
1250	openlog("hciemu", LOG_PID | LOG_NDELAY | LOG_PERROR, LOG_DAEMON);
1251	syslog(LOG_INFO, "HCI emulation daemon ver %s started", VERSION);
1252
1253	memset(&sa, 0, sizeof(sa));
1254	sa.sa_flags   = SA_NOCLDSTOP;
1255	sa.sa_handler = SIG_IGN;
1256	sigaction(SIGCHLD, &sa, NULL);
1257	sigaction(SIGPIPE, &sa, NULL);
1258
1259	sa.sa_handler = sig_term;
1260	sigaction(SIGTERM, &sa, NULL);
1261	sigaction(SIGINT,  &sa, NULL);
1262
1263	io_init();
1264
1265	if (!device && dev >= 0)
1266		device = strdup(GHCI_DEV);
1267
1268	/* Open and create virtual HCI device */
1269	if (device) {
1270		fd = open(device, O_RDWR);
1271		if (fd < 0) {
1272			syslog(LOG_ERR, "Can't open device %s: %s (%d)",
1273						device, strerror(errno), errno);
1274			free(device);
1275			exit(1);
1276		}
1277		free(device);
1278	} else {
1279		fd = open(VHCI_DEV, O_RDWR);
1280		if (fd < 0) {
1281			fd = open(VHCI_UDEV, O_RDWR);
1282			if (fd < 0) {
1283				syslog(LOG_ERR, "Can't open device %s: %s (%d)",
1284						VHCI_DEV, strerror(errno), errno);
1285				exit(1);
1286			}
1287		}
1288	}
1289
1290	/* Create snoop file */
1291	if (snoop) {
1292		dd = create_snoop(snoop);
1293		if (dd < 0)
1294			syslog(LOG_ERR, "Can't create snoop file %s: %s (%d)",
1295						snoop, strerror(errno), errno);
1296		free(snoop);
1297	} else
1298		dd = -1;
1299
1300	/* Create event loop */
1301	event_loop = g_main_new(FALSE);
1302
1303	if (dev >= 0)
1304		return run_proxy(fd, dev, &bdaddr);
1305
1306	/* Device settings */
1307	vdev.features[0] = 0xff;
1308	vdev.features[1] = 0xff;
1309	vdev.features[2] = 0x8f;
1310	vdev.features[3] = 0xfe;
1311	vdev.features[4] = 0x9b;
1312	vdev.features[5] = 0xf9;
1313	vdev.features[6] = 0x01;
1314	vdev.features[7] = 0x80;
1315
1316	memset(vdev.name, 0, sizeof(vdev.name));
1317	strncpy((char *) vdev.name, "BlueZ (Virtual HCI)", sizeof(vdev.name));
1318
1319	vdev.dev_class[0] = 0x00;
1320	vdev.dev_class[1] = 0x00;
1321	vdev.dev_class[2] = 0x00;
1322
1323	vdev.inq_mode = 0x00;
1324	vdev.eir_fec = 0x00;
1325	memset(vdev.eir_data, 0, sizeof(vdev.eir_data));
1326
1327	vdev.fd = fd;
1328	vdev.dd = dd;
1329
1330	dev_io = g_io_channel_unix_new(fd);
1331	g_io_add_watch(dev_io, G_IO_IN, io_hci_data, NULL);
1332
1333	setpriority(PRIO_PROCESS, 0, -19);
1334
1335	/* Start event processor */
1336	g_main_run(event_loop);
1337
1338	close(fd);
1339
1340	if (dd >= 0)
1341		close(dd);
1342
1343	syslog(LOG_INFO, "Exit");
1344
1345	return 0;
1346}
1347