1 /*        $NetBSD: pcap-dbus.c,v 1.7 2024/09/02 15:33:37 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.7 2024/09/02 15:33:37 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
dbus_read(pcap_t * handle,int max_packets _U_,pcap_handler callback,u_char * user)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                     return -1;
89           }
90 
91           if (dbus_message_marshal(message, &raw_msg, &raw_msg_len)) {
92                     pkth.caplen = pkth.len = raw_msg_len;
93                     /* pkth.caplen = min (payload_len, handle->snapshot); */
94 
95                     gettimeofday(&pkth.ts, NULL);
96                     if (handle->fcode.bf_insns == NULL ||
97                         pcapint_filter(handle->fcode.bf_insns, (u_char *)raw_msg, pkth.len, pkth.caplen)) {
98                               handlep->packets_read++;
99                               callback(user, &pkth, (u_char *)raw_msg);
100                               count++;
101                     }
102 
103                     dbus_free(raw_msg);
104           }
105           return count;
106 }
107 
108 static int
dbus_write(pcap_t * handle,const void * buf,int size)109 dbus_write(pcap_t *handle, const void *buf, int size)
110 {
111           /* XXX, not tested */
112           struct pcap_dbus *handlep = handle->priv;
113 
114           DBusError error = DBUS_ERROR_INIT;
115           DBusMessage *msg;
116 
117           if (!(msg = dbus_message_demarshal(buf, size, &error))) {
118                     snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "dbus_message_demarshal() failed: %s", error.message);
119                     dbus_error_free(&error);
120                     return -1;
121           }
122 
123           dbus_connection_send(handlep->conn, msg, NULL);
124           dbus_connection_flush(handlep->conn);
125 
126           dbus_message_unref(msg);
127           return 0;
128 }
129 
130 static int
dbus_stats(pcap_t * handle,struct pcap_stat * stats)131 dbus_stats(pcap_t *handle, struct pcap_stat *stats)
132 {
133           struct pcap_dbus *handlep = handle->priv;
134 
135           stats->ps_recv = handlep->packets_read;
136           stats->ps_drop = 0;
137           stats->ps_ifdrop = 0;
138           return 0;
139 }
140 
141 static void
dbus_cleanup(pcap_t * handle)142 dbus_cleanup(pcap_t *handle)
143 {
144           struct pcap_dbus *handlep = handle->priv;
145 
146           dbus_connection_unref(handlep->conn);
147 
148           pcapint_cleanup_live_common(handle);
149 }
150 
151 /*
152  * We don't support non-blocking mode.  I'm not sure what we'd
153  * do to support it and, given that we don't support select()/
154  * poll()/epoll_wait()/kevent() etc., it probably doesn't
155  * matter.
156  */
157 static int
dbus_getnonblock(pcap_t * p)158 dbus_getnonblock(pcap_t *p)
159 {
160           snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
161               "Non-blocking mode isn't supported for capturing on D-Bus");
162           return (-1);
163 }
164 
165 static int
dbus_setnonblock(pcap_t * p,int nonblock _U_)166 dbus_setnonblock(pcap_t *p, int nonblock _U_)
167 {
168           snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
169               "Non-blocking mode isn't supported for capturing on D-Bus");
170           return (-1);
171 }
172 
173 static int
dbus_activate(pcap_t * handle)174 dbus_activate(pcap_t *handle)
175 {
176 #define EAVESDROPPING_RULE "eavesdrop=true,"
177 
178           static const char *rules[] = {
179                     EAVESDROPPING_RULE "type='signal'",
180                     EAVESDROPPING_RULE "type='method_call'",
181                     EAVESDROPPING_RULE "type='method_return'",
182                     EAVESDROPPING_RULE "type='error'",
183           };
184 
185           #define N_RULES sizeof(rules)/sizeof(rules[0])
186 
187           struct pcap_dbus *handlep = handle->priv;
188           const char *dev = handle->opt.device;
189 
190           DBusError error = DBUS_ERROR_INIT;
191           u_int i;
192 
193           if (strcmp(dev, "dbus-system") == 0) {
194                     if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) {
195                               snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get system bus: %s", error.message);
196                               dbus_error_free(&error);
197                               return PCAP_ERROR;
198                     }
199 
200           } else if (strcmp(dev, "dbus-session") == 0) {
201                     if (!(handlep->conn = dbus_bus_get(DBUS_BUS_SESSION, &error))) {
202                               snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to get session bus: %s", error.message);
203                               dbus_error_free(&error);
204                               return PCAP_ERROR;
205                     }
206 
207           } else if (strncmp(dev, "dbus://", 7) == 0) {
208                     const char *addr = dev + 7;
209 
210                     if (!(handlep->conn = dbus_connection_open(addr, &error))) {
211                               snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to open connection to: %s: %s", addr, error.message);
212                               dbus_error_free(&error);
213                               return PCAP_ERROR;
214                     }
215 
216                     if (!dbus_bus_register(handlep->conn, &error)) {
217                               snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to register bus %s: %s\n", addr, error.message);
218                               dbus_error_free(&error);
219                               return PCAP_ERROR;
220                     }
221 
222           } else {
223                     snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't get bus address from %s", handle->opt.device);
224                     return PCAP_ERROR;
225           }
226 
227           /* Initialize some components of the pcap structure. */
228           handle->bufsize = 0;
229           handle->offset = 0;
230           handle->linktype = DLT_DBUS;
231           handle->read_op = dbus_read;
232           handle->inject_op = dbus_write;
233           handle->setfilter_op = pcapint_install_bpf_program; /* XXX, later add support for dbus_bus_add_match() */
234           handle->setdirection_op = NULL;
235           handle->set_datalink_op = NULL;      /* can't change data link type */
236           handle->getnonblock_op = dbus_getnonblock;
237           handle->setnonblock_op = dbus_setnonblock;
238           handle->stats_op = dbus_stats;
239           handle->cleanup_op = dbus_cleanup;
240 
241 #ifndef _WIN32
242           /*
243            * Unfortunately, trying to do a select()/poll()/epoll_wait()/
244            * kevent()/etc. on a D-Bus connection isn't a simple
245            * case of "give me an FD on which to wait".
246            *
247            * Apparently, you have to register "add watch", "remove watch",
248            * and "toggle watch" functions with
249            * dbus_connection_set_watch_functions(),
250            * keep a *set* of FDs, add to that set in the "add watch"
251            * function, subtract from it in the "remove watch" function,
252            * and either add to or subtract from that set in the "toggle
253            * watch" function, and do the wait on *all* of the FDs in the
254            * set.  (Yes, you need the "toggle watch" function, so that
255            * the main loop doesn't itself need to check for whether
256            * a given watch is enabled or disabled - most libpcap programs
257            * know nothing about D-Bus and shouldn't *have* to know anything
258            * about D-Bus other than how to decode D-Bus messages.)
259            *
260            * Implementing that would require considerable changes in
261            * the way libpcap exports "selectable FDs" to its client.
262            * Until that's done, we just say "you can't do that".
263            */
264           handle->selectable_fd = handle->fd = -1;
265 #endif
266 
267           if (handle->opt.rfmon) {
268                     /*
269                      * Monitor mode doesn't apply to dbus connections.
270                      */
271                     dbus_cleanup(handle);
272                     return PCAP_ERROR_RFMON_NOTSUP;
273           }
274 
275           /*
276            * Turn a negative snapshot value (invalid), a snapshot value of
277            * 0 (unspecified), or a value bigger than the normal maximum
278            * value, into the maximum message length for D-Bus (128MB).
279            */
280           if (handle->snapshot <= 0 || handle->snapshot > 134217728)
281                     handle->snapshot = 134217728;
282 
283           /* dbus_connection_set_max_message_size(handlep->conn, handle->snapshot); */
284           if (handle->opt.buffer_size != 0)
285                     dbus_connection_set_max_received_size(handlep->conn, handle->opt.buffer_size);
286 
287           for (i = 0; i < N_RULES; i++) {
288                     dbus_bus_add_match(handlep->conn, rules[i], &error);
289                     if (dbus_error_is_set(&error)) {
290                               dbus_error_free(&error);
291 
292                               /* try without eavesdrop */
293                               dbus_bus_add_match(handlep->conn, rules[i] + strlen(EAVESDROPPING_RULE), &error);
294                               if (dbus_error_is_set(&error)) {
295                                         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Failed to add bus match: %s\n", error.message);
296                                         dbus_error_free(&error);
297                                         dbus_cleanup(handle);
298                                         return PCAP_ERROR;
299                               }
300                     }
301           }
302 
303           return 0;
304 }
305 
306 pcap_t *
dbus_create(const char * device,char * ebuf,int * is_ours)307 dbus_create(const char *device, char *ebuf, int *is_ours)
308 {
309           pcap_t *p;
310 
311           if (strcmp(device, "dbus-system") &&
312                     strcmp(device, "dbus-session") &&
313                     strncmp(device, "dbus://", 7))
314           {
315                     *is_ours = 0;
316                     return NULL;
317           }
318 
319           *is_ours = 1;
320           p = PCAP_CREATE_COMMON(ebuf, struct pcap_dbus);
321           if (p == NULL)
322                     return (NULL);
323 
324           p->activate_op = dbus_activate;
325           /*
326            * Set these up front, so that, even if our client tries
327            * to set non-blocking mode before we're activated, or
328            * query the state of non-blocking mode, they get an error,
329            * rather than having the non-blocking mode option set
330            * for use later.
331            */
332           p->getnonblock_op = dbus_getnonblock;
333           p->setnonblock_op = dbus_setnonblock;
334           return (p);
335 }
336 
337 int
dbus_findalldevs(pcap_if_list_t * devlistp,char * err_str)338 dbus_findalldevs(pcap_if_list_t *devlistp, char *err_str)
339 {
340           /*
341            * The notion of "connected" vs. "disconnected" doesn't apply.
342            * XXX - what about the notions of "up" and "running"?
343            */
344           if (pcapint_add_dev(devlistp, "dbus-system",
345               PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE, "D-Bus system bus",
346               err_str) == NULL)
347                     return -1;
348           if (pcapint_add_dev(devlistp, "dbus-session",
349               PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE, "D-Bus session bus",
350               err_str) == NULL)
351                     return -1;
352           return 0;
353 }
354 
355