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