Debian Codegraph @

bluetooth-monitor.c

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /*
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License version 2 as
5 * published by the Free Software Foundation;
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
10 * IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
11 * CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 *
16 * ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
17 * COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
18 * SOFTWARE IS DISCLAIMED.
19 *
20 */
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <string.h>
30 #include <signal.h>
31 #include <fcntl.h>
32 #include <errno.h>
33 #include <ctype.h>
34 #include <syslog.h>
35 #include <stdarg.h>
36
37 #include <termios.h>
38 #include <fcntl.h>
39 #include <getopt.h>
40 #include <sys/types.h>
41 #include <sys/ioctl.h>
42
43 #include <bluetooth/bluetooth.h>
44 #include <bluetooth/hci.h>
45 #include <bluetooth/hci_lib.h>
46
47 #define DBUS_API_SUBJECT_TO_CHANGE
48 #include <dbus/dbus.h>
49 #include <stdbool.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53
54 #define BTCONNECTTIMEOUT 5000
55 #define DEFAULTTHRESHOLD 200
56 #define DEFAULTINTERVAL 100
57 //#define DEBUG
58
59 #define DBUS_INTROSPECTION_DATA "<!DOCTYPE node PUBLIC \
60 \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\" \
61 \"http://dbus.freedesktop.org/doc/introspect.dtd\"> \n\
62 <node name=\"/cx/ath/matthew/bluemon/Bluemon\">\n\
63 <interface name=\"cx.ath.matthew.bluemon.Bluemon\">\n\
64 <method name=\"Status\" >\n\
65 <arg name=\"address\" type=\"s\" direction=\"in\"/>\n\
66 <arg name=\"address\" type=\"s\" direction=\"out\"/>\n\
67 <arg name=\"status\" type=\"b\" direction=\"out\"/>\n\
68 <arg name=\"level\" type=\"u\" direction=\"out\"/>\n\
69 </method>\n\
70 </interface>\n\
71 <interface name=\"cx.ath.matthew.bluemon.ProximitySignal\">\n\
72 <signal name=\"Connect\" >\n\
73 <arg name=\"address\" type=\"s\" direction=\"out\"/>\n\
74 </signal>\n\
75 <signal name=\"Disconnect\" >\n\
76 <arg name=\"address\" type=\"s\" direction=\"out\"/>\n\
77 </signal>\n\
78 </interface>\n\
79 <interface name=\"org.freedesktop.DBus.Introspectable\">\n\
80 <method name=\"Introspect\">\n\
81 <arg type=\"s\" direction=\"out\"/>\n\
82 </method>\n\
83 </interface>\n\
84 </node>"
85
86
87 struct devstruct;
88 typedef struct devstruct {
89 char* btid;
90 bdaddr_t bdaddr;
91 int dd;
92 int track;
93 bool connected;
94 struct devstruct* next;
95 } btdev_t;
96
97 btdev_t* btdev_append_new(btdev_t* current, char* btid)
98 {
99 btdev_t* temp;
100 if (NULL == current) {
101 temp = malloc(sizeof(btdev_t));
102 temp->btid = btid;
103 temp->dd = 0;
104 temp->connected = false;
105 temp->next = NULL;
106 temp->track = -1;
107 return temp;
108 }
109 else {
110 current->next = btdev_append_new(current->next, btid);
111 return current;
112 }
113 }
114
115 typedef struct {
116 char* config;
117 btdev_t* btdevroot;
118 int threshold;
119 int interval;
120 bool stdout;
121 bool fork;
122 bool verbose;
123 bool authenticate;
124 int uid;
125 int gid;
126 bool disconnecthack;
127 bool linkquality;
128 } arg_t;
129 arg_t opts;
130 arg_t args;
131 DBusConnection* conn = NULL;
132
133 void message(bool verbose, char* msg, ...);
134 void sendsignal(bool connected, btdev_t* btdev);
135
136 #define assert(a, b) if(!(a)) real_assert(b)
137 void real_assert (char* msg)
138 {
139 if (0 != errno) {
140 char* errstr = strerror(errno);
141 message(false, "[Assert] failed with errno %d/%s: %s\n", errno, errstr, msg);
142 } else
143 message(false, "[Assert] failed: %s\n", msg);
144 #ifdef DEBUG
145 exit(1);
146 #endif
147 }
148
149 static int find_conn(int s, int dev_id, long arg)
150 {
151 struct hci_conn_list_req *cl;
152 struct hci_conn_info *ci;
153 int i;
154
155 if (!(cl = malloc(10 * sizeof(*ci) + sizeof(*cl)))) {
156 perror("Can't allocate memory");
157 exit(1);
158 }
159 cl->dev_id = dev_id;
160 cl->conn_num = 10;
161 ci = cl->conn_info;
162
163 if (ioctl(s, HCIGETCONNLIST, (void*)cl)) {
164 perror("Can't get connection list");
165 exit(1);
166 }
167
168 for (i=0; i < cl->conn_num; i++, ci++)
169 if (!bacmp((bdaddr_t *)arg, &ci->bdaddr)) {
170 free(cl);
171 return 1;
172 }
173 free(cl);
174 return 0;
175 }
176
177 // open connection
178 bool btconnect(btdev_t* btdev)
179 {
180 int ptype;
181 uint16_t handle = 0;
182 uint8_t role;
183 bool rval;
184 struct hci_conn_info_req *cr;
185 struct hci_request rq;
186 auth_requested_cp acp;
187 evt_auth_complete arp;
188 evt_encrypt_change erp;
189 set_conn_encrypt_cp ecp;
190
191 role = 0x01;
192 ptype = HCI_DM1 | HCI_DM3 | HCI_DM5 | HCI_DH1 | HCI_DH3 | HCI_DH5;
193
194 int dev_id = hci_for_each_dev(HCI_UP, find_conn, (long) &(btdev->bdaddr));
195 if (dev_id < 0) {
196 message(true, "Connecting to: %x:%x:%x:%x:%x:%x\n", btdev->bdaddr.b[5], btdev->bdaddr.b[4], btdev->bdaddr.b[3], btdev->bdaddr.b[2], btdev->bdaddr.b[1], btdev->bdaddr.b[0]);
197 if (hci_create_connection(btdev->dd, &(btdev->bdaddr), htobs(ptype), 0, role, &handle, BTCONNECTTIMEOUT) < 0) {
198 message(true, "Can't create connection\n");
199 return false;
200 }
201 btdev->connected = true;
202 }
203 else btdev->connected = false;
204
205 if (0 == handle) {
206 cr = malloc(sizeof(*cr) + sizeof(struct hci_conn_info));
207
208 bacpy(&cr->bdaddr, &(btdev->bdaddr));
209 cr->type = ACL_LINK;
210 if (ioctl(btdev->dd, HCIGETCONNINFO, (unsigned long) cr) < 0) {
211 message(true, "Get connection info failed");
212 return false;
213 }
214 handle = htobs(cr->conn_info->handle);
215 free(cr);
216 }
217
218 if (opts.authenticate || args.authenticate) {
219
220 acp.handle = htobs(handle);
221
222 memset(&rq, 0, sizeof(rq));
223 rq.ogf = OGF_LINK_CTL;
224 rq.ocf = OCF_AUTH_REQUESTED;
225 rq.cparam = &acp;
226 rq.clen = AUTH_REQUESTED_CP_SIZE;
227 rq.rparam = &arp;
228 rq.rlen = EVT_AUTH_COMPLETE_SIZE;
229 rq.event = EVT_AUTH_COMPLETE;
230
231 if (hci_send_req(btdev->dd, &rq, 25000) < 0) {
232 #ifdef DEBUG
233 message(true, "Can't authenticate link\n");
234 #endif
235 return false;
236 }
237 ecp.handle = htobs(handle);
238 ecp.encrypt = 1;
239
240 memset(&rq, 0, sizeof(rq));
241 rq.ogf = OGF_LINK_CTL;
242 rq.ocf = OCF_SET_CONN_ENCRYPT;
243 rq.cparam = &ecp;
244 rq.clen = SET_CONN_ENCRYPT_CP_SIZE;
245 rq.rparam = &erp;
246 rq.rlen = EVT_ENCRYPT_CHANGE_SIZE;
247 rq.event = EVT_ENCRYPT_CHANGE;
248
249 if (hci_send_req(btdev->dd, &rq, 25000) < 0) {
250 #ifdef DEBUG
251 message(true, "Can't encrypt link\n");
252 #endif
253 return false;
254 }
255 }
256 return true;
257 }
258
259
260 // close connection
261 void btdisconnect(btdev_t* btdev)
262 {
263 struct hci_conn_info_req *cr;
264 cr = malloc(sizeof(*cr) + sizeof(struct hci_conn_info));
265 if (!cr)
266 return;
267
268 bacpy(&cr->bdaddr, &(btdev->bdaddr));
269 cr->type = ACL_LINK;
270 if (ioctl(btdev->dd, HCIGETCONNINFO, (unsigned long) cr) < 0) {
271 message(false, "Get connection info failed\n");
272 exit(1);
273 }
274
275 if (hci_disconnect(btdev->dd, htobs(cr->conn_info->handle), HCI_OE_USER_ENDED_CONNECTION, 100) < 0)
276 message(false, "Disconnect failed\n");
277 free(cr);
278 }
279
280
281
282 // query link quality
283 int get_link_qual(btdev_t* btdev)
284 {
285 struct hci_conn_info_req *cr;
286 struct hci_request rq;
287 #ifdef OCF_GET_LINK_QUALITY
288 get_link_quality_rp rp;
289 #else
290 read_link_quality_rp rp;
291 #endif
292 uint16_t handle;
293 int qual;
294
295 // check the quality
296 if (opts.linkquality || args.linkquality) {
297 cr = malloc(sizeof(*cr) + sizeof(struct hci_conn_info));
298 if (!cr)
299 return 0;
300 bacpy(&cr->bdaddr, &(btdev->bdaddr));
301 cr->type = ACL_LINK;
302 if (ioctl(btdev->dd, HCIGETCONNINFO, (unsigned long) cr) < 0) {
303 #ifdef DEBUG
304 message(true, "Get connection info failed, trying reconnect\n");
305 #endif
306 return -1;
307 }
308
309 handle = htobs(cr->conn_info->handle);
310
311 memset(&rq, 0, sizeof(rq));
312 rq.ogf = OGF_STATUS_PARAM;
313 #ifdef OCF_GET_LINK_QUALITY
314 rq.ocf = OCF_GET_LINK_QUALITY;
315 #else
316 rq.ocf = OCF_READ_LINK_QUALITY;
317 #endif
318 rq.cparam = &handle;
319 rq.clen = 2;
320 rq.rparam = &rp;
321 #ifdef OCF_GET_LINK_QUALITY_RP_SIZE
322 rq.rlen = GET_LINK_QUALITY_RP_SIZE;
323 #else
324 rq.rlen = READ_LINK_QUALITY_RP_SIZE;
325 #endif
326
327 if (hci_send_req(btdev->dd, &rq, 100) < 0) {
328 message(true, "HCI get_link_quality request failed, trying reconnect\n");
329 free(cr);
330 return -1;
331 }
332
333 if (rp.status) {
334 #ifdef DEBUG
335 message(true, "HCI get_link_quality cmd failed (0x%2.2X), trying reconnect\n", rp.status);
336 #endif
337 free(cr);
338 return -1;
339 }
340
341 qual = rp.link_quality;
342 free(cr);
343 return qual;
344 }
345 // just check for connection
346 else {
347 qual = hci_for_each_dev(HCI_UP, find_conn, (long) &(btdev->bdaddr));
348 return qual < 0 ? qual : 255;
349 }
350 }
351
352 void readoptions(arg_t args, arg_t* opts)
353 {
354 opts->config = NULL;
355 opts->btdevroot = NULL;
356 opts->threshold = DEFAULTTHRESHOLD;
357 opts->interval = DEFAULTINTERVAL;
358 opts->stdout = false;
359 opts->fork = true;
360 opts->verbose = false;
361 opts->uid = 0;
362 opts->gid = 0;
363 opts->authenticate = false;
364 opts->linkquality = false;
365 }
366
367 char* progname;
368
369 void syntax()
370 {
371 printf("Syntax: %s <options>\n", progname);
372 //printf(" -c configfile --config=configfile\n");
373 printf(" -b aa:bb:cc:dd:ee:ff --btid=aa:bb:cc:dd:ee:ff\n");
374 printf(" -t threshold --threshold=threshold\n");
375 printf(" -i interval --interval=interval\n");
376 printf(" -s --stdout --no-syslog\n");
377 printf(" -n --no-fork\n");
378 printf(" -v --verbose\n");
379 printf(" -V --version\n");
380 printf(" -d --disconnect-hack\n");
381 printf(" -q --link-quality\n");
382 printf(" -a --authenticate\n");
383 printf(" -h --help\n");
384 exit(1);
385 }
386
387 /*
388 * -c --config
389 * -b --btid
390 * -t --threshold
391 * -i --interval
392 * -s --stdout --no-syslog
393 * -n --no-fork
394 * -v --verbose
395 * -a --authenticate
396 * -h --help
397 */
398 void readargs(int argc, char** argv, arg_t* args)
399 {
400 args->config = NULL;
401 args->btdevroot = NULL;
402 args->threshold = DEFAULTTHRESHOLD;
403 args->interval = DEFAULTINTERVAL;
404 args->stdout = false;
405 args->fork = true;
406 args->verbose = false;
407 args->authenticate = false;
408 args->disconnecthack = false;
409 args->linkquality = false;
410 args->uid = 0;
411 args->gid = 0;
412
413 int c;
414 static struct option long_opts[] = {
415 {"config", 1, 0, 'c'},
416 {"btid", 1, 0, 'b'},
417 {"threshold", 1, 0, 't'},
418 {"interval", 1, 0, 'i'},
419 {"stdout", 0, 0, 's'},
420 {"help", 0, 0, 'h'},
421 {"no-fork", 0, 0, 'n'},
422 {"verbose", 0, 0, 'v'},
423 {"version", 0, 0, 'V'},
424 {"authenticate", 0, 0, 'a'},
425 {"no-syslog", 0, 0, 's'},
426 {"uid", 1, 0, 'u'},
427 {"gid", 1, 0, 'u'},
428 {"disconnect-hack", 1, 0, 'd'},
429 {"link-quality", 1, 0, 'q'}
430 };
431 int idx = 0;
432 while (-1 != (c = getopt_long(argc, argv, "-c:b:t:i:o:sqhVndvag:u:",long_opts, &idx))) {
433 switch (c) {
434 case 'c':
435 args->config = optarg;
436 break;
437 case 'b':
438 args->btdevroot = btdev_append_new(args->btdevroot, optarg);
439 break;
440 case 't':
441 args->threshold = atoi(optarg);
442 break;
443 case 'i':
444 args->interval = atoi(optarg);
445 break;
446 case 'u':
447 args->uid = atoi(optarg);
448 break;
449 case 'g':
450 args->gid = atoi(optarg);
451 break;
452 case 's':
453 args->stdout = true;
454 break;
455 case 'n':
456 args->fork = false;
457 break;
458 case 'v':
459 args->verbose = true;
460 break;
461 case 'd':
462 args->disconnecthack = true;
463 break;
464 case 'a':
465 args->authenticate = true;
466 break;
467 case 'q':
468 args->linkquality = true;
469 break;
470 case 'V':
471 printf("Bluemon version %s.\n", VERSION);
472 break;
473 case 'h':
474 case ':':
475 case '?':
476 case 1:
477 syntax();
478 break;
479 }
480 idx = 0;
481 }
482 }
483
484 int testint(int a, int b, char* errormsg)
485 {
486 if (0 != a)
487 return a;
488 if (0 != b)
489 return b;
490 message(false, "%s\n", errormsg);
491 exit(1);
492 }
493 btdev_t* testdev(btdev_t* a, btdev_t* b, char* errormsg)
494 {
495 if (NULL != a)
496 return a;
497 if (NULL != b)
498 return b;
499 message(false, "%s\n", errormsg);
500
501 exit(1);
502 }
503 char* testchar(char* a, char* b, char* errormsg)
504 {
505 if (NULL != a)
506 return a;
507 if (NULL != b)
508 return b;
509 message(false, "%s\n", errormsg);
510
511 exit(1);
512 }
513
514 // write a message to syslog or stdout depending on setup
515 void message(bool verbose, char* msg, ...)
516 {
517 if (!args.verbose && !opts.verbose && verbose) return;
518 va_list vargs;
519 va_start(vargs, msg);
520
521 if (args.stdout || opts.stdout)
522 vprintf(msg, vargs);
523 else
524 vsyslog(LOG_NOTICE, msg, vargs);
525
526 va_end(vargs);
527 }
528
529
530
531 void sighandle(int signum)
532 {
533 btdev_t* btdev;
534 switch (signum) {
535 case SIGINT:
536 case SIGTERM:
537 btdev = testdev(args.btdevroot, opts.btdevroot, "No Devices Specified");
538 while (NULL != btdev) {
539 if (btdev->connected) {
540 // disconnect bluetooth
541 btdisconnect(btdev);
542 message(true, "Disconnected %s\n", btdev->btid);
543 }
544 if (NULL != conn)
545 sendsignal(false, btdev);
546 hci_close_dev(btdev->dd);
547 btdev_t* temp = btdev->next;
548 free(btdev);
549 btdev = temp;
550 }
551 message(false, "Caught SIGTERM, announcing our demise\n");
552 if (NULL != conn)
553 dbus_connection_unref(conn);
554 exit(0);
555 case SIGHUP:
556 readoptions(args, &opts);
557 break;
558 }
559 }
560
561 void writepidfile(void)
562 {
563 FILE* fd;
564 fd = fopen("/var/run/bluemon.pid", "w");
565 if (NULL != fd) {
566 fprintf(fd, "%d", getpid());
567 fclose(fd);
568 } else {
569 message(true, "Could not write PID file, quitting\n");
570 exit(1);
571 }
572 }
573
574 DBusConnection* register_dbus()
575 {
576 DBusError err;
577 DBusConnection* conn;
578 int ret;
579
580 dbus_error_init(&err);
581
582 conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
583 if (dbus_error_is_set(&err)) {
584 message(true, "DBUS Connection Error (%s)\n", err.message);
585 dbus_error_free(&err);
586 }
587 if (NULL == conn) {
588 exit(1);
589 }
590
591 ret = dbus_bus_request_name(conn, "cx.ath.matthew.bluemon.server",
592 DBUS_NAME_FLAG_REPLACE_EXISTING,
593 &err);
594 if (dbus_error_is_set(&err)) {
595 message(true, "DBUS Name Error (%s)\n", err.message);
596 dbus_error_free(&err);
597 }
598 if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
599 exit(1);
600 }
601 return conn;
602 }
603
604 void sendsignal(bool inrange, btdev_t* btdev)
605 {
606 DBusMessage* msg;
607 DBusMessageIter it;
608 dbus_uint32_t serial;
609 if (inrange)
610 msg = dbus_message_new_signal("/cx/ath/matthew/bluemon/Bluemon", "cx.ath.matthew.bluemon.ProximitySignal", "Connect");
611 else
612 msg = dbus_message_new_signal("/cx/ath/matthew/bluemon/Bluemon", "cx.ath.matthew.bluemon.ProximitySignal", "Disconnect");
613 if (NULL == msg) { message(true, "DBUS Message Null, ALIEN INVASION\n"); exit(1); }
614 dbus_message_iter_init_append(msg, &it);
615 if (!dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &(btdev->btid))) {
616 message(true, "Out Of Memory!");
617 exit(1);
618 }
619 if (!dbus_connection_send(conn, msg, &serial)) {
620 message(true, "Out Of Memory!");
621 exit(1);
622 }
623
624 //dbus_connection_flush(conn);
625 dbus_message_unref(msg);
626 message(true, "Signal sent (%s, %s)\n", inrange?"true":"false", btdev->btid);
627 }
628
629 void handle_dbus_message(DBusMessage* msg, int threshold)
630 {
631 DBusMessage* reply;
632 DBusMessageIter it;
633 dbus_uint32_t serial, level;
634 dbus_bool_t stat;
635 char* address;
636
637 if (!dbus_message_iter_init(msg, &it)) {
638 message(true, "Bad parameter count for Status message");
639 return;
640 }
641 if (DBUS_TYPE_STRING != dbus_message_iter_get_arg_type(&it)) {
642 message(true, "Bad parameter type (%d) for Status message", dbus_message_iter_get_arg_type(&it));
643 return;
644 }
645 dbus_message_iter_get_basic(&it, &address);
646 message(true, "Handling dbus status query for %d\n", address);
647 reply = dbus_message_new_method_return(msg);
648 if (NULL == reply) {
649 message(true, "Reply is NULL!! You have been eaten by a GRUE!");
650 return;
651 }
652 dbus_message_iter_init_append(reply, &it);
653 btdev_t* btdev = testdev(args.btdevroot, opts.btdevroot, "No Devices Specified");
654 for (; NULL != btdev; btdev = btdev->next) {
655 if (0 == strncmp("", address, 1) || 0 == strncasecmp(btdev->btid, address, strlen(btdev->btid))) {
656 if (!dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &(btdev->btid))) {
657 message(true, "Out Of Memory! Lock me in the cellar and feed me pins, PINS!!");
658 dbus_message_unref(reply);
659 return;
660 }
661 if (btdev->track >= threshold) {
662 stat = TRUE;
663 level = btdev->track;
664 } else {
665 stat = FALSE;
666 level = -1;
667 }
668 break;
669 } else {
670 //address = "";
671 stat = FALSE;
672 level = -1;
673 dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &address);
674 }
675 }
676 if (!dbus_message_iter_append_basic(&it, DBUS_TYPE_BOOLEAN, &stat)){
677 message(true, "Out Of Memory! The bells! the bells!");
678 dbus_message_unref(reply);
679 return;
680 }
681
682 if (!dbus_message_iter_append_basic(&it, DBUS_TYPE_UINT32, &level)){
683 message(true, "Out Of Memory! Every night the steam part of my brain and feed it to their mum!");
684 dbus_message_unref(reply);
685 return;
686 }
687
688
689 if (!dbus_connection_send(conn, reply, &serial)){
690 message(true, "Out Of Memory! Universe error, redo from start!");
691 dbus_message_unref(reply);
692 return;
693 }
694 dbus_connection_flush(conn);
695 dbus_message_unref(reply);
696 }
697
698
699 void handle_introspection_message(DBusMessage* msg)
700 {
701 DBusMessage* reply;
702 DBusMessageIter it;
703 dbus_uint32_t serial;
704 char* xml = DBUS_INTROSPECTION_DATA;
705
706 message(true, "Handling dbus introspection query\n");
707 reply = dbus_message_new_method_return(msg);
708 if (NULL == reply) {
709 message(true, "Reply is NULL!! You have been eaten by a GRUE!");
710 return;
711 }
712 dbus_message_iter_init_append(reply, &it);
713 if (!dbus_message_iter_append_basic(&it, DBUS_TYPE_STRING, &xml)){
714 message(true, "Out Of Memory! The bells! the bells!");
715 dbus_message_unref(reply);
716 return;
717 }
718
719 if (!dbus_connection_send(conn, reply, &serial)){
720 message(true, "Out Of Memory! Universe error, redo from start!");
721 dbus_message_unref(reply);
722 return;
723 }
724 dbus_connection_flush(conn);
725 dbus_message_unref(reply);
726 }
727
728 int main(int argc, char ** argv)
729 {
730 int dev_id, pid;
731 int track, threshold, interval;
732 char* btid;
733 int ret;
734 int lq = 0;
735 bool run = true;
736 bool foo = false;
737 DBusMessage* msg;
738 DBusMessage* err;
739 dbus_uint32_t serial;
740
741 progname = argv[0];
742
743 readargs(argc, argv, &args);
744 readoptions(args, &opts);
745
746 // fork
747 if (args.fork && opts.fork) {
748 pid = fork();
749 if (pid < 0)
750 printf("Cannot fork");
751 if (pid > 0)
752 exit(0);
753 else {
754 setsid();
755 chdir("/");
756 umask(0);
757 }
758 }
759
760 writepidfile();
761
762 // syslog
763 if (!(args.stdout || opts.stdout))
764 openlog("bluetooth-monitor",0, LOG_DAEMON);
765
766 message(false, "Bluetooth monitoring system startup, version %s\n", VERSION);
767
768 // register cleanup code
769 signal(SIGTERM, sighandle);
770 signal(SIGINT, sighandle);
771 signal(SIGHUP, sighandle);
772
773 conn = register_dbus();
774
775 threshold = testint(args.threshold, opts.threshold, "No Link Quality Threshold Specified");
776
777 btdev_t* btdev = testdev(args.btdevroot, opts.btdevroot, "No Devices Specified");
778 for (; NULL != btdev; btdev = btdev->next) {
779 str2ba(btdev->btid, &(btdev->bdaddr));
780
781 message(true, "Connecting to address %x:%x:%x:%x:%x:%x\n", btdev->bdaddr.b[5], btdev->bdaddr.b[4], btdev->bdaddr.b[3], btdev->bdaddr.b[2], btdev->bdaddr.b[1], btdev->bdaddr.b[0]);
782 dev_id = hci_get_route(&(btdev->bdaddr));
783
784 if (dev_id < 0) {
785 message(false, "Device is not available.\n");
786 exit(1);
787 }
788
789 btdev->dd = hci_open_dev(dev_id);
790 if (btdev->dd < 0) {
791 message(false, "HCI device open failed\n");
792 exit(1);
793 }
794
795 foo = btconnect(btdev);
796 if (!btdev->connected)
797 message(true, "Using existing connection\n");
798 if (!foo) lq = -1;
799
800 message(true, "Monitoring link quality\n");
801 btdev->track = get_link_qual(btdev);
802 if (btdev->track >= threshold)
803 sendsignal(true, btdev);
804 }
805
806 // drop privs
807 if ((args.uid || opts.uid) && (args.gid || opts.gid))
808 setreuid(args.uid?args.uid:opts.uid, args.gid?args.gid:opts.gid);
809
810 while (run) {
811 threshold = testint(args.threshold, opts.threshold, "No Link Quality Threshold Specified");
812 interval = testint(args.interval, opts.interval, "No Interval Specified");
813
814 btdev_t* btdev = testdev(args.btdevroot, opts.btdevroot, "No Devices Specified");
815 for (; NULL != btdev; btdev = btdev->next) {
816 // if device disconnects every 54s check before reconnect statement
817 if (args.disconnecthack || opts.disconnecthack)
818 lq = get_link_qual(btdev);
819 if (-1 == lq)
820 btconnect(btdev);
821
822 lq = get_link_qual(btdev);
823
824 if (lq >= threshold && btdev->track < threshold) {
825 // good quality, stop the screensaver
826 sendsignal(true, btdev);
827 message(false, "Device %s Connected\n", btdev->btid);
828 }
829 else if (lq < threshold && btdev->track >= threshold) {
830 // bad quality, start the screensaver
831 sendsignal(false, btdev);
832 message(false, "Device %s Disconnected\n", btdev->btid);
833 }
834 btdev->track = lq;
835 }
836
837 dbus_connection_read_write(conn, interval);
838 while (NULL != (msg = dbus_connection_pop_message(conn))) {
839 if (dbus_message_is_method_call(msg, "cx.ath.matthew.bluemon.Bluemon", "Status"))
840 handle_dbus_message(msg, threshold);
841 else if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Introspectable", "Introspect"))
842 handle_introspection_message(msg);
843 else if (dbus_message_is_method_call(msg, "org.freedesktop.DBus.Peer", "Ping")) {
844 err = dbus_message_new_method_return (msg);
845 dbus_connection_send(conn, err, &serial);
846 dbus_message_unref(err);
847 }
848 else if (DBUS_MESSAGE_TYPE_METHOD_CALL == dbus_message_get_type(msg)) {
849 err = dbus_message_new_error (msg, "cx.ath.matthew.bluemon.error", "Unknown Method");
850 dbus_connection_send(conn, err, &serial);
851 dbus_message_unref(err);
852 }
853 dbus_message_unref(msg);
854 }
855 }
856
857 btdev = testdev(args.btdevroot, opts.btdevroot, "No Devices Specified");
858 while (NULL != btdev) {
859 if (btdev->connected) {
860 // disconnect bluetooth
861 btdisconnect(btdev);
862 if (NULL != conn)
863 sendsignal(false, btdev);
864 message(true, "Disconnected %s\n", btdev->btid);
865 }
866 hci_close_dev(btdev->dd);
867 btdev_t* temp = btdev->next;
868 free(btdev);
869 btdev = temp;
870 }
871 // disconnect socket
872 if (NULL != conn)
873 dbus_connection_unref(conn);
874 }
875