Home | History | Annotate | Line # | Download | only in dist
      1 /*	$NetBSD: pcap-dbus.c,v 1.8 2026/03/18 23:43:20 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2012 Jakub Zawadzki
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  *
     11  * 1. Redistributions of source code must retain the above copyright
     12  * notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  * notice, this list of conditions and the following disclaimer in the
     15  * documentation and/or other materials provided with the distribution.
     16  * 3. The name of the author may not be used to endorse or promote
     17  * products derived from this software without specific prior written
     18  * permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __RCSID("$NetBSD: pcap-dbus.c,v 1.8 2026/03/18 23:43:20 christos Exp $");
     35 
     36 #include <config.h>
     37 
     38 #include <string.h>
     39 
     40 #include <time.h>
     41 #include <sys/time.h>
     42 
     43 #include <dbus/dbus.h>
     44 
     45 #include "pcap-int.h"
     46 #include "pcap-dbus.h"
     47 
     48 /*
     49  * Private data for capturing on D-Bus.
     50  */
     51 struct pcap_dbus {
     52 	DBusConnection *conn;
     53 	u_int	packets_read;	/* count of packets read */
     54 };
     55 
     56 static int
     57 dbus_read(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
     58 {
     59 	struct pcap_dbus *handlep = handle->priv;
     60 
     61 	struct pcap_pkthdr pkth;
     62 	DBusMessage *message;
     63 
     64 	char *raw_msg;
     65 	int raw_msg_len;
     66 
     67 	int count = 0;
     68 
     69 	message = dbus_connection_pop_message(handlep->conn);
     70 
     71 	while (!message) {
     72 		/* XXX handle->opt.timeout = timeout_ms; */
     73 		if (!dbus_connection_read_write(handlep->conn, 100)) {
     74 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Connection closed");
     75 			return -1;
     76 		}
     77 
     78 		if (handle->break_loop) {
     79 			handle->break_loop = 0;
     80 			return -2;
     81 		}
     82 
     83 		message = dbus_connection_pop_message(handlep->conn);
     84 	}
     85 
     86 	if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
     87 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Disconnected");
     88 		dbus_message_unref(message);
     89 		return -1;
     90 	}
     91 
     92 	if (dbus_message_marshal(message, &raw_msg, &raw_msg_len)) {
     93 		pkth.caplen = pkth.len = raw_msg_len;
     94 		/* pkth.caplen = min (payload_len, handle->snapshot); */
     95 
     96 		gettimeofday(&pkth.ts, NULL);
     97 		if (handle->fcode.bf_insns == NULL ||
     98 		    pcapint_filter(handle->fcode.bf_insns, (u_char *)raw_msg, pkth.len, pkth.caplen)) {
     99 			handlep->packets_read++;
    100 			callback(user, &pkth, (u_char *)raw_msg);
    101 			count++;
    102 		}
    103 
    104 		dbus_free(raw_msg);
    105 	}
    106 
    107 	dbus_message_unref(message);
    108 
    109 	return count;
    110 }
    111 
    112 static int
    113 dbus_write(pcap_t *handle, const void *buf, int size)
    114 {
    115 	/* XXX, not tested */
    116 	struct pcap_dbus *handlep = handle->priv;
    117 
    118 	DBusError error = DBUS_ERROR_INIT;
    119 	DBusMessage *msg;
    120 
    121 	if (!(msg = dbus_message_demarshal(buf, size, &error))) {
    122 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dbus_message_demarshal() failed: %s", error.message);
    123 		dbus_error_free(&error);
    124 		return -1;
    125 	}
    126 
    127 	dbus_connection_send(handlep->conn, msg, NULL);
    128 	dbus_connection_flush(handlep->conn);
    129 
    130 	dbus_message_unref(msg);
    131 	return 0;
    132 }
    133 
    134 static int
    135 dbus_stats(pcap_t *handle, struct pcap_stat *stats)
    136 {
    137 	struct pcap_dbus *handlep = handle->priv;
    138 
    139 	stats->ps_recv = handlep->packets_read;
    140 	stats->ps_drop = 0;
    141 	stats->ps_ifdrop = 0;
    142 	return 0;
    143 }
    144 
    145 static void
    146 dbus_cleanup(pcap_t *handle)
    147 {
    148 	struct pcap_dbus *handlep = handle->priv;
    149 
    150 	dbus_connection_unref(handlep->conn);
    151 
    152 	pcapint_cleanup_live_common(handle);
    153 }
    154 
    155 /*
    156  * We don't support non-blocking mode.  I'm not sure what we'd
    157  * do to support it and, given that we don't support select()/
    158  * poll()/epoll_wait()/kevent() etc., it probably doesn't
    159  * matter.
    160  */
    161 static int
    162 dbus_getnonblock(pcap_t *p)
    163 {
    164 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
    165 	    "Non-blocking mode isn't supported for capturing on D-Bus");
    166 	return (-1);
    167 }
    168 
    169 static int
    170 dbus_setnonblock(pcap_t *p, int nonblock _U_)
    171 {
    172 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
    173 	    "Non-blocking mode isn't supported for capturing on D-Bus");
    174 	return (-1);
    175 }
    176 
    177 static int
    178 dbus_activate(pcap_t *handle)
    179 {
    180 #define EAVESDROPPING_RULE "eavesdrop=true,"
    181 
    182 	static const char *rules[] = {
    183 		EAVESDROPPING_RULE "type='signal'",
    184 		EAVESDROPPING_RULE "type='method_call'",
    185 		EAVESDROPPING_RULE "type='method_return'",
    186 		EAVESDROPPING_RULE "type='error'",
    187 	};
    188 
    189 	#define N_RULES sizeof(rules)/sizeof(rules[0])
    190 
    191 	struct pcap_dbus *handlep = handle->priv;
    192 	const char *dev = handle->opt.device;
    193 
    194 	DBusError error = DBUS_ERROR_INIT;
    195 	u_int i;
    196 
    197 	if (strcmp(dev, "dbus-system") == 0) {
    198 		if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) {
    199 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get system bus: %s", error.message);
    200 			dbus_error_free(&error);
    201 			return PCAP_ERROR;
    202 		}
    203 
    204 	} else if (strcmp(dev, "dbus-session") == 0) {
    205 		if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SESSION, &error))) {
    206 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get session bus: %s", error.message);
    207 			dbus_error_free(&error);
    208 			return PCAP_ERROR;
    209 		}
    210 
    211 	} else if (strncmp(dev, "dbus://", 7) == 0) {
    212 		const char *addr = dev + 7;
    213 
    214 		if (!(handlep->conn = dbus_connection_open(addr, &error))) {
    215 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to open connection to: %s: %s", addr, error.message);
    216 			dbus_error_free(&error);
    217 			return PCAP_ERROR;
    218 		}
    219 
    220 		if (!dbus_bus_register(handlep->conn, &error)) {
    221 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to register bus %s: %s\n", addr, error.message);
    222 			dbus_error_free(&error);
    223 			return PCAP_ERROR;
    224 		}
    225 
    226 	} else {
    227 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't get bus address from %s", handle->opt.device);
    228 		return PCAP_ERROR;
    229 	}
    230 
    231 	/* Initialize some components of the pcap structure. */
    232 	handle->bufsize = 0;
    233 	handle->offset = 0;
    234 	handle->linktype = DLT_DBUS;
    235 	handle->read_op = dbus_read;
    236 	handle->inject_op = dbus_write;
    237 	handle->setfilter_op = pcapint_install_bpf_program; /* XXX, later add support for dbus_bus_add_match() */
    238 	handle->setdirection_op = NULL;
    239 	handle->set_datalink_op = NULL;      /* can't change data link type */
    240 	handle->getnonblock_op = dbus_getnonblock;
    241 	handle->setnonblock_op = dbus_setnonblock;
    242 	handle->stats_op = dbus_stats;
    243 	handle->cleanup_op = dbus_cleanup;
    244 
    245 #ifndef _WIN32
    246 	/*
    247 	 * Unfortunately, trying to do a select()/poll()/epoll_wait()/
    248 	 * kevent()/etc. on a D-Bus connection isn't a simple
    249 	 * case of "give me an FD on which to wait".
    250 	 *
    251 	 * Apparently, you have to register "add watch", "remove watch",
    252 	 * and "toggle watch" functions with
    253 	 * dbus_connection_set_watch_functions(),
    254 	 * keep a *set* of FDs, add to that set in the "add watch"
    255 	 * function, subtract from it in the "remove watch" function,
    256 	 * and either add to or subtract from that set in the "toggle
    257 	 * watch" function, and do the wait on *all* of the FDs in the
    258 	 * set.  (Yes, you need the "toggle watch" function, so that
    259 	 * the main loop doesn't itself need to check for whether
    260 	 * a given watch is enabled or disabled - most libpcap programs
    261 	 * know nothing about D-Bus and shouldn't *have* to know anything
    262 	 * about D-Bus other than how to decode D-Bus messages.)
    263 	 *
    264 	 * Implementing that would require considerable changes in
    265 	 * the way libpcap exports "selectable FDs" to its client.
    266 	 * Until that's done, we just say "you can't do that".
    267 	 */
    268 	handle->selectable_fd = handle->fd = -1;
    269 #endif
    270 
    271 	if (handle->opt.rfmon) {
    272 		/*
    273 		 * Monitor mode doesn't apply to dbus connections.
    274 		 */
    275 		dbus_cleanup(handle);
    276 		return PCAP_ERROR_RFMON_NOTSUP;
    277 	}
    278 
    279 	/*
    280 	 * Turn a negative snapshot value (invalid), a snapshot value of
    281 	 * 0 (unspecified), or a value bigger than the normal maximum
    282 	 * value, into the maximum message length for D-Bus (128MB).
    283 	 */
    284 	if (handle->snapshot <= 0 || handle->snapshot > 134217728)
    285 		handle->snapshot = 134217728;
    286 
    287 	/* dbus_connection_set_max_message_size(handlep->conn, handle->snapshot); */
    288 	if (handle->opt.buffer_size != 0)
    289 		dbus_connection_set_max_received_size(handlep->conn, handle->opt.buffer_size);
    290 
    291 	for (i = 0; i < N_RULES; i++) {
    292 		dbus_bus_add_match(handlep->conn, rules[i], &error);
    293 		if (dbus_error_is_set(&error)) {
    294 			dbus_error_free(&error);
    295 
    296 			/* try without eavesdrop */
    297 			dbus_bus_add_match(handlep->conn, rules[i] + strlen(EAVESDROPPING_RULE), &error);
    298 			if (dbus_error_is_set(&error)) {
    299 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to add bus match: %s\n", error.message);
    300 				dbus_error_free(&error);
    301 				dbus_cleanup(handle);
    302 				return PCAP_ERROR;
    303 			}
    304 		}
    305 	}
    306 
    307 	return 0;
    308 }
    309 
    310 pcap_t *
    311 dbus_create(const char *device, char *ebuf, int *is_ours)
    312 {
    313 	pcap_t *p;
    314 
    315 	if (strcmp(device, "dbus-system") &&
    316 		strcmp(device, "dbus-session") &&
    317 		strncmp(device, "dbus://", 7))
    318 	{
    319 		*is_ours = 0;
    320 		return NULL;
    321 	}
    322 
    323 	*is_ours = 1;
    324 	p = PCAP_CREATE_COMMON(ebuf, struct pcap_dbus);
    325 	if (p == NULL)
    326 		return (NULL);
    327 
    328 	p->activate_op = dbus_activate;
    329 	/*
    330 	 * Set these up front, so that, even if our client tries
    331 	 * to set non-blocking mode before we're activated, or
    332 	 * query the state of non-blocking mode, they get an error,
    333 	 * rather than having the non-blocking mode option set
    334 	 * for use later.
    335 	 */
    336 	p->getnonblock_op = dbus_getnonblock;
    337 	p->setnonblock_op = dbus_setnonblock;
    338 	return (p);
    339 }
    340 
    341 int
    342 dbus_findalldevs(pcap_if_list_t *devlistp, char *err_str)
    343 {
    344 	/*
    345 	 * The notion of "connected" vs. "disconnected" doesn't apply.
    346 	 * XXX - what about the notions of "up" and "running"?
    347 	 */
    348 	if (pcapint_add_dev(devlistp, "dbus-system",
    349 	    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE, "D-Bus system bus",
    350 	    err_str) == NULL)
    351 		return -1;
    352 	if (pcapint_add_dev(devlistp, "dbus-session",
    353 	    PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE, "D-Bus session bus",
    354 	    err_str) == NULL)
    355 		return -1;
    356 	return 0;
    357 }
    358 
    359