1 --- a/net/netfilter/Kconfig
2 +++ b/net/netfilter/Kconfig
3 @@ -1016,6 +1016,27 @@ config NETFILTER_XT_MATCH_STATE
5 To compile it as a module, choose M here. If unsure, say N.
7 +config NETFILTER_XT_MATCH_LAYER7
8 + tristate '"layer7" match support'
9 + depends on NETFILTER_XTABLES
10 + depends on EXPERIMENTAL && (IP_NF_CONNTRACK || NF_CONNTRACK)
11 + depends on NETFILTER_ADVANCED
13 + Say Y if you want to be able to classify connections (and their
14 + packets) based on regular expression matching of their application
15 + layer data. This is one way to classify applications such as
16 + peer-to-peer filesharing systems that do not always use the same
19 + To compile it as a module, choose M here. If unsure, say N.
21 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
22 + bool 'Layer 7 debugging output'
23 + depends on NETFILTER_XT_MATCH_LAYER7
25 + Say Y to get lots of debugging output.
28 config NETFILTER_XT_MATCH_STATISTIC
29 tristate '"statistic" match support'
30 depends on NETFILTER_ADVANCED
31 --- a/net/netfilter/Makefile
32 +++ b/net/netfilter/Makefile
33 @@ -102,6 +102,7 @@ obj-$(CONFIG_NETFILTER_XT_MATCH_RECENT)
34 obj-$(CONFIG_NETFILTER_XT_MATCH_SCTP) += xt_sctp.o
35 obj-$(CONFIG_NETFILTER_XT_MATCH_SOCKET) += xt_socket.o
36 obj-$(CONFIG_NETFILTER_XT_MATCH_STATE) += xt_state.o
37 +obj-$(CONFIG_NETFILTER_XT_MATCH_LAYER7) += xt_layer7.o
38 obj-$(CONFIG_NETFILTER_XT_MATCH_STATISTIC) += xt_statistic.o
39 obj-$(CONFIG_NETFILTER_XT_MATCH_STRING) += xt_string.o
40 obj-$(CONFIG_NETFILTER_XT_MATCH_TCPMSS) += xt_tcpmss.o
42 +++ b/net/netfilter/xt_layer7.c
45 + Kernel module to match application layer (OSI layer 7) data in connections.
47 + http://l7-filter.sf.net
49 + (C) 2003-2009 Matthew Strait and Ethan Sommer.
51 + This program is free software; you can redistribute it and/or
52 + modify it under the terms of the GNU General Public License
53 + as published by the Free Software Foundation; either version
54 + 2 of the License, or (at your option) any later version.
55 + http://www.gnu.org/licenses/gpl.txt
57 + Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>,
58 + xt_helper.c (C) 2002 Harald Welte and cls_layer7.c (C) 2003 Matthew Strait,
59 + Ethan Sommer, Justin Levandoski.
62 +#include <linux/spinlock.h>
63 +#include <linux/version.h>
66 +#include <linux/module.h>
67 +#include <linux/skbuff.h>
68 +#include <linux/netfilter.h>
69 +#include <net/netfilter/nf_conntrack.h>
70 +#include <net/netfilter/nf_conntrack_core.h>
71 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 27)
72 +#include <net/netfilter/nf_conntrack_extend.h>
73 +#include <net/netfilter/nf_conntrack_acct.h>
75 +#include <linux/netfilter/x_tables.h>
76 +#include <linux/netfilter/xt_layer7.h>
77 +#include <linux/ctype.h>
78 +#include <linux/proc_fs.h>
80 +#include "regexp/regexp.c"
82 +MODULE_LICENSE("GPL");
83 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
84 +MODULE_DESCRIPTION("iptables application layer match module");
85 +MODULE_ALIAS("ipt_layer7");
86 +MODULE_VERSION("2.21");
88 +static int maxdatalen = 2048; // this is the default
89 +module_param(maxdatalen, int, 0444);
90 +MODULE_PARM_DESC(maxdatalen, "maximum bytes of data looked at by l7-filter");
91 +#ifdef CONFIG_NETFILTER_XT_MATCH_LAYER7_DEBUG
92 + #define DPRINTK(format,args...) printk(format,##args)
94 + #define DPRINTK(format,args...)
97 +/* Number of packets whose data we look at.
98 +This can be modified through /proc/net/layer7_numpackets */
99 +static int num_packets = 10;
101 +static struct pattern_cache {
102 + char * regex_string;
104 + struct pattern_cache * next;
105 +} * first_pattern_cache = NULL;
107 +DEFINE_SPINLOCK(l7_lock);
109 +static int total_acct_packets(struct nf_conn *ct)
111 +#if LINUX_VERSION_CODE <= KERNEL_VERSION(2, 6, 26)
112 + BUG_ON(ct == NULL);
113 + return (ct->counters[IP_CT_DIR_ORIGINAL].packets + ct->counters[IP_CT_DIR_REPLY].packets);
115 + struct nf_conn_counter *acct;
117 + BUG_ON(ct == NULL);
118 + acct = nf_conn_acct_find(ct);
121 + return (acct[IP_CT_DIR_ORIGINAL].packets + acct[IP_CT_DIR_REPLY].packets);
125 +#ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
126 +/* Converts an unfriendly string into a friendly one by
127 +replacing unprintables with periods and all whitespace with " ". */
128 +static char * friendly_print(unsigned char * s)
130 + char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
134 + if (net_ratelimit())
135 + printk(KERN_ERR "layer7: out of memory in "
136 + "friendly_print, bailing.\n");
140 + for(i = 0; i < strlen(s); i++){
141 + if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
142 + else if(isspace(s[i])) f[i] = ' ';
149 +static char dec2hex(int i)
156 + return (i - 10 + 'a');
159 + if (net_ratelimit())
160 + printk("layer7: Problem in dec2hex\n");
165 +static char * hex_print(unsigned char * s)
167 + char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
171 + if (net_ratelimit())
172 + printk(KERN_ERR "layer7: out of memory in hex_print, "
177 + for(i = 0; i < strlen(s); i++) {
178 + g[i*3 ] = dec2hex(s[i]/16);
179 + g[i*3 + 1] = dec2hex(s[i]%16);
188 +/* Use instead of regcomp. As we expect to be seeing the same regexps over and
189 +over again, it make sense to cache the results. */
190 +static regexp * compile_and_cache(const char * regex_string,
191 + const char * protocol)
193 + struct pattern_cache * node = first_pattern_cache;
194 + struct pattern_cache * last_pattern_cache = first_pattern_cache;
195 + struct pattern_cache * tmp;
198 + while (node != NULL) {
199 + if (!strcmp(node->regex_string, regex_string))
200 + return node->pattern;
202 + last_pattern_cache = node;/* points at the last non-NULL node */
206 + /* If we reach the end of the list, then we have not yet cached
207 + the pattern for this regex. Let's do that now.
208 + Be paranoid about running out of memory to avoid list corruption. */
209 + tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
212 + if (net_ratelimit())
213 + printk(KERN_ERR "layer7: out of memory in "
214 + "compile_and_cache, bailing.\n");
218 + tmp->regex_string = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
219 + tmp->pattern = kmalloc(sizeof(struct regexp), GFP_ATOMIC);
222 + if(!tmp->regex_string || !tmp->pattern) {
223 + if (net_ratelimit())
224 + printk(KERN_ERR "layer7: out of memory in "
225 + "compile_and_cache, bailing.\n");
226 + kfree(tmp->regex_string);
227 + kfree(tmp->pattern);
232 + /* Ok. The new node is all ready now. */
235 + if(first_pattern_cache == NULL) /* list is empty */
236 + first_pattern_cache = node; /* make node the beginning */
238 + last_pattern_cache->next = node; /* attach node to the end */
240 + /* copy the string and compile the regex */
241 + len = strlen(regex_string);
242 + DPRINTK("About to compile this: \"%s\"\n", regex_string);
243 + node->pattern = regcomp((char *)regex_string, &len);
244 + if ( !node->pattern ) {
245 + if (net_ratelimit())
246 + printk(KERN_ERR "layer7: Error compiling regexp "
248 + regex_string, protocol);
249 + /* pattern is now cached as NULL, so we won't try again. */
252 + strcpy(node->regex_string, regex_string);
253 + return node->pattern;
256 +static int can_handle(const struct sk_buff *skb)
258 + if(!ip_hdr(skb)) /* not IP */
260 + if(ip_hdr(skb)->protocol != IPPROTO_TCP &&
261 + ip_hdr(skb)->protocol != IPPROTO_UDP &&
262 + ip_hdr(skb)->protocol != IPPROTO_ICMP)
267 +/* Returns offset the into the skb->data that the application data starts */
268 +static int app_data_offset(const struct sk_buff *skb)
270 + /* In case we are ported somewhere (ebtables?) where ip_hdr(skb)
271 + isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
272 + int ip_hl = 4*ip_hdr(skb)->ihl;
274 + if( ip_hdr(skb)->protocol == IPPROTO_TCP ) {
275 + /* 12 == offset into TCP header for the header length field.
276 + Can't get this with skb->h.th->doff because the tcphdr
277 + struct doesn't get set when routing (this is confirmed to be
278 + true in Netfilter as well as QoS.) */
279 + int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
281 + return ip_hl + tcp_hl;
282 + } else if( ip_hdr(skb)->protocol == IPPROTO_UDP ) {
283 + return ip_hl + 8; /* UDP header is always 8 bytes */
284 + } else if( ip_hdr(skb)->protocol == IPPROTO_ICMP ) {
285 + return ip_hl + 8; /* ICMP header is 8 bytes */
287 + if (net_ratelimit())
288 + printk(KERN_ERR "layer7: tried to handle unknown "
290 + return ip_hl + 8; /* something reasonable */
294 +/* handles whether there's a match when we aren't appending data anymore */
295 +static int match_no_append(struct nf_conn * conntrack,
296 + struct nf_conn * master_conntrack,
297 + enum ip_conntrack_info ctinfo,
298 + enum ip_conntrack_info master_ctinfo,
299 + const struct xt_layer7_info * info)
301 + /* If we're in here, throw the app data away */
302 + if(master_conntrack->layer7.app_data != NULL) {
304 + #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
305 + if(!master_conntrack->layer7.app_proto) {
307 + friendly_print(master_conntrack->layer7.app_data);
309 + hex_print(master_conntrack->layer7.app_data);
310 + DPRINTK("\nl7-filter gave up after %d bytes "
311 + "(%d packets):\n%s\n",
312 + strlen(f), total_acct_packets(master_conntrack), f);
314 + DPRINTK("In hex: %s\n", g);
319 + kfree(master_conntrack->layer7.app_data);
320 + master_conntrack->layer7.app_data = NULL; /* don't free again */
323 + if(master_conntrack->layer7.app_proto){
324 + /* Here child connections set their .app_proto (for /proc) */
325 + if(!conntrack->layer7.app_proto) {
326 + conntrack->layer7.app_proto =
327 + kmalloc(strlen(master_conntrack->layer7.app_proto)+1,
329 + if(!conntrack->layer7.app_proto){
330 + if (net_ratelimit())
331 + printk(KERN_ERR "layer7: out of memory "
332 + "in match_no_append, "
336 + strcpy(conntrack->layer7.app_proto,
337 + master_conntrack->layer7.app_proto);
340 + return (!strcmp(master_conntrack->layer7.app_proto,
344 + /* If not classified, set to "unknown" to distinguish from
345 + connections that are still being tested. */
346 + master_conntrack->layer7.app_proto =
347 + kmalloc(strlen("unknown")+1, GFP_ATOMIC);
348 + if(!master_conntrack->layer7.app_proto){
349 + if (net_ratelimit())
350 + printk(KERN_ERR "layer7: out of memory in "
351 + "match_no_append, bailing.\n");
354 + strcpy(master_conntrack->layer7.app_proto, "unknown");
359 +/* add the new app data to the conntrack. Return number of bytes added. */
360 +static int add_data(struct nf_conn * master_conntrack,
361 + char * app_data, int appdatalen)
364 + int oldlength = master_conntrack->layer7.app_data_len;
366 + /* This is a fix for a race condition by Deti Fliegl. However, I'm not
367 + clear on whether the race condition exists or whether this really
368 + fixes it. I might just be being dense... Anyway, if it's not really
369 + a fix, all it does is waste a very small amount of time. */
370 + if(!master_conntrack->layer7.app_data) return 0;
372 + /* Strip nulls. Make everything lower case (our regex lib doesn't
373 + do case insensitivity). Add it to the end of the current data. */
374 + for(i = 0; i < maxdatalen-oldlength-1 &&
375 + i < appdatalen; i++) {
376 + if(app_data[i] != '\0') {
377 + /* the kernel version of tolower mungs 'upper ascii' */
378 + master_conntrack->layer7.app_data[length+oldlength] =
379 + isascii(app_data[i])?
380 + tolower(app_data[i]) : app_data[i];
385 + master_conntrack->layer7.app_data[length+oldlength] = '\0';
386 + master_conntrack->layer7.app_data_len = length + oldlength;
391 +/* taken from drivers/video/modedb.c */
392 +static int my_atoi(const char *s)
399 + val = 10*val+(*s-'0');
407 +/* write out num_packets to userland. */
408 +static int layer7_read_proc(char* page, char ** start, off_t off, int count,
409 + int* eof, void * data)
411 + if(num_packets > 99 && net_ratelimit())
412 + printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
414 + page[0] = num_packets/10 + '0';
415 + page[1] = num_packets%10 + '0';
424 +/* Read in num_packets from userland */
425 +static int layer7_write_proc(struct file* file, const char* buffer,
426 + unsigned long count, void *data)
428 + char * foo = kmalloc(count, GFP_ATOMIC);
431 + if (net_ratelimit())
432 + printk(KERN_ERR "layer7: out of memory, bailing. "
433 + "num_packets unchanged.\n");
437 + if(copy_from_user(foo, buffer, count)) {
442 + num_packets = my_atoi(foo);
445 + /* This has an arbitrary limit to make the math easier. I'm lazy.
446 + But anyway, 99 is a LOT! If you want more, you're doing it wrong! */
447 + if(num_packets > 99) {
448 + printk(KERN_WARNING "layer7: num_packets can't be > 99.\n");
450 + } else if(num_packets < 1) {
451 + printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
459 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
460 +match(const struct sk_buff *skbin, const struct xt_match_param *par)
462 +match(const struct sk_buff *skbin,
463 + const struct net_device *in,
464 + const struct net_device *out,
465 + const struct xt_match *match,
466 + const void *matchinfo,
468 + unsigned int protoff,
472 + /* sidestep const without getting a compiler warning... */
473 + struct sk_buff * skb = (struct sk_buff *)skbin;
475 + const struct xt_layer7_info * info =
476 + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
482 + enum ip_conntrack_info master_ctinfo, ctinfo;
483 + struct nf_conn *master_conntrack, *conntrack;
484 + unsigned char * app_data;
485 + unsigned int pattern_result, appdatalen;
486 + regexp * comppattern;
488 + /* Be paranoid/incompetent - lock the entire match function. */
489 + spin_lock_bh(&l7_lock);
491 + if(!can_handle(skb)){
492 + DPRINTK("layer7: This is some protocol I can't handle.\n");
493 + spin_unlock_bh(&l7_lock);
494 + return info->invert;
497 + /* Treat parent & all its children together as one connection, except
498 + for the purpose of setting conntrack->layer7.app_proto in the actual
499 + connection. This makes /proc/net/ip_conntrack more satisfying. */
500 + if(!(conntrack = nf_ct_get(skb, &ctinfo)) ||
501 + !(master_conntrack=nf_ct_get(skb,&master_ctinfo))){
502 + DPRINTK("layer7: couldn't get conntrack.\n");
503 + spin_unlock_bh(&l7_lock);
504 + return info->invert;
507 + /* Try to get a master conntrack (and its master etc) for FTP, etc. */
508 + while (master_ct(master_conntrack) != NULL)
509 + master_conntrack = master_ct(master_conntrack);
511 + /* if we've classified it or seen too many packets */
512 + if(total_acct_packets(master_conntrack) > num_packets ||
513 + master_conntrack->layer7.app_proto) {
515 + pattern_result = match_no_append(conntrack, master_conntrack,
516 + ctinfo, master_ctinfo, info);
518 + /* skb->cb[0] == seen. Don't do things twice if there are
519 + multiple l7 rules. I'm not sure that using cb for this purpose
520 + is correct, even though it says "put your private variables
521 + there". But it doesn't look like it is being used for anything
522 + else in the skbs that make it here. */
523 + skb->cb[0] = 1; /* marking it seen here's probably irrelevant */
525 + spin_unlock_bh(&l7_lock);
526 + return (pattern_result ^ info->invert);
529 + if(skb_is_nonlinear(skb)){
530 + if(skb_linearize(skb) != 0){
531 + if (net_ratelimit())
532 + printk(KERN_ERR "layer7: failed to linearize "
533 + "packet, bailing.\n");
534 + spin_unlock_bh(&l7_lock);
535 + return info->invert;
539 + /* now that the skb is linearized, it's safe to set these. */
540 + app_data = skb->data + app_data_offset(skb);
541 + appdatalen = skb_tail_pointer(skb) - app_data;
543 + /* the return value gets checked later, when we're ready to use it */
544 + comppattern = compile_and_cache(info->pattern, info->protocol);
546 + /* On the first packet of a connection, allocate space for app data */
547 + if(total_acct_packets(master_conntrack) == 1 && !skb->cb[0] &&
548 + !master_conntrack->layer7.app_data){
549 + master_conntrack->layer7.app_data =
550 + kmalloc(maxdatalen, GFP_ATOMIC);
551 + if(!master_conntrack->layer7.app_data){
552 + if (net_ratelimit())
553 + printk(KERN_ERR "layer7: out of memory in "
554 + "match, bailing.\n");
555 + spin_unlock_bh(&l7_lock);
556 + return info->invert;
559 + master_conntrack->layer7.app_data[0] = '\0';
562 + /* Can be here, but unallocated, if numpackets is increased near
563 + the beginning of a connection */
564 + if(master_conntrack->layer7.app_data == NULL){
565 + spin_unlock_bh(&l7_lock);
566 + return info->invert; /* unmatched */
571 + newbytes = add_data(master_conntrack, app_data, appdatalen);
573 + if(newbytes == 0) { /* didn't add any data */
575 + /* Didn't match before, not going to match now */
576 + spin_unlock_bh(&l7_lock);
577 + return info->invert;
581 + /* If looking for "unknown", then never match. "Unknown" means that
582 + we've given up; we're still trying with these packets. */
583 + if(!strcmp(info->protocol, "unknown")) {
584 + pattern_result = 0;
585 + /* If looking for "unset", then always match. "Unset" means that we
586 + haven't yet classified the connection. */
587 + } else if(!strcmp(info->protocol, "unset")) {
588 + pattern_result = 2;
589 + DPRINTK("layer7: matched unset: not yet classified "
590 + "(%d/%d packets)\n",
591 + total_acct_packets(master_conntrack), num_packets);
592 + /* If the regexp failed to compile, don't bother running it */
593 + } else if(comppattern &&
594 + regexec(comppattern, master_conntrack->layer7.app_data)){
595 + DPRINTK("layer7: matched %s\n", info->protocol);
596 + pattern_result = 1;
597 + } else pattern_result = 0;
599 + if(pattern_result == 1) {
600 + master_conntrack->layer7.app_proto =
601 + kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
602 + if(!master_conntrack->layer7.app_proto){
603 + if (net_ratelimit())
604 + printk(KERN_ERR "layer7: out of memory in "
605 + "match, bailing.\n");
606 + spin_unlock_bh(&l7_lock);
607 + return (pattern_result ^ info->invert);
609 + strcpy(master_conntrack->layer7.app_proto, info->protocol);
610 + } else if(pattern_result > 1) { /* cleanup from "unset" */
611 + pattern_result = 1;
614 + /* mark the packet seen */
617 + spin_unlock_bh(&l7_lock);
618 + return (pattern_result ^ info->invert);
621 +// load nf_conntrack_ipv4
622 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
623 +static bool check(const struct xt_mtchk_param *par)
625 + if (nf_ct_l3proto_try_module_get(par->match->family) < 0) {
626 + printk(KERN_WARNING "can't load conntrack support for "
627 + "proto=%d\n", par->match->family);
629 +static bool check(const char *tablename, const void *inf,
630 + const struct xt_match *match, void *matchinfo,
631 + unsigned int hook_mask)
633 + if (nf_ct_l3proto_try_module_get(match->family) < 0) {
634 + printk(KERN_WARNING "can't load conntrack support for "
635 + "proto=%d\n", match->family);
643 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
644 + static void destroy(const struct xt_mtdtor_param *par)
646 + nf_ct_l3proto_module_put(par->match->family);
649 + static void destroy(const struct xt_match *match, void *matchinfo)
651 + nf_ct_l3proto_module_put(match->family);
655 +static struct xt_match xt_layer7_match[] __read_mostly = {
659 + .checkentry = check,
661 + .destroy = destroy,
662 + .matchsize = sizeof(struct xt_layer7_info),
667 +static void layer7_cleanup_proc(void)
669 + remove_proc_entry("layer7_numpackets", init_net.proc_net);
672 +/* register the proc file */
673 +static void layer7_init_proc(void)
675 + struct proc_dir_entry* entry;
676 + entry = create_proc_entry("layer7_numpackets", 0644, init_net.proc_net);
677 + entry->read_proc = layer7_read_proc;
678 + entry->write_proc = layer7_write_proc;
681 +static int __init xt_layer7_init(void)
685 + layer7_init_proc();
686 + if(maxdatalen < 1) {
687 + printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
691 + /* This is not a hard limit. It's just here to prevent people from
692 + bringing their slow machines to a grinding halt. */
693 + else if(maxdatalen > 65536) {
694 + printk(KERN_WARNING "layer7: maxdatalen can't be > 65536, "
696 + maxdatalen = 65536;
698 + return xt_register_matches(xt_layer7_match,
699 + ARRAY_SIZE(xt_layer7_match));
702 +static void __exit xt_layer7_fini(void)
704 + layer7_cleanup_proc();
705 + xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
708 +module_init(xt_layer7_init);
709 +module_exit(xt_layer7_fini);
711 +++ b/net/netfilter/regexp/regexp.c
714 + * regcomp and regexec -- regsub and regerror are elsewhere
715 + * @(#)regexp.c 1.3 of 18 April 87
717 + * Copyright (c) 1986 by University of Toronto.
718 + * Written by Henry Spencer. Not derived from licensed software.
720 + * Permission is granted to anyone to use this software for any
721 + * purpose on any computer system, and to redistribute it freely,
722 + * subject to the following restrictions:
724 + * 1. The author is not responsible for the consequences of use of
725 + * this software, no matter how awful, even if they arise
726 + * from defects in it.
728 + * 2. The origin of this software must not be misrepresented, either
729 + * by explicit claim or by omission.
731 + * 3. Altered versions must be plainly marked as such, and must not
732 + * be misrepresented as being the original software.
734 + * Beware that some of this code is subtly aware of the way operator
735 + * precedence is structured in regular expressions. Serious changes in
736 + * regular-expression syntax might require a total rethink.
738 + * This code was modified by Ethan Sommer to work within the kernel
739 + * (it now uses kmalloc etc..)
741 + * Modified slightly by Matthew Strait to use more modern C.
745 +#include "regmagic.h"
747 +/* added by ethan and matt. Lets it work in both kernel and user space.
748 +(So iptables can use it, for instance.) Yea, it goes both ways... */
750 + #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
752 + #define printk(format,args...) printf(format,##args)
755 +void regerror(char * s)
757 + printk("<3>Regexp: %s\n", s);
762 + * The "internal use only" fields in regexp.h are present to pass info from
763 + * compile to execute that permits the execute phase to run lots faster on
764 + * simple cases. They are:
766 + * regstart char that must begin a match; '\0' if none obvious
767 + * reganch is the match anchored (at beginning-of-line only)?
768 + * regmust string (pointer into program) that match must include, or NULL
769 + * regmlen length of regmust string
771 + * Regstart and reganch permit very fast decisions on suitable starting points
772 + * for a match, cutting down the work a lot. Regmust permits fast rejection
773 + * of lines that cannot possibly match. The regmust tests are costly enough
774 + * that regcomp() supplies a regmust only if the r.e. contains something
775 + * potentially expensive (at present, the only such thing detected is * or +
776 + * at the start of the r.e., which can involve a lot of backup). Regmlen is
777 + * supplied because the test in regexec() needs it and regcomp() is computing
782 + * Structure for regexp "program". This is essentially a linear encoding
783 + * of a nondeterministic finite-state machine (aka syntax charts or
784 + * "railroad normal form" in parsing technology). Each node is an opcode
785 + * plus a "next" pointer, possibly plus an operand. "Next" pointers of
786 + * all nodes except BRANCH implement concatenation; a "next" pointer with
787 + * a BRANCH on both ends of it is connecting two alternatives. (Here we
788 + * have one of the subtle syntax dependencies: an individual BRANCH (as
789 + * opposed to a collection of them) is never concatenated with anything
790 + * because of operator precedence.) The operand of some types of node is
791 + * a literal string; for others, it is a node leading into a sub-FSM. In
792 + * particular, the operand of a BRANCH node is the first node of the branch.
793 + * (NB this is *not* a tree structure: the tail of the branch connects
794 + * to the thing following the set of BRANCHes.) The opcodes are:
797 +/* definition number opnd? meaning */
798 +#define END 0 /* no End of program. */
799 +#define BOL 1 /* no Match "" at beginning of line. */
800 +#define EOL 2 /* no Match "" at end of line. */
801 +#define ANY 3 /* no Match any one character. */
802 +#define ANYOF 4 /* str Match any character in this string. */
803 +#define ANYBUT 5 /* str Match any character not in this string. */
804 +#define BRANCH 6 /* node Match this alternative, or the next... */
805 +#define BACK 7 /* no Match "", "next" ptr points backward. */
806 +#define EXACTLY 8 /* str Match this string. */
807 +#define NOTHING 9 /* no Match empty string. */
808 +#define STAR 10 /* node Match this (simple) thing 0 or more times. */
809 +#define PLUS 11 /* node Match this (simple) thing 1 or more times. */
810 +#define OPEN 20 /* no Mark this point in input as start of #n. */
811 + /* OPEN+1 is number 1, etc. */
812 +#define CLOSE 30 /* no Analogous to OPEN. */
817 + * BRANCH The set of branches constituting a single choice are hooked
818 + * together with their "next" pointers, since precedence prevents
819 + * anything being concatenated to any individual branch. The
820 + * "next" pointer of the last BRANCH in a choice points to the
821 + * thing following the whole choice. This is also where the
822 + * final "next" pointer of each individual branch points; each
823 + * branch starts with the operand node of a BRANCH node.
825 + * BACK Normal "next" pointers all implicitly point forward; BACK
826 + * exists to make loop structures possible.
828 + * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
829 + * BRANCH structures using BACK. Simple cases (one character
830 + * per match) are implemented with STAR and PLUS for speed
831 + * and to minimize recursive plunges.
833 + * OPEN,CLOSE ...are numbered at compile time.
837 + * A node is one char of opcode followed by two chars of "next" pointer.
838 + * "Next" pointers are stored as two 8-bit pieces, high order first. The
839 + * value is a positive offset from the opcode of the node containing it.
840 + * An operand, if any, simply follows the node. (Note that much of the
841 + * code generation knows about this implicit relationship.)
843 + * Using two bytes for the "next" pointer is vast overkill for most things,
844 + * but allows patterns to get big without disasters.
846 +#define OP(p) (*(p))
847 +#define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
848 +#define OPERAND(p) ((p) + 3)
851 + * See regmagic.h for one further detail of program structure.
856 + * Utility definitions.
859 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
861 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
864 +#define FAIL(m) { regerror(m); return(NULL); }
865 +#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
866 +#define META "^$.[()|?+*\\"
869 + * Flags to be passed up and down.
871 +#define HASWIDTH 01 /* Known never to match null string. */
872 +#define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
873 +#define SPSTART 04 /* Starts with * or +. */
874 +#define WORST 0 /* Worst case. */
877 + * Global work variables for regcomp().
879 +struct match_globals {
880 +char *reginput; /* String-input pointer. */
881 +char *regbol; /* Beginning of input, for ^ check. */
882 +char **regstartp; /* Pointer to startp array. */
883 +char **regendp; /* Ditto for endp. */
884 +char *regparse; /* Input-scan pointer. */
885 +int regnpar; /* () count. */
887 +char *regcode; /* Code-emit pointer; ®dummy = don't. */
888 +long regsize; /* Code size. */
892 + * Forward declarations for regcomp()'s friends.
895 +#define STATIC static
897 +STATIC char *reg(struct match_globals *g, int paren,int *flagp);
898 +STATIC char *regbranch(struct match_globals *g, int *flagp);
899 +STATIC char *regpiece(struct match_globals *g, int *flagp);
900 +STATIC char *regatom(struct match_globals *g, int *flagp);
901 +STATIC char *regnode(struct match_globals *g, char op);
902 +STATIC char *regnext(struct match_globals *g, char *p);
903 +STATIC void regc(struct match_globals *g, char b);
904 +STATIC void reginsert(struct match_globals *g, char op, char *opnd);
905 +STATIC void regtail(struct match_globals *g, char *p, char *val);
906 +STATIC void regoptail(struct match_globals *g, char *p, char *val);
909 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
916 + for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
917 + for (scan2 = (char *)s2; *scan2 != '\0';) /* ++ moved down. */
918 + if (*scan1 == *scan2++)
926 + - regcomp - compile a regular expression into internal code
928 + * We can't allocate space until we know how big the compiled form will be,
929 + * but we can't compile it (and thus know how big it is) until we've got a
930 + * place to put the code. So we cheat: we compile it twice, once with code
931 + * generation turned off and size counting turned on, and once "for real".
932 + * This also means that we don't allocate space until we are sure that the
933 + * thing really will compile successfully, and we never have to move the
934 + * code and thus invalidate pointers into it. (Note that it has to be in
935 + * one piece because free() must be able to free it all.)
937 + * Beware that the optimization-preparation code in here knows about some
938 + * of the structure of the compiled regexp.
941 +regcomp(char *exp,int *patternsize)
943 + register regexp *r;
944 + register char *scan;
945 + register char *longest;
948 + struct match_globals g;
950 + /* commented out by ethan
951 + extern char *malloc();
955 + FAIL("NULL argument");
957 + /* First pass: determine size, legality. */
961 + g.regcode = &g.regdummy;
963 + if (reg(&g, 0, &flags) == NULL)
966 + /* Small enough for pointer-storage convention? */
967 + if (g.regsize >= 32767L) /* Probably could be 65535L. */
968 + FAIL("regexp too big");
970 + /* Allocate space. */
971 + *patternsize=sizeof(regexp) + (unsigned)g.regsize;
972 + r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
974 + FAIL("out of space");
976 + /* Second pass: emit code. */
979 + g.regcode = r->program;
981 + if (reg(&g, 0, &flags) == NULL)
984 + /* Dig out information for optimizations. */
985 + r->regstart = '\0'; /* Worst-case defaults. */
989 + scan = r->program+1; /* First BRANCH. */
990 + if (OP(regnext(&g, scan)) == END) { /* Only one top-level choice. */
991 + scan = OPERAND(scan);
993 + /* Starting-point info. */
994 + if (OP(scan) == EXACTLY)
995 + r->regstart = *OPERAND(scan);
996 + else if (OP(scan) == BOL)
1000 + * If there's something expensive in the r.e., find the
1001 + * longest literal string that must appear and make it the
1002 + * regmust. Resolve ties in favor of later strings, since
1003 + * the regstart check works with the beginning of the r.e.
1004 + * and avoiding duplication strengthens checking. Not a
1005 + * strong reason, but sufficient in the absence of others.
1007 + if (flags&SPSTART) {
1010 + for (; scan != NULL; scan = regnext(&g, scan))
1011 + if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
1012 + longest = OPERAND(scan);
1013 + len = strlen(OPERAND(scan));
1015 + r->regmust = longest;
1024 + - reg - regular expression, i.e. main body or parenthesized thing
1026 + * Caller must absorb opening parenthesis.
1028 + * Combining parenthesis handling with the base level of regular expression
1029 + * is a trifle forced, but the need to tie the tails of the branches to what
1030 + * follows makes it hard to avoid.
1033 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
1035 + register char *ret;
1036 + register char *br;
1037 + register char *ender;
1038 + register int parno = 0; /* 0 makes gcc happy */
1041 + *flagp = HASWIDTH; /* Tentatively. */
1043 + /* Make an OPEN node, if parenthesized. */
1045 + if (g->regnpar >= NSUBEXP)
1046 + FAIL("too many ()");
1047 + parno = g->regnpar;
1049 + ret = regnode(g, OPEN+parno);
1053 + /* Pick up the branches, linking them together. */
1054 + br = regbranch(g, &flags);
1058 + regtail(g, ret, br); /* OPEN -> first. */
1061 + if (!(flags&HASWIDTH))
1062 + *flagp &= ~HASWIDTH;
1063 + *flagp |= flags&SPSTART;
1064 + while (*g->regparse == '|') {
1066 + br = regbranch(g, &flags);
1069 + regtail(g, ret, br); /* BRANCH -> BRANCH. */
1070 + if (!(flags&HASWIDTH))
1071 + *flagp &= ~HASWIDTH;
1072 + *flagp |= flags&SPSTART;
1075 + /* Make a closing node, and hook it on the end. */
1076 + ender = regnode(g, (paren) ? CLOSE+parno : END);
1077 + regtail(g, ret, ender);
1079 + /* Hook the tails of the branches to the closing node. */
1080 + for (br = ret; br != NULL; br = regnext(g, br))
1081 + regoptail(g, br, ender);
1083 + /* Check for proper termination. */
1084 + if (paren && *g->regparse++ != ')') {
1085 + FAIL("unmatched ()");
1086 + } else if (!paren && *g->regparse != '\0') {
1087 + if (*g->regparse == ')') {
1088 + FAIL("unmatched ()");
1090 + FAIL("junk on end"); /* "Can't happen". */
1098 + - regbranch - one alternative of an | operator
1100 + * Implements the concatenation operator.
1103 +regbranch(struct match_globals *g, int *flagp)
1105 + register char *ret;
1106 + register char *chain;
1107 + register char *latest;
1110 + *flagp = WORST; /* Tentatively. */
1112 + ret = regnode(g, BRANCH);
1114 + while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
1115 + latest = regpiece(g, &flags);
1116 + if (latest == NULL)
1118 + *flagp |= flags&HASWIDTH;
1119 + if (chain == NULL) /* First piece. */
1120 + *flagp |= flags&SPSTART;
1122 + regtail(g, chain, latest);
1125 + if (chain == NULL) /* Loop ran zero times. */
1126 + (void) regnode(g, NOTHING);
1132 + - regpiece - something followed by possible [*+?]
1134 + * Note that the branching code sequences used for ? and the general cases
1135 + * of * and + are somewhat optimized: they use the same NOTHING node as
1136 + * both the endmarker for their branch list and the body of the last branch.
1137 + * It might seem that this node could be dispensed with entirely, but the
1138 + * endmarker role is not redundant.
1141 +regpiece(struct match_globals *g, int *flagp)
1143 + register char *ret;
1145 + register char *next;
1148 + ret = regatom(g, &flags);
1152 + op = *g->regparse;
1153 + if (!ISMULT(op)) {
1158 + if (!(flags&HASWIDTH) && op != '?')
1159 + FAIL("*+ operand could be empty");
1160 + *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
1162 + if (op == '*' && (flags&SIMPLE))
1163 + reginsert(g, STAR, ret);
1164 + else if (op == '*') {
1165 + /* Emit x* as (x&|), where & means "self". */
1166 + reginsert(g, BRANCH, ret); /* Either x */
1167 + regoptail(g, ret, regnode(g, BACK)); /* and loop */
1168 + regoptail(g, ret, ret); /* back */
1169 + regtail(g, ret, regnode(g, BRANCH)); /* or */
1170 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
1171 + } else if (op == '+' && (flags&SIMPLE))
1172 + reginsert(g, PLUS, ret);
1173 + else if (op == '+') {
1174 + /* Emit x+ as x(&|), where & means "self". */
1175 + next = regnode(g, BRANCH); /* Either */
1176 + regtail(g, ret, next);
1177 + regtail(g, regnode(g, BACK), ret); /* loop back */
1178 + regtail(g, next, regnode(g, BRANCH)); /* or */
1179 + regtail(g, ret, regnode(g, NOTHING)); /* null. */
1180 + } else if (op == '?') {
1181 + /* Emit x? as (x|) */
1182 + reginsert(g, BRANCH, ret); /* Either x */
1183 + regtail(g, ret, regnode(g, BRANCH)); /* or */
1184 + next = regnode(g, NOTHING); /* null. */
1185 + regtail(g, ret, next);
1186 + regoptail(g, ret, next);
1189 + if (ISMULT(*g->regparse))
1190 + FAIL("nested *?+");
1196 + - regatom - the lowest level
1198 + * Optimization: gobbles an entire sequence of ordinary characters so that
1199 + * it can turn them into a single node, which is smaller to store and
1200 + * faster to run. Backslashed characters are exceptions, each becoming a
1201 + * separate node; the code is simpler that way and it's not worth fixing.
1204 +regatom(struct match_globals *g, int *flagp)
1206 + register char *ret;
1209 + *flagp = WORST; /* Tentatively. */
1211 + switch (*g->regparse++) {
1213 + ret = regnode(g, BOL);
1216 + ret = regnode(g, EOL);
1219 + ret = regnode(g, ANY);
1220 + *flagp |= HASWIDTH|SIMPLE;
1223 + register int class;
1224 + register int classend;
1226 + if (*g->regparse == '^') { /* Complement of range. */
1227 + ret = regnode(g, ANYBUT);
1230 + ret = regnode(g, ANYOF);
1231 + if (*g->regparse == ']' || *g->regparse == '-')
1232 + regc(g, *g->regparse++);
1233 + while (*g->regparse != '\0' && *g->regparse != ']') {
1234 + if (*g->regparse == '-') {
1236 + if (*g->regparse == ']' || *g->regparse == '\0')
1239 + class = UCHARAT(g->regparse-2)+1;
1240 + classend = UCHARAT(g->regparse);
1241 + if (class > classend+1)
1242 + FAIL("invalid [] range");
1243 + for (; class <= classend; class++)
1248 + regc(g, *g->regparse++);
1251 + if (*g->regparse != ']')
1252 + FAIL("unmatched []");
1254 + *flagp |= HASWIDTH|SIMPLE;
1258 + ret = reg(g, 1, &flags);
1261 + *flagp |= flags&(HASWIDTH|SPSTART);
1266 + FAIL("internal urp"); /* Supposed to be caught earlier. */
1271 + FAIL("?+* follows nothing");
1274 + if (*g->regparse == '\0')
1275 + FAIL("trailing \\");
1276 + ret = regnode(g, EXACTLY);
1277 + regc(g, *g->regparse++);
1279 + *flagp |= HASWIDTH|SIMPLE;
1283 + register char ender;
1286 + len = my_strcspn((const char *)g->regparse, (const char *)META);
1288 + FAIL("internal disaster");
1289 + ender = *(g->regparse+len);
1290 + if (len > 1 && ISMULT(ender))
1291 + len--; /* Back off clear of ?+* operand. */
1292 + *flagp |= HASWIDTH;
1295 + ret = regnode(g, EXACTLY);
1297 + regc(g, *g->regparse++);
1309 + - regnode - emit a node
1311 +static char * /* Location. */
1312 +regnode(struct match_globals *g, char op)
1314 + register char *ret;
1315 + register char *ptr;
1318 + if (ret == &g->regdummy) {
1325 + *ptr++ = '\0'; /* Null "next" pointer. */
1333 + - regc - emit (if appropriate) a byte of code
1336 +regc(struct match_globals *g, char b)
1338 + if (g->regcode != &g->regdummy)
1339 + *g->regcode++ = b;
1345 + - reginsert - insert an operator in front of already-emitted operand
1347 + * Means relocating the operand.
1350 +reginsert(struct match_globals *g, char op, char* opnd)
1352 + register char *src;
1353 + register char *dst;
1354 + register char *place;
1356 + if (g->regcode == &g->regdummy) {
1364 + while (src > opnd)
1367 + place = opnd; /* Op node, where operand used to be. */
1374 + - regtail - set the next-pointer at the end of a node chain
1377 +regtail(struct match_globals *g, char *p, char *val)
1379 + register char *scan;
1380 + register char *temp;
1381 + register int offset;
1383 + if (p == &g->regdummy)
1386 + /* Find last node. */
1389 + temp = regnext(g, scan);
1395 + if (OP(scan) == BACK)
1396 + offset = scan - val;
1398 + offset = val - scan;
1399 + *(scan+1) = (offset>>8)&0377;
1400 + *(scan+2) = offset&0377;
1404 + - regoptail - regtail on operand of first argument; nop if operandless
1407 +regoptail(struct match_globals *g, char *p, char *val)
1409 + /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1410 + if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
1412 + regtail(g, OPERAND(p), val);
1416 + * regexec and friends
1423 +STATIC int regtry(struct match_globals *g, regexp *prog, char *string);
1424 +STATIC int regmatch(struct match_globals *g, char *prog);
1425 +STATIC int regrepeat(struct match_globals *g, char *p);
1428 +int regnarrate = 0;
1430 +STATIC char *regprop(char *op);
1434 + - regexec - match a regexp against a string
1437 +regexec(regexp *prog, char *string)
1440 + struct match_globals g;
1442 + /* Be paranoid... */
1443 + if (prog == NULL || string == NULL) {
1444 + printk("<3>Regexp: NULL parameter\n");
1448 + /* Check validity of program. */
1449 + if (UCHARAT(prog->program) != MAGIC) {
1450 + printk("<3>Regexp: corrupted program\n");
1454 + /* If there is a "must appear" string, look for it. */
1455 + if (prog->regmust != NULL) {
1457 + while ((s = strchr(s, prog->regmust[0])) != NULL) {
1458 + if (strncmp(s, prog->regmust, prog->regmlen) == 0)
1459 + break; /* Found it. */
1462 + if (s == NULL) /* Not present. */
1466 + /* Mark beginning of line for ^ . */
1467 + g.regbol = string;
1469 + /* Simplest case: anchored match need be tried only once. */
1470 + if (prog->reganch)
1471 + return(regtry(&g, prog, string));
1473 + /* Messy cases: unanchored match. */
1475 + if (prog->regstart != '\0')
1476 + /* We know what char it must start with. */
1477 + while ((s = strchr(s, prog->regstart)) != NULL) {
1478 + if (regtry(&g, prog, s))
1483 + /* We don't -- general case. */
1485 + if (regtry(&g, prog, s))
1487 + } while (*s++ != '\0');
1494 + - regtry - try match at specific point
1496 +static int /* 0 failure, 1 success */
1497 +regtry(struct match_globals *g, regexp *prog, char *string)
1500 + register char **sp;
1501 + register char **ep;
1503 + g->reginput = string;
1504 + g->regstartp = prog->startp;
1505 + g->regendp = prog->endp;
1507 + sp = prog->startp;
1509 + for (i = NSUBEXP; i > 0; i--) {
1513 + if (regmatch(g, prog->program + 1)) {
1514 + prog->startp[0] = string;
1515 + prog->endp[0] = g->reginput;
1522 + - regmatch - main matching routine
1524 + * Conceptually the strategy is simple: check to see whether the current
1525 + * node matches, call self recursively to see whether the rest matches,
1526 + * and then act accordingly. In practice we make some effort to avoid
1527 + * recursion, in particular by going through "ordinary" nodes (that don't
1528 + * need to know whether the rest of the match failed) by a loop instead of
1531 +static int /* 0 failure, 1 success */
1532 +regmatch(struct match_globals *g, char *prog)
1534 + register char *scan = prog; /* Current node. */
1535 + char *next; /* Next node. */
1538 + if (scan != NULL && regnarrate)
1539 + fprintf(stderr, "%s(\n", regprop(scan));
1541 + while (scan != NULL) {
1544 + fprintf(stderr, "%s...\n", regprop(scan));
1546 + next = regnext(g, scan);
1548 + switch (OP(scan)) {
1550 + if (g->reginput != g->regbol)
1554 + if (*g->reginput != '\0')
1558 + if (*g->reginput == '\0')
1564 + register char *opnd;
1566 + opnd = OPERAND(scan);
1567 + /* Inline the first character, for speed. */
1568 + if (*opnd != *g->reginput)
1570 + len = strlen(opnd);
1571 + if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
1573 + g->reginput += len;
1577 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
1582 + if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1599 + register char *save;
1601 + no = OP(scan) - OPEN;
1602 + save = g->reginput;
1604 + if (regmatch(g, next)) {
1606 + * Don't set startp if some later
1607 + * invocation of the same parentheses
1610 + if (g->regstartp[no] == NULL)
1611 + g->regstartp[no] = save;
1628 + register char *save;
1630 + no = OP(scan) - CLOSE;
1631 + save = g->reginput;
1633 + if (regmatch(g, next)) {
1635 + * Don't set endp if some later
1636 + * invocation of the same parentheses
1639 + if (g->regendp[no] == NULL)
1640 + g->regendp[no] = save;
1647 + register char *save;
1649 + if (OP(next) != BRANCH) /* No choice. */
1650 + next = OPERAND(scan); /* Avoid recursion. */
1653 + save = g->reginput;
1654 + if (regmatch(g, OPERAND(scan)))
1656 + g->reginput = save;
1657 + scan = regnext(g, scan);
1658 + } while (scan != NULL && OP(scan) == BRANCH);
1666 + register char nextch;
1668 + register char *save;
1672 + * Lookahead to avoid useless match attempts
1673 + * when we know what character comes next.
1676 + if (OP(next) == EXACTLY)
1677 + nextch = *OPERAND(next);
1678 + min = (OP(scan) == STAR) ? 0 : 1;
1679 + save = g->reginput;
1680 + no = regrepeat(g, OPERAND(scan));
1681 + while (no >= min) {
1682 + /* If it could work, try it. */
1683 + if (nextch == '\0' || *g->reginput == nextch)
1684 + if (regmatch(g, next))
1686 + /* Couldn't or didn't -- back up. */
1688 + g->reginput = save + no;
1694 + return(1); /* Success! */
1697 + printk("<3>Regexp: memory corruption\n");
1706 + * We get here only if there's trouble -- normally "case END" is
1707 + * the terminating point.
1709 + printk("<3>Regexp: corrupted pointers\n");
1714 + - regrepeat - repeatedly match something simple, report how many
1717 +regrepeat(struct match_globals *g, char *p)
1719 + register int count = 0;
1720 + register char *scan;
1721 + register char *opnd;
1723 + scan = g->reginput;
1724 + opnd = OPERAND(p);
1727 + count = strlen(scan);
1731 + while (*opnd == *scan) {
1737 + while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1743 + while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1748 + default: /* Oh dear. Called inappropriately. */
1749 + printk("<3>Regexp: internal foulup\n");
1750 + count = 0; /* Best compromise. */
1753 + g->reginput = scan;
1759 + - regnext - dig the "next" pointer out of a node
1762 +regnext(struct match_globals *g, char *p)
1764 + register int offset;
1766 + if (p == &g->regdummy)
1773 + if (OP(p) == BACK)
1781 +STATIC char *regprop();
1784 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1790 + register char op = EXACTLY; /* Arbitrary non-END op. */
1791 + register char *next;
1792 + /* extern char *strchr(); */
1795 + s = r->program + 1;
1796 + while (op != END) { /* While that wasn't END last time... */
1798 + printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1799 + next = regnext(s);
1800 + if (next == NULL) /* Next ptr. */
1803 + printf("(%d)", (s-r->program)+(next-s));
1805 + if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1806 + /* Literal string, where present. */
1807 + while (*s != '\0') {
1816 + /* Header fields of interest. */
1817 + if (r->regstart != '\0')
1818 + printf("start `%c' ", r->regstart);
1820 + printf("anchored ");
1821 + if (r->regmust != NULL)
1822 + printf("must have \"%s\"", r->regmust);
1827 + - regprop - printable representation of opcode
1834 + static char buf[BUFLEN];
1878 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1890 + snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1900 + printk("<3>Regexp: corrupted opcode\n");
1904 + strncat(buf, p, BUFLEN-strlen(buf));
1911 +++ b/net/netfilter/regexp/regexp.h
1914 + * Definitions etc. for regexp(3) routines.
1916 + * Caveat: this is V8 regexp(3) [actually, a reimplementation thereof],
1917 + * not the System V one.
1925 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1926 +which contains a version of this library, says:
1929 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1930 + * will not work properly.
1933 +However, it looks rather like this library is limited to 10. If you think
1934 +otherwise, let us know.
1938 +typedef struct regexp {
1939 + char *startp[NSUBEXP];
1940 + char *endp[NSUBEXP];
1941 + char regstart; /* Internal use only. */
1942 + char reganch; /* Internal use only. */
1943 + char *regmust; /* Internal use only. */
1944 + int regmlen; /* Internal use only. */
1945 + char program[1]; /* Unwarranted chumminess with compiler. */
1948 +regexp * regcomp(char *exp, int *patternsize);
1949 +int regexec(regexp *prog, char *string);
1950 +void regsub(regexp *prog, char *source, char *dest);
1951 +void regerror(char *s);
1955 +++ b/net/netfilter/regexp/regmagic.h
1958 + * The first byte of the regexp internal "program" is actually this magic
1959 + * number; the start node begins in the second byte.
1963 +++ b/net/netfilter/regexp/regsub.c
1967 + * @(#)regsub.c 1.3 of 2 April 86
1969 + * Copyright (c) 1986 by University of Toronto.
1970 + * Written by Henry Spencer. Not derived from licensed software.
1972 + * Permission is granted to anyone to use this software for any
1973 + * purpose on any computer system, and to redistribute it freely,
1974 + * subject to the following restrictions:
1976 + * 1. The author is not responsible for the consequences of use of
1977 + * this software, no matter how awful, even if they arise
1978 + * from defects in it.
1980 + * 2. The origin of this software must not be misrepresented, either
1981 + * by explicit claim or by omission.
1983 + * 3. Altered versions must be plainly marked as such, and must not
1984 + * be misrepresented as being the original software.
1987 + * This code was modified by Ethan Sommer to work within the kernel
1988 + * (it now uses kmalloc etc..)
1991 +#include "regexp.h"
1992 +#include "regmagic.h"
1993 +#include <linux/string.h>
1997 +#define UCHARAT(p) ((int)*(unsigned char *)(p))
1999 +#define UCHARAT(p) ((int)*(p)&CHARBITS)
2003 +//void regerror(char * s)
2005 +// printk("regexp(3): %s", s);
2006 +// /* NOTREACHED */
2011 + - regsub - perform substitutions after a regexp match
2014 +regsub(regexp * prog, char * source, char * dest)
2016 + register char *src;
2017 + register char *dst;
2022 + /* Not necessary and gcc doesn't like it -MLS */
2023 + /*extern char *strncpy();*/
2025 + if (prog == NULL || source == NULL || dest == NULL) {
2026 + regerror("NULL parm to regsub");
2029 + if (UCHARAT(prog->program) != MAGIC) {
2030 + regerror("damaged regexp fed to regsub");
2036 + while ((c = *src++) != '\0') {
2039 + else if (c == '\\' && '0' <= *src && *src <= '9')
2040 + no = *src++ - '0';
2044 + if (no < 0) { /* Ordinary character. */
2045 + if (c == '\\' && (*src == '\\' || *src == '&'))
2048 + } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
2049 + len = prog->endp[no] - prog->startp[no];
2050 + (void) strncpy(dst, prog->startp[no], len);
2052 + if (len != 0 && *(dst-1) == '\0') { /* strncpy hit NUL. */
2053 + regerror("damaged match string");
2060 --- a/net/netfilter/nf_conntrack_core.c
2061 +++ b/net/netfilter/nf_conntrack_core.c
2062 @@ -213,6 +213,14 @@ destroy_conntrack(struct nf_conntrack *n
2064 nf_ct_remove_expectations(ct);
2066 + #if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
2067 + if(ct->layer7.app_proto)
2068 + kfree(ct->layer7.app_proto);
2069 + if(ct->layer7.app_data)
2070 + kfree(ct->layer7.app_data);
2074 /* We overload first tuple to link into unconfirmed list. */
2075 if (!nf_ct_is_confirmed(ct)) {
2076 BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
2077 --- a/net/netfilter/nf_conntrack_standalone.c
2078 +++ b/net/netfilter/nf_conntrack_standalone.c
2079 @@ -239,6 +239,12 @@ static int ct_seq_show(struct seq_file *
2080 if (ct_show_delta_time(s, ct))
2083 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
2084 + if(ct->layer7.app_proto &&
2085 + seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
2089 if (seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use)))
2092 --- a/include/net/netfilter/nf_conntrack.h
2093 +++ b/include/net/netfilter/nf_conntrack.h
2094 @@ -134,6 +134,22 @@ struct nf_conn {
2098 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
2099 + defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
2102 + * e.g. "http". NULL before decision. "unknown" after decision
2107 + * application layer data so far. NULL after match decision.
2110 + unsigned int app_data_len;
2114 /* Storage reserved for other modules, must be the last member */
2115 union nf_conntrack_proto proto;
2118 +++ b/include/linux/netfilter/xt_layer7.h
2120 +#ifndef _XT_LAYER7_H
2121 +#define _XT_LAYER7_H
2123 +#define MAX_PATTERN_LEN 8192
2124 +#define MAX_PROTOCOL_LEN 256
2126 +struct xt_layer7_info {
2127 + char protocol[MAX_PROTOCOL_LEN];
2128 + char pattern[MAX_PATTERN_LEN];
2132 +#endif /* _XT_LAYER7_H */
2133 --- a/include/linux/netfilter/Kbuild
2134 +++ b/include/linux/netfilter/Kbuild
2135 @@ -45,6 +45,7 @@ header-y += xt_hashlimit.h
2136 header-y += xt_helper.h
2137 header-y += xt_iprange.h
2138 header-y += xt_ipvs.h
2139 +header-y += xt_layer7.h
2140 header-y += xt_length.h
2141 header-y += xt_limit.h
2142 header-y += xt_mac.h