]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_divert.c
The r48589 promised to remove implicit inclusion of if_var.h soon. Prepare
[FreeBSD/FreeBSD.git] / sys / netinet / ip_divert.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.  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  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_sctp.h"
36 #ifndef INET
37 #error "IPDIVERT requires INET"
38 #endif
39
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/module.h>
46 #include <sys/kernel.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <net/vnet.h>
54
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/netisr.h> 
58
59 #include <netinet/in.h>
60 #include <netinet/in_pcb.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_var.h>
65 #ifdef INET6
66 #include <netinet/ip6.h>
67 #include <netinet6/ip6_var.h>
68 #endif
69 #ifdef SCTP
70 #include <netinet/sctp_crc32.h>
71 #endif
72
73 #include <security/mac/mac_framework.h>
74
75 /*
76  * Divert sockets
77  */
78
79 /*
80  * Allocate enough space to hold a full IP packet
81  */
82 #define DIVSNDQ         (65536 + 100)
83 #define DIVRCVQ         (65536 + 100)
84
85 /*
86  * Divert sockets work in conjunction with ipfw or other packet filters,
87  * see the divert(4) manpage for features.
88  * Packets are selected by the packet filter and tagged with an
89  * MTAG_IPFW_RULE tag carrying the 'divert port' number (as set by
90  * the packet filter) and information on the matching filter rule for
91  * subsequent reinjection. The divert_port is used to put the packet
92  * on the corresponding divert socket, while the rule number is passed
93  * up (at least partially) as the sin_port in the struct sockaddr.
94  *
95  * Packets written to the divert socket carry in sin_addr a
96  * destination address, and in sin_port the number of the filter rule
97  * after which to continue processing.
98  * If the destination address is INADDR_ANY, the packet is treated as
99  * as outgoing and sent to ip_output(); otherwise it is treated as
100  * incoming and sent to ip_input().
101  * Further, sin_zero carries some information on the interface,
102  * which can be used in the reinject -- see comments in the code.
103  *
104  * On reinjection, processing in ip_input() and ip_output()
105  * will be exactly the same as for the original packet, except that
106  * packet filter processing will start at the rule number after the one
107  * written in the sin_port (ipfw does not allow a rule #0, so sin_port=0
108  * will apply the entire ruleset to the packet).
109  */
110
111 /* Internal variables. */
112 static VNET_DEFINE(struct inpcbhead, divcb);
113 static VNET_DEFINE(struct inpcbinfo, divcbinfo);
114
115 #define V_divcb                         VNET(divcb)
116 #define V_divcbinfo                     VNET(divcbinfo)
117
118 static u_long   div_sendspace = DIVSNDQ;        /* XXX sysctl ? */
119 static u_long   div_recvspace = DIVRCVQ;        /* XXX sysctl ? */
120
121 static eventhandler_tag ip_divert_event_tag;
122
123 /*
124  * Initialize divert connection block queue.
125  */
126 static void
127 div_zone_change(void *tag)
128 {
129
130         uma_zone_set_max(V_divcbinfo.ipi_zone, maxsockets);
131 }
132
133 static int
134 div_inpcb_init(void *mem, int size, int flags)
135 {
136         struct inpcb *inp = mem;
137
138         INP_LOCK_INIT(inp, "inp", "divinp");
139         return (0);
140 }
141
142 static void
143 div_inpcb_fini(void *mem, int size)
144 {
145         struct inpcb *inp = mem;
146
147         INP_LOCK_DESTROY(inp);
148 }
149
150 static void
151 div_init(void)
152 {
153
154         /*
155          * XXX We don't use the hash list for divert IP, but it's easier to
156          * allocate one-entry hash lists than it is to check all over the
157          * place for hashbase == NULL.
158          */
159         in_pcbinfo_init(&V_divcbinfo, "div", &V_divcb, 1, 1, "divcb",
160             div_inpcb_init, div_inpcb_fini, UMA_ZONE_NOFREE,
161             IPI_HASHFIELDS_NONE);
162 }
163
164 static void
165 div_destroy(void)
166 {
167
168         in_pcbinfo_destroy(&V_divcbinfo);
169 }
170
171 /*
172  * IPPROTO_DIVERT is not in the real IP protocol number space; this
173  * function should never be called.  Just in case, drop any packets.
174  */
175 static void
176 div_input(struct mbuf *m, int off)
177 {
178
179         KMOD_IPSTAT_INC(ips_noproto);
180         m_freem(m);
181 }
182
183 /*
184  * Divert a packet by passing it up to the divert socket at port 'port'.
185  *
186  * Setup generic address and protocol structures for div_input routine,
187  * then pass them along with mbuf chain.
188  */
189 static void
190 divert_packet(struct mbuf *m, int incoming)
191 {
192         struct ip *ip;
193         struct inpcb *inp;
194         struct socket *sa;
195         u_int16_t nport;
196         struct sockaddr_in divsrc;
197         struct m_tag *mtag;
198
199         mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
200         if (mtag == NULL) {
201                 m_freem(m);
202                 return;
203         }
204         /* Assure header */
205         if (m->m_len < sizeof(struct ip) &&
206             (m = m_pullup(m, sizeof(struct ip))) == 0)
207                 return;
208         ip = mtod(m, struct ip *);
209
210         /* Delayed checksums are currently not compatible with divert. */
211         if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
212                 in_delayed_cksum(m);
213                 m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
214         }
215 #ifdef SCTP
216         if (m->m_pkthdr.csum_flags & CSUM_SCTP) {
217                 sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
218                 m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
219         }
220 #endif
221         bzero(&divsrc, sizeof(divsrc));
222         divsrc.sin_len = sizeof(divsrc);
223         divsrc.sin_family = AF_INET;
224         /* record matching rule, in host format */
225         divsrc.sin_port = ((struct ipfw_rule_ref *)(mtag+1))->rulenum;
226         /*
227          * Record receive interface address, if any.
228          * But only for incoming packets.
229          */
230         if (incoming) {
231                 struct ifaddr *ifa;
232                 struct ifnet *ifp;
233
234                 /* Sanity check */
235                 M_ASSERTPKTHDR(m);
236
237                 /* Find IP address for receive interface */
238                 ifp = m->m_pkthdr.rcvif;
239                 if_addr_rlock(ifp);
240                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
241                         if (ifa->ifa_addr->sa_family != AF_INET)
242                                 continue;
243                         divsrc.sin_addr =
244                             ((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
245                         break;
246                 }
247                 if_addr_runlock(ifp);
248         }
249         /*
250          * Record the incoming interface name whenever we have one.
251          */
252         if (m->m_pkthdr.rcvif) {
253                 /*
254                  * Hide the actual interface name in there in the 
255                  * sin_zero array. XXX This needs to be moved to a
256                  * different sockaddr type for divert, e.g.
257                  * sockaddr_div with multiple fields like 
258                  * sockaddr_dl. Presently we have only 7 bytes
259                  * but that will do for now as most interfaces
260                  * are 4 or less + 2 or less bytes for unit.
261                  * There is probably a faster way of doing this,
262                  * possibly taking it from the sockaddr_dl on the iface.
263                  * This solves the problem of a P2P link and a LAN interface
264                  * having the same address, which can result in the wrong
265                  * interface being assigned to the packet when fed back
266                  * into the divert socket. Theoretically if the daemon saves
267                  * and re-uses the sockaddr_in as suggested in the man pages,
268                  * this iface name will come along for the ride.
269                  * (see div_output for the other half of this.)
270                  */ 
271                 strlcpy(divsrc.sin_zero, m->m_pkthdr.rcvif->if_xname,
272                     sizeof(divsrc.sin_zero));
273         }
274
275         /* Put packet on socket queue, if any */
276         sa = NULL;
277         nport = htons((u_int16_t)(((struct ipfw_rule_ref *)(mtag+1))->info));
278         INP_INFO_RLOCK(&V_divcbinfo);
279         LIST_FOREACH(inp, &V_divcb, inp_list) {
280                 /* XXX why does only one socket match? */
281                 if (inp->inp_lport == nport) {
282                         INP_RLOCK(inp);
283                         sa = inp->inp_socket;
284                         SOCKBUF_LOCK(&sa->so_rcv);
285                         if (sbappendaddr_locked(&sa->so_rcv,
286                             (struct sockaddr *)&divsrc, m,
287                             (struct mbuf *)0) == 0) {
288                                 SOCKBUF_UNLOCK(&sa->so_rcv);
289                                 sa = NULL;      /* force mbuf reclaim below */
290                         } else
291                                 sorwakeup_locked(sa);
292                         INP_RUNLOCK(inp);
293                         break;
294                 }
295         }
296         INP_INFO_RUNLOCK(&V_divcbinfo);
297         if (sa == NULL) {
298                 m_freem(m);
299                 KMOD_IPSTAT_INC(ips_noproto);
300                 KMOD_IPSTAT_DEC(ips_delivered);
301         }
302 }
303
304 /*
305  * Deliver packet back into the IP processing machinery.
306  *
307  * If no address specified, or address is 0.0.0.0, send to ip_output();
308  * otherwise, send to ip_input() and mark as having been received on
309  * the interface with that address.
310  */
311 static int
312 div_output(struct socket *so, struct mbuf *m, struct sockaddr_in *sin,
313     struct mbuf *control)
314 {
315         struct ip *const ip = mtod(m, struct ip *);
316         struct m_tag *mtag;
317         struct ipfw_rule_ref *dt;
318         int error = 0;
319
320         /*
321          * An mbuf may hasn't come from userland, but we pretend
322          * that it has.
323          */
324         m->m_pkthdr.rcvif = NULL;
325         m->m_nextpkt = NULL;
326         M_SETFIB(m, so->so_fibnum);
327
328         if (control)
329                 m_freem(control);               /* XXX */
330
331         mtag = m_tag_locate(m, MTAG_IPFW_RULE, 0, NULL);
332         if (mtag == NULL) {
333                 /* this should be normal */
334                 mtag = m_tag_alloc(MTAG_IPFW_RULE, 0,
335                     sizeof(struct ipfw_rule_ref), M_NOWAIT | M_ZERO);
336                 if (mtag == NULL) {
337                         error = ENOBUFS;
338                         goto cantsend;
339                 }
340                 m_tag_prepend(m, mtag);
341         }
342         dt = (struct ipfw_rule_ref *)(mtag+1);
343
344         /* Loopback avoidance and state recovery */
345         if (sin) {
346                 int i;
347
348                 /* set the starting point. We provide a non-zero slot,
349                  * but a non_matching chain_id to skip that info and use
350                  * the rulenum/rule_id.
351                  */
352                 dt->slot = 1; /* dummy, chain_id is invalid */
353                 dt->chain_id = 0;
354                 dt->rulenum = sin->sin_port+1; /* host format ? */
355                 dt->rule_id = 0;
356                 /*
357                  * Find receive interface with the given name, stuffed
358                  * (if it exists) in the sin_zero[] field.
359                  * The name is user supplied data so don't trust its size
360                  * or that it is zero terminated.
361                  */
362                 for (i = 0; i < sizeof(sin->sin_zero) && sin->sin_zero[i]; i++)
363                         ;
364                 if ( i > 0 && i < sizeof(sin->sin_zero))
365                         m->m_pkthdr.rcvif = ifunit(sin->sin_zero);
366         }
367
368         /* Reinject packet into the system as incoming or outgoing */
369         if (!sin || sin->sin_addr.s_addr == 0) {
370                 struct mbuf *options = NULL;
371                 struct inpcb *inp;
372
373                 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_OUT;
374                 inp = sotoinpcb(so);
375                 INP_RLOCK(inp);
376                 switch (ip->ip_v) {
377                 case IPVERSION:
378                         /*
379                          * Don't allow both user specified and setsockopt
380                          * options, and don't allow packet length sizes that
381                          * will crash.
382                          */
383                         if ((((ip->ip_hl << 2) != sizeof(struct ip)) &&
384                             inp->inp_options != NULL) ||
385                             ((u_short)ntohs(ip->ip_len) > m->m_pkthdr.len)) {
386                                 error = EINVAL;
387                                 INP_RUNLOCK(inp);
388                                 goto cantsend;
389                         }
390                         break;
391 #ifdef INET6
392                 case IPV6_VERSION >> 4:
393                     {
394                         struct ip6_hdr *const ip6 = mtod(m, struct ip6_hdr *);
395
396                         /* Don't allow packet length sizes that will crash */
397                         if (((u_short)ntohs(ip6->ip6_plen) > m->m_pkthdr.len)) {
398                                 error = EINVAL;
399                                 INP_RUNLOCK(inp);
400                                 goto cantsend;
401                         }
402                         break;
403                     }
404 #endif
405                 default:
406                         error = EINVAL;
407                         INP_RUNLOCK(inp);
408                         goto cantsend;
409                 }
410
411                 /* Send packet to output processing */
412                 KMOD_IPSTAT_INC(ips_rawout);            /* XXX */
413
414 #ifdef MAC
415                 mac_inpcb_create_mbuf(inp, m);
416 #endif
417                 /*
418                  * Get ready to inject the packet into ip_output().
419                  * Just in case socket options were specified on the
420                  * divert socket, we duplicate them.  This is done
421                  * to avoid having to hold the PCB locks over the call
422                  * to ip_output(), as doing this results in a number of
423                  * lock ordering complexities.
424                  *
425                  * Note that we set the multicast options argument for
426                  * ip_output() to NULL since it should be invariant that
427                  * they are not present.
428                  */
429                 KASSERT(inp->inp_moptions == NULL,
430                     ("multicast options set on a divert socket"));
431                 /*
432                  * XXXCSJP: It is unclear to me whether or not it makes
433                  * sense for divert sockets to have options.  However,
434                  * for now we will duplicate them with the INP locks
435                  * held so we can use them in ip_output() without
436                  * requring a reference to the pcb.
437                  */
438                 if (inp->inp_options != NULL) {
439                         options = m_dup(inp->inp_options, M_NOWAIT);
440                         if (options == NULL) {
441                                 INP_RUNLOCK(inp);
442                                 error = ENOBUFS;
443                                 goto cantsend;
444                         }
445                 }
446                 INP_RUNLOCK(inp);
447
448                 switch (ip->ip_v) {
449                 case IPVERSION:
450                         error = ip_output(m, options, NULL,
451                             ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0)
452                             | IP_ALLOWBROADCAST | IP_RAWOUTPUT, NULL, NULL);
453                         break;
454 #ifdef INET6
455                 case IPV6_VERSION >> 4:
456                         error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
457                         break;
458 #endif
459                 }
460                 if (options != NULL)
461                         m_freem(options);
462         } else {
463                 dt->info |= IPFW_IS_DIVERT | IPFW_INFO_IN;
464                 if (m->m_pkthdr.rcvif == NULL) {
465                         /*
466                          * No luck with the name, check by IP address.
467                          * Clear the port and the ifname to make sure
468                          * there are no distractions for ifa_ifwithaddr.
469                          */
470                         struct  ifaddr *ifa;
471
472                         bzero(sin->sin_zero, sizeof(sin->sin_zero));
473                         sin->sin_port = 0;
474                         ifa = ifa_ifwithaddr((struct sockaddr *) sin);
475                         if (ifa == NULL) {
476                                 error = EADDRNOTAVAIL;
477                                 goto cantsend;
478                         }
479                         m->m_pkthdr.rcvif = ifa->ifa_ifp;
480                         ifa_free(ifa);
481                 }
482 #ifdef MAC
483                 mac_socket_create_mbuf(so, m);
484 #endif
485                 /* Send packet to input processing via netisr */
486                 switch (ip->ip_v) {
487                 case IPVERSION:
488                         netisr_queue_src(NETISR_IP, (uintptr_t)so, m);
489                         break;
490 #ifdef INET6
491                 case IPV6_VERSION >> 4:
492                         netisr_queue_src(NETISR_IPV6, (uintptr_t)so, m);
493                         break;
494 #endif
495                 default:
496                         error = EINVAL;
497                         goto cantsend;
498                 }
499         }
500
501         return (error);
502
503 cantsend:
504         m_freem(m);
505         return (error);
506 }
507
508 static int
509 div_attach(struct socket *so, int proto, struct thread *td)
510 {
511         struct inpcb *inp;
512         int error;
513
514         inp  = sotoinpcb(so);
515         KASSERT(inp == NULL, ("div_attach: inp != NULL"));
516         if (td != NULL) {
517                 error = priv_check(td, PRIV_NETINET_DIVERT);
518                 if (error)
519                         return (error);
520         }
521         error = soreserve(so, div_sendspace, div_recvspace);
522         if (error)
523                 return error;
524         INP_INFO_WLOCK(&V_divcbinfo);
525         error = in_pcballoc(so, &V_divcbinfo);
526         if (error) {
527                 INP_INFO_WUNLOCK(&V_divcbinfo);
528                 return error;
529         }
530         inp = (struct inpcb *)so->so_pcb;
531         INP_INFO_WUNLOCK(&V_divcbinfo);
532         inp->inp_ip_p = proto;
533         inp->inp_vflag |= INP_IPV4;
534         inp->inp_flags |= INP_HDRINCL;
535         INP_WUNLOCK(inp);
536         return 0;
537 }
538
539 static void
540 div_detach(struct socket *so)
541 {
542         struct inpcb *inp;
543
544         inp = sotoinpcb(so);
545         KASSERT(inp != NULL, ("div_detach: inp == NULL"));
546         INP_INFO_WLOCK(&V_divcbinfo);
547         INP_WLOCK(inp);
548         in_pcbdetach(inp);
549         in_pcbfree(inp);
550         INP_INFO_WUNLOCK(&V_divcbinfo);
551 }
552
553 static int
554 div_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
555 {
556         struct inpcb *inp;
557         int error;
558
559         inp = sotoinpcb(so);
560         KASSERT(inp != NULL, ("div_bind: inp == NULL"));
561         /* in_pcbbind assumes that nam is a sockaddr_in
562          * and in_pcbbind requires a valid address. Since divert
563          * sockets don't we need to make sure the address is
564          * filled in properly.
565          * XXX -- divert should not be abusing in_pcbind
566          * and should probably have its own family.
567          */
568         if (nam->sa_family != AF_INET)
569                 return EAFNOSUPPORT;
570         ((struct sockaddr_in *)nam)->sin_addr.s_addr = INADDR_ANY;
571         INP_INFO_WLOCK(&V_divcbinfo);
572         INP_WLOCK(inp);
573         INP_HASH_WLOCK(&V_divcbinfo);
574         error = in_pcbbind(inp, nam, td->td_ucred);
575         INP_HASH_WUNLOCK(&V_divcbinfo);
576         INP_WUNLOCK(inp);
577         INP_INFO_WUNLOCK(&V_divcbinfo);
578         return error;
579 }
580
581 static int
582 div_shutdown(struct socket *so)
583 {
584         struct inpcb *inp;
585
586         inp = sotoinpcb(so);
587         KASSERT(inp != NULL, ("div_shutdown: inp == NULL"));
588         INP_WLOCK(inp);
589         socantsendmore(so);
590         INP_WUNLOCK(inp);
591         return 0;
592 }
593
594 static int
595 div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
596     struct mbuf *control, struct thread *td)
597 {
598
599         /* Packet must have a header (but that's about it) */
600         if (m->m_len < sizeof (struct ip) &&
601             (m = m_pullup(m, sizeof (struct ip))) == 0) {
602                 KMOD_IPSTAT_INC(ips_toosmall);
603                 m_freem(m);
604                 return EINVAL;
605         }
606
607         /* Send packet */
608         return div_output(so, m, (struct sockaddr_in *)nam, control);
609 }
610
611 static void
612 div_ctlinput(int cmd, struct sockaddr *sa, void *vip)
613 {
614         struct in_addr faddr;
615
616         faddr = ((struct sockaddr_in *)sa)->sin_addr;
617         if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
618                 return;
619         if (PRC_IS_REDIRECT(cmd))
620                 return;
621 }
622
623 static int
624 div_pcblist(SYSCTL_HANDLER_ARGS)
625 {
626         int error, i, n;
627         struct inpcb *inp, **inp_list;
628         inp_gen_t gencnt;
629         struct xinpgen xig;
630
631         /*
632          * The process of preparing the TCB list is too time-consuming and
633          * resource-intensive to repeat twice on every request.
634          */
635         if (req->oldptr == 0) {
636                 n = V_divcbinfo.ipi_count;
637                 n += imax(n / 8, 10);
638                 req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
639                 return 0;
640         }
641
642         if (req->newptr != 0)
643                 return EPERM;
644
645         /*
646          * OK, now we're committed to doing something.
647          */
648         INP_INFO_RLOCK(&V_divcbinfo);
649         gencnt = V_divcbinfo.ipi_gencnt;
650         n = V_divcbinfo.ipi_count;
651         INP_INFO_RUNLOCK(&V_divcbinfo);
652
653         error = sysctl_wire_old_buffer(req,
654             2 * sizeof(xig) + n*sizeof(struct xinpcb));
655         if (error != 0)
656                 return (error);
657
658         xig.xig_len = sizeof xig;
659         xig.xig_count = n;
660         xig.xig_gen = gencnt;
661         xig.xig_sogen = so_gencnt;
662         error = SYSCTL_OUT(req, &xig, sizeof xig);
663         if (error)
664                 return error;
665
666         inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
667         if (inp_list == 0)
668                 return ENOMEM;
669         
670         INP_INFO_RLOCK(&V_divcbinfo);
671         for (inp = LIST_FIRST(V_divcbinfo.ipi_listhead), i = 0; inp && i < n;
672              inp = LIST_NEXT(inp, inp_list)) {
673                 INP_WLOCK(inp);
674                 if (inp->inp_gencnt <= gencnt &&
675                     cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
676                         in_pcbref(inp);
677                         inp_list[i++] = inp;
678                 }
679                 INP_WUNLOCK(inp);
680         }
681         INP_INFO_RUNLOCK(&V_divcbinfo);
682         n = i;
683
684         error = 0;
685         for (i = 0; i < n; i++) {
686                 inp = inp_list[i];
687                 INP_RLOCK(inp);
688                 if (inp->inp_gencnt <= gencnt) {
689                         struct xinpcb xi;
690                         bzero(&xi, sizeof(xi));
691                         xi.xi_len = sizeof xi;
692                         /* XXX should avoid extra copy */
693                         bcopy(inp, &xi.xi_inp, sizeof *inp);
694                         if (inp->inp_socket)
695                                 sotoxsocket(inp->inp_socket, &xi.xi_socket);
696                         INP_RUNLOCK(inp);
697                         error = SYSCTL_OUT(req, &xi, sizeof xi);
698                 } else
699                         INP_RUNLOCK(inp);
700         }
701         INP_INFO_WLOCK(&V_divcbinfo);
702         for (i = 0; i < n; i++) {
703                 inp = inp_list[i];
704                 INP_RLOCK(inp);
705                 if (!in_pcbrele_rlocked(inp))
706                         INP_RUNLOCK(inp);
707         }
708         INP_INFO_WUNLOCK(&V_divcbinfo);
709
710         if (!error) {
711                 /*
712                  * Give the user an updated idea of our state.
713                  * If the generation differs from what we told
714                  * her before, she knows that something happened
715                  * while we were processing this request, and it
716                  * might be necessary to retry.
717                  */
718                 INP_INFO_RLOCK(&V_divcbinfo);
719                 xig.xig_gen = V_divcbinfo.ipi_gencnt;
720                 xig.xig_sogen = so_gencnt;
721                 xig.xig_count = V_divcbinfo.ipi_count;
722                 INP_INFO_RUNLOCK(&V_divcbinfo);
723                 error = SYSCTL_OUT(req, &xig, sizeof xig);
724         }
725         free(inp_list, M_TEMP);
726         return error;
727 }
728
729 #ifdef SYSCTL_NODE
730 static SYSCTL_NODE(_net_inet, IPPROTO_DIVERT, divert, CTLFLAG_RW, 0,
731     "IPDIVERT");
732 SYSCTL_PROC(_net_inet_divert, OID_AUTO, pcblist, CTLTYPE_OPAQUE | CTLFLAG_RD,
733     NULL, 0, div_pcblist, "S,xinpcb", "List of active divert sockets");
734 #endif
735
736 struct pr_usrreqs div_usrreqs = {
737         .pru_attach =           div_attach,
738         .pru_bind =             div_bind,
739         .pru_control =          in_control,
740         .pru_detach =           div_detach,
741         .pru_peeraddr =         in_getpeeraddr,
742         .pru_send =             div_send,
743         .pru_shutdown =         div_shutdown,
744         .pru_sockaddr =         in_getsockaddr,
745         .pru_sosetlabel =       in_pcbsosetlabel
746 };
747
748 struct protosw div_protosw = {
749         .pr_type =              SOCK_RAW,
750         .pr_protocol =          IPPROTO_DIVERT,
751         .pr_flags =             PR_ATOMIC|PR_ADDR,
752         .pr_input =             div_input,
753         .pr_ctlinput =          div_ctlinput,
754         .pr_ctloutput =         ip_ctloutput,
755         .pr_init =              div_init,
756 #ifdef VIMAGE
757         .pr_destroy =           div_destroy,
758 #endif
759         .pr_usrreqs =           &div_usrreqs
760 };
761
762 static int
763 div_modevent(module_t mod, int type, void *unused)
764 {
765         int err = 0;
766 #ifndef VIMAGE
767         int n;
768 #endif
769
770         switch (type) {
771         case MOD_LOAD:
772                 /*
773                  * Protocol will be initialized by pf_proto_register().
774                  * We don't have to register ip_protox because we are not
775                  * a true IP protocol that goes over the wire.
776                  */
777                 err = pf_proto_register(PF_INET, &div_protosw);
778                 if (err != 0)
779                         return (err);
780                 ip_divert_ptr = divert_packet;
781                 ip_divert_event_tag = EVENTHANDLER_REGISTER(maxsockets_change,
782                     div_zone_change, NULL, EVENTHANDLER_PRI_ANY);
783                 break;
784         case MOD_QUIESCE:
785                 /*
786                  * IPDIVERT may normally not be unloaded because of the
787                  * potential race conditions.  Tell kldunload we can't be
788                  * unloaded unless the unload is forced.
789                  */
790                 err = EPERM;
791                 break;
792         case MOD_UNLOAD:
793 #ifdef VIMAGE
794                 err = EPERM;
795                 break;
796 #else
797                 /*
798                  * Forced unload.
799                  *
800                  * Module ipdivert can only be unloaded if no sockets are
801                  * connected.  Maybe this can be changed later to forcefully
802                  * disconnect any open sockets.
803                  *
804                  * XXXRW: Note that there is a slight race here, as a new
805                  * socket open request could be spinning on the lock and then
806                  * we destroy the lock.
807                  */
808                 INP_INFO_WLOCK(&V_divcbinfo);
809                 n = V_divcbinfo.ipi_count;
810                 if (n != 0) {
811                         err = EBUSY;
812                         INP_INFO_WUNLOCK(&V_divcbinfo);
813                         break;
814                 }
815                 ip_divert_ptr = NULL;
816                 err = pf_proto_unregister(PF_INET, IPPROTO_DIVERT, SOCK_RAW);
817                 INP_INFO_WUNLOCK(&V_divcbinfo);
818                 div_destroy();
819                 EVENTHANDLER_DEREGISTER(maxsockets_change, ip_divert_event_tag);
820                 break;
821 #endif /* !VIMAGE */
822         default:
823                 err = EOPNOTSUPP;
824                 break;
825         }
826         return err;
827 }
828
829 static moduledata_t ipdivertmod = {
830         "ipdivert",
831         div_modevent,
832         0
833 };
834
835 DECLARE_MODULE(ipdivert, ipdivertmod, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY);
836 MODULE_DEPEND(ipdivert, ipfw, 2, 2, 2);
837 MODULE_VERSION(ipdivert, 1);