Our raw socket expects ip.{ip_len,ip_off} in host byte order.
[dragonfly.git] / sbin / dhclient / bpf.c
1 /*      $OpenBSD: bpf.c,v 1.20 2007/01/08 02:51:13 krw Exp $    */
2 /*      $DragonFly: src/sbin/dhclient/bpf.c,v 1.2 2008/11/05 14:08:41 sephe Exp $       */
3
4 /* BPF socket interface code, originally contributed by Archie Cobbs. */
5
6 /*
7  * Copyright (c) 1995, 1996, 1998, 1999
8  * The Internet Software Consortium.    All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of The Internet Software Consortium nor the names
20  *    of its contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
24  * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
25  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
28  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
30  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
31  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
34  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  * This software has been written for the Internet Software Consortium
38  * by Ted Lemon <mellon@fugue.com> in cooperation with Vixie
39  * Enterprises.  To learn more about the Internet Software Consortium,
40  * see ``http://www.vix.com/isc''.  To learn more about Vixie
41  * Enterprises, see ``http://www.vix.com''.
42  */
43
44 #include <sys/ioctl.h>
45 #include <sys/uio.h>
46
47 #include <net/bpf.h>
48 #include <netinet/if_ether.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/udp.h>
52
53 #include "dhcpd.h"
54
55 #define BPF_FORMAT "/dev/bpf%d"
56
57 /*
58  * Called by get_interface_list for each interface that's discovered.
59  * Opens a packet filter for each interface and adds it to the select
60  * mask.
61  */
62 int
63 if_register_bpf(void)
64 {
65         char filename[50];
66         int sock, b;
67
68         /* Open a BPF device */
69         for (b = 0; 1; b++) {
70                 snprintf(filename, sizeof(filename), BPF_FORMAT, b);
71                 sock = open(filename, O_RDWR, 0);
72                 if (sock < 0) {
73                         if (errno == EBUSY)
74                                 continue;
75                         else
76                                 error("Can't find free bpf: %m");
77                 } else
78                         break;
79         }
80
81         /* Set the BPF device to point at this interface. */
82         if (ioctl(sock, BIOCSETIF, ifi->ifp) < 0)
83                 error("Can't attach interface %s to bpf device %s: %m",
84                     ifi->name, filename);
85
86         return (sock);
87 }
88
89 void
90 if_register_send(void)
91 {
92         int sock, on = 1;
93
94         /*
95          * If we're using the bpf API for sending and receiving, we
96          * don't need to register this interface twice.
97          */
98         ifi->wfdesc = ifi->rfdesc;
99
100         /*
101          * Use raw socket for unicast send.
102          */
103         if ((sock = socket(AF_INET, SOCK_RAW, IPPROTO_UDP)) == -1)
104                 error("socket(SOCK_RAW): %m");
105         if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on,
106             sizeof(on)) == -1)
107                 error("setsockopt(IP_HDRINCL): %m");
108         ifi->ufdesc = sock;
109 }
110
111 /*
112  * Packet filter program...
113  *
114  * XXX: Changes to the filter program may require changes to the
115  * constant offsets used in if_register_send to patch the BPF program!
116  */
117 struct bpf_insn dhcp_bpf_filter[] = {
118         /* Make sure this is an IP packet... */
119         BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
120         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),
121
122         /* Make sure it's a UDP packet... */
123         BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
124         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),
125
126         /* Make sure this isn't a fragment... */
127         BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
128         BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),
129
130         /* Get the IP header length... */
131         BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
132
133         /* Make sure it's to the right port... */
134         BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
135         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 67, 0, 1),          /* patch */
136
137         /* If we passed all the tests, ask for the whole packet. */
138         BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
139
140         /* Otherwise, drop it. */
141         BPF_STMT(BPF_RET+BPF_K, 0),
142 };
143
144 int dhcp_bpf_filter_len = sizeof(dhcp_bpf_filter) / sizeof(struct bpf_insn);
145
146 /*
147  * Packet write filter program:
148  * 'ip and udp and src port bootps and dst port (bootps or bootpc)'
149  */
150 struct bpf_insn dhcp_bpf_wfilter[] = {
151         BPF_STMT(BPF_LD + BPF_B + BPF_IND, 14),
152         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, (IPVERSION << 4) + 5, 0, 12),
153
154         /* Make sure this is an IP packet... */
155         BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12),
156         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 10),
157
158         /* Make sure it's a UDP packet... */
159         BPF_STMT(BPF_LD + BPF_B + BPF_ABS, 23),
160         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 8),
161
162         /* Make sure this isn't a fragment... */
163         BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
164         BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 6, 0),     /* patched */
165
166         /* Get the IP header length... */
167         BPF_STMT(BPF_LDX + BPF_B + BPF_MSH, 14),
168
169         /* Make sure it's from the right port... */
170         BPF_STMT(BPF_LD + BPF_H + BPF_IND, 14),
171         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 68, 0, 3),
172
173         /* Make sure it is to the right ports ... */
174         BPF_STMT(BPF_LD + BPF_H + BPF_IND, 16),
175         BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, 67, 0, 1),
176
177         /* If we passed all the tests, ask for the whole packet. */
178         BPF_STMT(BPF_RET+BPF_K, (u_int)-1),
179
180         /* Otherwise, drop it. */
181         BPF_STMT(BPF_RET+BPF_K, 0),
182 };
183
184 int dhcp_bpf_wfilter_len = sizeof(dhcp_bpf_wfilter) / sizeof(struct bpf_insn);
185
186 void
187 if_register_receive(void)
188 {
189         struct bpf_version v;
190         struct bpf_program p;
191         int flag = 1, sz;
192
193         /* Open a BPF device and hang it on this interface... */
194         ifi->rfdesc = if_register_bpf();
195
196         /* Make sure the BPF version is in range... */
197         if (ioctl(ifi->rfdesc, BIOCVERSION, &v) < 0)
198                 error("Can't get BPF version: %m");
199
200         if (v.bv_major != BPF_MAJOR_VERSION ||
201             v.bv_minor < BPF_MINOR_VERSION)
202                 error("Kernel BPF version out of range - recompile dhcpd!");
203
204         /*
205          * Set immediate mode so that reads return as soon as a packet
206          * comes in, rather than waiting for the input buffer to fill
207          * with packets.
208          */
209         if (ioctl(ifi->rfdesc, BIOCIMMEDIATE, &flag) < 0)
210                 error("Can't set immediate mode on bpf device: %m");
211
212         /*if (ioctl(ifi->rfdesc, BIOCSFILDROP, &flag) < 0)
213                 error("Can't set filter-drop mode on bpf device: %m");*/
214
215         /* Get the required BPF buffer length from the kernel. */
216         if (ioctl(ifi->rfdesc, BIOCGBLEN, &sz) < 0)
217                 error("Can't get bpf buffer length: %m");
218         ifi->rbuf_max = sz;
219         ifi->rbuf = malloc(ifi->rbuf_max);
220         if (!ifi->rbuf)
221                 error("Can't allocate %lu bytes for bpf input buffer.",
222                     (unsigned long)ifi->rbuf_max);
223         ifi->rbuf_offset = 0;
224         ifi->rbuf_len = 0;
225
226         /* Set up the bpf filter program structure. */
227         p.bf_len = dhcp_bpf_filter_len;
228         p.bf_insns = dhcp_bpf_filter;
229
230         /* Patch the server port into the BPF program...
231          *
232          * XXX: changes to filter program may require changes to the
233          * insn number(s) used below!
234          */
235         dhcp_bpf_filter[8].k = LOCAL_PORT;
236
237         if (ioctl(ifi->rfdesc, BIOCSETF, &p) < 0)
238                 error("Can't install packet filter program: %m");
239
240         /* Set up the bpf write filter program structure. */
241         p.bf_len = dhcp_bpf_wfilter_len;
242         p.bf_insns = dhcp_bpf_wfilter;
243
244         if (dhcp_bpf_wfilter[7].k == 0x1fff)
245                 dhcp_bpf_wfilter[7].k = htons(IP_MF|IP_OFFMASK);
246
247         if (ioctl(ifi->rfdesc, BIOCSETWF, &p) < 0)
248                 error("Can't install write filter program: %m");
249
250         if (ioctl(ifi->rfdesc, BIOCLOCK, NULL) < 0)
251                 error("Cannot lock bpf");
252 }
253
254 ssize_t
255 send_packet(struct in_addr from, struct sockaddr_in *to,
256     struct hardware *hto)
257 {
258 #define IOVCNT          2
259         unsigned char buf[256];
260         struct iovec iov[IOVCNT];
261         struct msghdr msg;
262         int result, bufp = 0;
263
264         if (to->sin_addr.s_addr == INADDR_BROADCAST) {
265                 assemble_hw_header(buf, &bufp, hto);
266         }
267
268         assemble_udp_ip_header(buf, &bufp, from.s_addr,
269             to->sin_addr.s_addr, to->sin_port,
270             (unsigned char *)&client->packet,
271             client->packet_length);
272
273         iov[0].iov_base = (char *)buf;
274         iov[0].iov_len = bufp;
275         iov[1].iov_base = (char *)&client->packet;
276         iov[1].iov_len = client->packet_length;
277
278         if (to->sin_addr.s_addr == INADDR_BROADCAST) {
279                 result = writev(ifi->wfdesc, iov, IOVCNT);
280         } else {
281                 struct ip *ip = (struct ip *)buf;
282
283                 /*
284                  * DragonFly's raw socket expects ip_len/ip_off
285                  * in host byte order.
286                  */
287                 ip->ip_len = ntohs(ip->ip_len);
288                 ip->ip_off = ntohs(ip->ip_off);
289
290                 memset(&msg, 0, sizeof(msg));
291                 msg.msg_name = (struct sockaddr *)to;
292                 msg.msg_namelen = sizeof(*to);
293                 msg.msg_iov = iov;
294                 msg.msg_iovlen = IOVCNT;
295                 result = sendmsg(ifi->ufdesc, &msg, 0);
296         }
297
298         if (result == -1)
299                 warning("send_packet: %m");
300         return (result);
301 }
302
303 ssize_t
304 receive_packet(struct sockaddr_in *from, struct hardware *hfrom)
305 {
306         int length = 0, offset = 0;
307         struct bpf_hdr hdr;
308
309         /*
310          * All this complexity is because BPF doesn't guarantee that
311          * only one packet will be returned at a time.  We're getting
312          * what we deserve, though - this is a terrible abuse of the BPF
313          * interface.  Sigh.
314          */
315
316         /* Process packets until we get one we can return or until we've
317          * done a read and gotten nothing we can return...
318          */
319         do {
320                 /* If the buffer is empty, fill it. */
321                 if (ifi->rbuf_offset == ifi->rbuf_len) {
322                         length = read(ifi->rfdesc, ifi->rbuf, ifi->rbuf_max);
323                         if (length <= 0)
324                                 return (length);
325                         ifi->rbuf_offset = 0;
326                         ifi->rbuf_len = BPF_WORDALIGN(length);
327                 }
328
329                 /*
330                  * If there isn't room for a whole bpf header, something
331                  * went wrong, but we'll ignore it and hope it goes
332                  * away... XXX
333                  */
334                 if (ifi->rbuf_len - ifi->rbuf_offset < sizeof(hdr)) {
335                         ifi->rbuf_offset = ifi->rbuf_len;
336                         continue;
337                 }
338
339                 /* Copy out a bpf header... */
340                 memcpy(&hdr, &ifi->rbuf[ifi->rbuf_offset], sizeof(hdr));
341
342                 /*
343                  * If the bpf header plus data doesn't fit in what's
344                  * left of the buffer, stick head in sand yet again...
345                  */
346                 if (ifi->rbuf_offset + hdr.bh_hdrlen + hdr.bh_caplen >
347                     ifi->rbuf_len) {
348                         ifi->rbuf_offset = ifi->rbuf_len;
349                         continue;
350                 }
351
352                 /*
353                  * If the captured data wasn't the whole packet, or if
354                  * the packet won't fit in the input buffer, all we can
355                  * do is drop it.
356                  */
357                 if (hdr.bh_caplen != hdr.bh_datalen) {
358                         ifi->rbuf_offset = BPF_WORDALIGN(
359                             ifi->rbuf_offset + hdr.bh_hdrlen +
360                             hdr.bh_caplen);
361                         continue;
362                 }
363
364                 /* Skip over the BPF header... */
365                 ifi->rbuf_offset += hdr.bh_hdrlen;
366
367                 /* Decode the physical header... */
368                 offset = decode_hw_header(ifi->rbuf, ifi->rbuf_offset, hfrom);
369
370                 /*
371                  * If a physical layer checksum failed (dunno of any
372                  * physical layer that supports this, but WTH), skip
373                  * this packet.
374                  */
375                 if (offset < 0) {
376                         ifi->rbuf_offset = BPF_WORDALIGN(
377                             ifi->rbuf_offset + hdr.bh_caplen);
378                         continue;
379                 }
380                 ifi->rbuf_offset += offset;
381                 hdr.bh_caplen -= offset;
382
383                 /* Decode the IP and UDP headers... */
384                 offset = decode_udp_ip_header(ifi->rbuf,
385                     ifi->rbuf_offset, from, NULL, hdr.bh_caplen);
386
387                 /* If the IP or UDP checksum was bad, skip the packet... */
388                 if (offset < 0) {
389                         ifi->rbuf_offset = BPF_WORDALIGN(
390                             ifi->rbuf_offset + hdr.bh_caplen);
391                         continue;
392                 }
393                 ifi->rbuf_offset += offset;
394                 hdr.bh_caplen -= offset;
395
396                 /*
397                  * If there's not enough room to stash the packet data,
398                  * we have to skip it (this shouldn't happen in real
399                  * life, though).
400                  */
401                 if (hdr.bh_caplen > sizeof(client->packet)) {
402                         ifi->rbuf_offset = BPF_WORDALIGN(
403                             ifi->rbuf_offset + hdr.bh_caplen);
404                         continue;
405                 }
406
407                 /* Copy out the data in the packet... */
408                 memset(&client->packet, DHO_END, sizeof(client->packet));
409                 memcpy(&client->packet, ifi->rbuf + ifi->rbuf_offset,
410                     hdr.bh_caplen);
411                 ifi->rbuf_offset = BPF_WORDALIGN(ifi->rbuf_offset +
412                     hdr.bh_caplen);
413                 return (hdr.bh_caplen);
414         } while (!length);
415         return (0);
416 }