The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netgraph/ng_bpf.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

    1 /*
    2  * ng_bpf.c
    3  */
    4 
    5 /*-
    6  * Copyright (c) 1999 Whistle Communications, Inc.
    7  * All rights reserved.
    8  * 
    9  * Subject to the following obligations and disclaimer of warranty, use and
   10  * redistribution of this software, in source or object code forms, with or
   11  * without modifications are expressly permitted by Whistle Communications;
   12  * provided, however, that:
   13  * 1. Any and all reproductions of the source or object code must include the
   14  *    copyright notice above and the following disclaimer of warranties; and
   15  * 2. No rights are granted, in any manner or form, to use Whistle
   16  *    Communications, Inc. trademarks, including the mark "WHISTLE
   17  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
   18  *    such appears in the above copyright notice or in the software.
   19  * 
   20  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
   21  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
   22  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
   23  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
   24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
   25  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
   26  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
   27  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
   28  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
   29  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
   30  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
   31  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
   32  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
   33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   35  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
   36  * OF SUCH DAMAGE.
   37  *
   38  * Author: Archie Cobbs <archie@freebsd.org>
   39  *
   40  * $FreeBSD$
   41  * $Whistle: ng_bpf.c,v 1.3 1999/12/03 20:30:23 archie Exp $
   42  */
   43 
   44 /*
   45  * BPF NETGRAPH NODE TYPE
   46  *
   47  * This node type accepts any number of hook connections.  With each hook
   48  * is associated a bpf(4) filter program, and two hook names (each possibly
   49  * the empty string).  Incoming packets are compared against the filter;
   50  * matching packets are delivered out the first named hook (or dropped if
   51  * the empty string), and non-matching packets are delivered out the second
   52  * named hook (or dropped if the empty string).
   53  *
   54  * Each hook also keeps statistics about how many packets have matched, etc.
   55  */
   56 
   57 #include <sys/param.h>
   58 #include <sys/systm.h>
   59 #include <sys/errno.h>
   60 #include <sys/kernel.h>
   61 #include <sys/malloc.h>
   62 #include <sys/mbuf.h>
   63 
   64 #include <net/bpf.h>
   65 
   66 #include <netgraph/ng_message.h>
   67 #include <netgraph/netgraph.h>
   68 #include <netgraph/ng_parse.h>
   69 #include <netgraph/ng_bpf.h>
   70 
   71 #ifdef NG_SEPARATE_MALLOC
   72 MALLOC_DEFINE(M_NETGRAPH_BPF, "netgraph_bpf", "netgraph bpf node ");
   73 #else
   74 #define M_NETGRAPH_BPF M_NETGRAPH
   75 #endif
   76 
   77 #define OFFSETOF(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
   78 
   79 #define ERROUT(x)       do { error = (x); goto done; } while (0)
   80 
   81 /* Per hook private info */
   82 struct ng_bpf_hookinfo {
   83         hook_p                  hook;
   84         hook_p                  match;
   85         hook_p                  nomatch;
   86         struct ng_bpf_hookprog  *prog;
   87         struct ng_bpf_hookstat  stats;
   88 };
   89 typedef struct ng_bpf_hookinfo *hinfo_p;
   90 
   91 /* Netgraph methods */
   92 static ng_constructor_t ng_bpf_constructor;
   93 static ng_rcvmsg_t      ng_bpf_rcvmsg;
   94 static ng_shutdown_t    ng_bpf_shutdown;
   95 static ng_newhook_t     ng_bpf_newhook;
   96 static ng_rcvdata_t     ng_bpf_rcvdata;
   97 static ng_disconnect_t  ng_bpf_disconnect;
   98 
   99 /* Internal helper functions */
  100 static int      ng_bpf_setprog(hook_p hook, const struct ng_bpf_hookprog *hp);
  101 
  102 /* Parse type for one struct bfp_insn */
  103 static const struct ng_parse_struct_field ng_bpf_insn_type_fields[] = {
  104         { "code",       &ng_parse_hint16_type   },
  105         { "jt",         &ng_parse_uint8_type    },
  106         { "jf",         &ng_parse_uint8_type    },
  107         { "k",          &ng_parse_uint32_type   },
  108         { NULL }
  109 };
  110 static const struct ng_parse_type ng_bpf_insn_type = {
  111         &ng_parse_struct_type,
  112         &ng_bpf_insn_type_fields
  113 };
  114 
  115 /* Parse type for the field 'bpf_prog' in struct ng_bpf_hookprog */
  116 static int
  117 ng_bpf_hookprogary_getLength(const struct ng_parse_type *type,
  118         const u_char *start, const u_char *buf)
  119 {
  120         const struct ng_bpf_hookprog *hp;
  121 
  122         hp = (const struct ng_bpf_hookprog *)
  123             (buf - OFFSETOF(struct ng_bpf_hookprog, bpf_prog));
  124         return hp->bpf_prog_len;
  125 }
  126 
  127 static const struct ng_parse_array_info ng_bpf_hookprogary_info = {
  128         &ng_bpf_insn_type,
  129         &ng_bpf_hookprogary_getLength,
  130         NULL
  131 };
  132 static const struct ng_parse_type ng_bpf_hookprogary_type = {
  133         &ng_parse_array_type,
  134         &ng_bpf_hookprogary_info
  135 };
  136 
  137 /* Parse type for struct ng_bpf_hookprog */
  138 static const struct ng_parse_struct_field ng_bpf_hookprog_type_fields[]
  139         = NG_BPF_HOOKPROG_TYPE_INFO(&ng_bpf_hookprogary_type);
  140 static const struct ng_parse_type ng_bpf_hookprog_type = {
  141         &ng_parse_struct_type,
  142         &ng_bpf_hookprog_type_fields
  143 };
  144 
  145 /* Parse type for struct ng_bpf_hookstat */
  146 static const struct ng_parse_struct_field ng_bpf_hookstat_type_fields[]
  147         = NG_BPF_HOOKSTAT_TYPE_INFO;
  148 static const struct ng_parse_type ng_bpf_hookstat_type = {
  149         &ng_parse_struct_type,
  150         &ng_bpf_hookstat_type_fields
  151 };
  152 
  153 /* List of commands and how to convert arguments to/from ASCII */
  154 static const struct ng_cmdlist ng_bpf_cmdlist[] = {
  155         {
  156           NGM_BPF_COOKIE,
  157           NGM_BPF_SET_PROGRAM,
  158           "setprogram",
  159           &ng_bpf_hookprog_type,
  160           NULL
  161         },
  162         {
  163           NGM_BPF_COOKIE,
  164           NGM_BPF_GET_PROGRAM,
  165           "getprogram",
  166           &ng_parse_hookbuf_type,
  167           &ng_bpf_hookprog_type
  168         },
  169         {
  170           NGM_BPF_COOKIE,
  171           NGM_BPF_GET_STATS,
  172           "getstats",
  173           &ng_parse_hookbuf_type,
  174           &ng_bpf_hookstat_type
  175         },
  176         {
  177           NGM_BPF_COOKIE,
  178           NGM_BPF_CLR_STATS,
  179           "clrstats",
  180           &ng_parse_hookbuf_type,
  181           NULL
  182         },
  183         {
  184           NGM_BPF_COOKIE,
  185           NGM_BPF_GETCLR_STATS,
  186           "getclrstats",
  187           &ng_parse_hookbuf_type,
  188           &ng_bpf_hookstat_type
  189         },
  190         { 0 }
  191 };
  192 
  193 /* Netgraph type descriptor */
  194 static struct ng_type typestruct = {
  195         .version =      NG_ABI_VERSION,
  196         .name =         NG_BPF_NODE_TYPE,
  197         .constructor =  ng_bpf_constructor,
  198         .rcvmsg =       ng_bpf_rcvmsg,
  199         .shutdown =     ng_bpf_shutdown,
  200         .newhook =      ng_bpf_newhook,
  201         .rcvdata =      ng_bpf_rcvdata,
  202         .disconnect =   ng_bpf_disconnect,
  203         .cmdlist =      ng_bpf_cmdlist,
  204 };
  205 NETGRAPH_INIT(bpf, &typestruct);
  206 
  207 /* Default BPF program for a hook that matches nothing */
  208 static const struct ng_bpf_hookprog ng_bpf_default_prog = {
  209         { '\0' },               /* to be filled in at hook creation time */
  210         { '\0' },
  211         { '\0' },
  212         1,
  213         { BPF_STMT(BPF_RET+BPF_K, 0) }
  214 };
  215 
  216 /*
  217  * Node constructor
  218  *
  219  * We don't keep any per-node private data
  220  * We go via the hooks.
  221  */
  222 static int
  223 ng_bpf_constructor(node_p node)
  224 {
  225         NG_NODE_SET_PRIVATE(node, NULL);
  226         return (0);
  227 }
  228 
  229 /*
  230  * Callback functions to be used by NG_NODE_FOREACH_HOOK() macro.
  231  */
  232 static int
  233 ng_bpf_addrefs(hook_p hook, void* arg)
  234 {
  235         hinfo_p hip = NG_HOOK_PRIVATE(hook);
  236         hook_p h = (hook_p)arg;
  237 
  238         if (strcmp(hip->prog->ifMatch, NG_HOOK_NAME(h)) == 0)
  239             hip->match = h;
  240         if (strcmp(hip->prog->ifNotMatch, NG_HOOK_NAME(h)) == 0)
  241             hip->nomatch = h;
  242         return (1);
  243 }
  244 
  245 static int
  246 ng_bpf_remrefs(hook_p hook, void* arg)
  247 {
  248         hinfo_p hip = NG_HOOK_PRIVATE(hook);
  249         hook_p h = (hook_p)arg;
  250 
  251         if (hip->match == h)
  252             hip->match = NULL;
  253         if (hip->nomatch == h)
  254             hip->nomatch = NULL;
  255         return (1);
  256 }
  257 
  258 /*
  259  * Add a hook
  260  */
  261 static int
  262 ng_bpf_newhook(node_p node, hook_p hook, const char *name)
  263 {
  264         hinfo_p hip;
  265         hook_p tmp;
  266         int error;
  267 
  268         /* Create hook private structure */
  269         MALLOC(hip, hinfo_p, sizeof(*hip), M_NETGRAPH_BPF, M_NOWAIT | M_ZERO);
  270         if (hip == NULL)
  271                 return (ENOMEM);
  272         hip->hook = hook;
  273         NG_HOOK_SET_PRIVATE(hook, hip);
  274 
  275         /* Add our reference into other hooks data. */
  276         NG_NODE_FOREACH_HOOK(node, ng_bpf_addrefs, hook, tmp);
  277 
  278         /* Attach the default BPF program */
  279         if ((error = ng_bpf_setprog(hook, &ng_bpf_default_prog)) != 0) {
  280                 FREE(hip, M_NETGRAPH_BPF);
  281                 NG_HOOK_SET_PRIVATE(hook, NULL);
  282                 return (error);
  283         }
  284 
  285         /* Set hook name */
  286         strlcpy(hip->prog->thisHook, name, sizeof(hip->prog->thisHook));
  287         return (0);
  288 }
  289 
  290 /*
  291  * Receive a control message
  292  */
  293 static int
  294 ng_bpf_rcvmsg(node_p node, item_p item, hook_p lasthook)
  295 {
  296         struct ng_mesg *msg;
  297         struct ng_mesg *resp = NULL;
  298         int error = 0;
  299 
  300         NGI_GET_MSG(item, msg);
  301         switch (msg->header.typecookie) {
  302         case NGM_BPF_COOKIE:
  303                 switch (msg->header.cmd) {
  304                 case NGM_BPF_SET_PROGRAM:
  305                     {
  306                         struct ng_bpf_hookprog *const
  307                             hp = (struct ng_bpf_hookprog *)msg->data;
  308                         hook_p hook;
  309 
  310                         /* Sanity check */
  311                         if (msg->header.arglen < sizeof(*hp)
  312                             || msg->header.arglen
  313                               != NG_BPF_HOOKPROG_SIZE(hp->bpf_prog_len))
  314                                 ERROUT(EINVAL);
  315 
  316                         /* Find hook */
  317                         if ((hook = ng_findhook(node, hp->thisHook)) == NULL)
  318                                 ERROUT(ENOENT);
  319 
  320                         /* Set new program */
  321                         if ((error = ng_bpf_setprog(hook, hp)) != 0)
  322                                 ERROUT(error);
  323                         break;
  324                     }
  325 
  326                 case NGM_BPF_GET_PROGRAM:
  327                     {
  328                         struct ng_bpf_hookprog *hp;
  329                         hook_p hook;
  330 
  331                         /* Sanity check */
  332                         if (msg->header.arglen == 0)
  333                                 ERROUT(EINVAL);
  334                         msg->data[msg->header.arglen - 1] = '\0';
  335 
  336                         /* Find hook */
  337                         if ((hook = ng_findhook(node, msg->data)) == NULL)
  338                                 ERROUT(ENOENT);
  339 
  340                         /* Build response */
  341                         hp = ((hinfo_p)NG_HOOK_PRIVATE(hook))->prog;
  342                         NG_MKRESPONSE(resp, msg,
  343                             NG_BPF_HOOKPROG_SIZE(hp->bpf_prog_len), M_NOWAIT);
  344                         if (resp == NULL)
  345                                 ERROUT(ENOMEM);
  346                         bcopy(hp, resp->data,
  347                            NG_BPF_HOOKPROG_SIZE(hp->bpf_prog_len));
  348                         break;
  349                     }
  350 
  351                 case NGM_BPF_GET_STATS:
  352                 case NGM_BPF_CLR_STATS:
  353                 case NGM_BPF_GETCLR_STATS:
  354                     {
  355                         struct ng_bpf_hookstat *stats;
  356                         hook_p hook;
  357 
  358                         /* Sanity check */
  359                         if (msg->header.arglen == 0)
  360                                 ERROUT(EINVAL);
  361                         msg->data[msg->header.arglen - 1] = '\0';
  362 
  363                         /* Find hook */
  364                         if ((hook = ng_findhook(node, msg->data)) == NULL)
  365                                 ERROUT(ENOENT);
  366                         stats = &((hinfo_p)NG_HOOK_PRIVATE(hook))->stats;
  367 
  368                         /* Build response (if desired) */
  369                         if (msg->header.cmd != NGM_BPF_CLR_STATS) {
  370                                 NG_MKRESPONSE(resp,
  371                                     msg, sizeof(*stats), M_NOWAIT);
  372                                 if (resp == NULL)
  373                                         ERROUT(ENOMEM);
  374                                 bcopy(stats, resp->data, sizeof(*stats));
  375                         }
  376 
  377                         /* Clear stats (if desired) */
  378                         if (msg->header.cmd != NGM_BPF_GET_STATS)
  379                                 bzero(stats, sizeof(*stats));
  380                         break;
  381                     }
  382 
  383                 default:
  384                         error = EINVAL;
  385                         break;
  386                 }
  387                 break;
  388         default:
  389                 error = EINVAL;
  390                 break;
  391         }
  392 done:
  393         NG_RESPOND_MSG(error, node, item, resp);
  394         NG_FREE_MSG(msg);
  395         return (error);
  396 }
  397 
  398 /*
  399  * Receive data on a hook
  400  *
  401  * Apply the filter, and then drop or forward packet as appropriate.
  402  */
  403 static int
  404 ng_bpf_rcvdata(hook_p hook, item_p item)
  405 {
  406         const hinfo_p hip = NG_HOOK_PRIVATE(hook);
  407         int totlen;
  408         int error = 0;
  409         u_char *data = NULL;
  410         hinfo_p dhip;
  411         hook_p dest;
  412         u_int len;
  413         struct mbuf *m;
  414 
  415         m = NGI_M(item);        /* 'item' still owns it.. we are peeking */ 
  416         totlen = m->m_pkthdr.len;
  417         /* Update stats on incoming hook. XXX Can we do 64 bits atomically? */
  418         /* atomic_add_int64(&hip->stats.recvFrames, 1); */
  419         /* atomic_add_int64(&hip->stats.recvOctets, totlen); */
  420         hip->stats.recvFrames++; 
  421         hip->stats.recvOctets += totlen;
  422 
  423         /* Don't call bpf_filter() with totlen == 0! */
  424         if (totlen == 0) {
  425                 len = 0;
  426                 goto ready;
  427         }
  428 
  429         /* Try to put packet in contiguous memory for bpf */
  430         if (m->m_next == NULL || totlen < MHLEN) {
  431                 if (m->m_next != NULL) {
  432                         NGI_M(item) = m = m_pullup(m, totlen);
  433                         if (m == NULL) {
  434                                 NG_FREE_ITEM(item);
  435                                 return (ENOBUFS);
  436                         }
  437                 }
  438                 data = mtod(m, u_char *);
  439         }
  440 
  441         /* Run packet through filter */
  442         if (data)
  443                 len = bpf_filter(hip->prog->bpf_prog, data, totlen, totlen);
  444         else
  445                 len = bpf_filter(hip->prog->bpf_prog, (u_char *)m, totlen, 0);
  446 ready:
  447         /* See if we got a match and find destination hook */
  448         if (len > 0) {
  449 
  450                 /* Update stats */
  451                 /* XXX atomically? */
  452                 hip->stats.recvMatchFrames++;
  453                 hip->stats.recvMatchOctets += totlen;
  454 
  455                 /* Truncate packet length if required by the filter */
  456                 /* Assume this never changes m */
  457                 if (len < totlen) {
  458                         m_adj(m, -(totlen - len));
  459                         totlen = len;
  460                 }
  461                 dest = hip->match;
  462         } else
  463                 dest = hip->nomatch;
  464         if (dest == NULL) {
  465                 NG_FREE_ITEM(item);
  466                 return (0);
  467         }
  468 
  469         /* Deliver frame out destination hook */
  470         dhip = NG_HOOK_PRIVATE(dest);
  471         dhip->stats.xmitOctets += totlen;
  472         dhip->stats.xmitFrames++;
  473         NG_FWD_ITEM_HOOK(error, item, dest);
  474         return (error);
  475 }
  476 
  477 /*
  478  * Shutdown processing
  479  */
  480 static int
  481 ng_bpf_shutdown(node_p node)
  482 {
  483         NG_NODE_UNREF(node);
  484         return (0);
  485 }
  486 
  487 /*
  488  * Hook disconnection
  489  */
  490 static int
  491 ng_bpf_disconnect(hook_p hook)
  492 {
  493         const node_p node = NG_HOOK_NODE(hook);
  494         const hinfo_p hip = NG_HOOK_PRIVATE(hook);
  495         hook_p tmp;
  496 
  497         KASSERT(hip != NULL, ("%s: null info", __func__));
  498 
  499         /* Remove our reference from other hooks data. */
  500         NG_NODE_FOREACH_HOOK(node, ng_bpf_remrefs, hook, tmp);
  501 
  502         FREE(hip->prog, M_NETGRAPH_BPF);
  503         FREE(hip, M_NETGRAPH_BPF);
  504         if ((NG_NODE_NUMHOOKS(node) == 0) &&
  505             (NG_NODE_IS_VALID(node))) {
  506                 ng_rmnode_self(node);
  507         }
  508         return (0);
  509 }
  510 
  511 /************************************************************************
  512                         HELPER STUFF
  513  ************************************************************************/
  514 
  515 /*
  516  * Set the BPF program associated with a hook
  517  */
  518 static int
  519 ng_bpf_setprog(hook_p hook, const struct ng_bpf_hookprog *hp0)
  520 {
  521         const hinfo_p hip = NG_HOOK_PRIVATE(hook);
  522         struct ng_bpf_hookprog *hp;
  523         int size;
  524 
  525         /* Check program for validity */
  526         if (!bpf_validate(hp0->bpf_prog, hp0->bpf_prog_len))
  527                 return (EINVAL);
  528 
  529         /* Make a copy of the program */
  530         size = NG_BPF_HOOKPROG_SIZE(hp0->bpf_prog_len);
  531         MALLOC(hp, struct ng_bpf_hookprog *, size, M_NETGRAPH_BPF, M_NOWAIT);
  532         if (hp == NULL)
  533                 return (ENOMEM);
  534         bcopy(hp0, hp, size);
  535 
  536         /* Free previous program, if any, and assign new one */
  537         if (hip->prog != NULL)
  538                 FREE(hip->prog, M_NETGRAPH_BPF);
  539         hip->prog = hp;
  540 
  541         /* Prepare direct references on target hooks. */
  542         hip->match = ng_findhook(NG_HOOK_NODE(hook), hip->prog->ifMatch);
  543         hip->nomatch = ng_findhook(NG_HOOK_NODE(hook), hip->prog->ifNotMatch);
  544         return (0);
  545 }

Cache object: ad7beea7fef546a10d305ce5d10b6ece


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.