kernel: add support for 3.9-rc2
[openwrt.git] / target / linux / generic / patches-3.9 / 600-netfilter_layer7_2.22.patch
1 --- a/net/netfilter/Kconfig
2 +++ b/net/netfilter/Kconfig
3 @@ -1203,6 +1203,27 @@ config NETFILTER_XT_MATCH_STATE
4  
5           To compile it as a module, choose M here.  If unsure, say N.
6  
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
12 +       help
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
17 +         port.
18 +
19 +         To compile it as a module, choose M here.  If unsure, say N.
20 +
21 +config NETFILTER_XT_MATCH_LAYER7_DEBUG
22 +        bool 'Layer 7 debugging output'
23 +        depends on NETFILTER_XT_MATCH_LAYER7
24 +        help
25 +          Say Y to get lots of debugging output.
26 +
27 +
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 @@ -134,6 +134,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
41 --- /dev/null
42 +++ b/net/netfilter/xt_layer7.c
43 @@ -0,0 +1,666 @@
44 +/*
45 +  Kernel module to match application layer (OSI layer 7) data in connections.
46 +
47 +  http://l7-filter.sf.net
48 +
49 +  (C) 2003-2009 Matthew Strait and Ethan Sommer.
50 +
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
56 +
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.
60 +*/
61 +
62 +#include <linux/spinlock.h>
63 +#include <linux/version.h>
64 +#include <net/ip.h>
65 +#include <net/tcp.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>
74 +#endif
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>
79 +
80 +#include "regexp/regexp.c"
81 +
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");
87 +
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)
93 +#else
94 +       #define DPRINTK(format,args...)
95 +#endif
96 +
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;
100 +
101 +static struct pattern_cache {
102 +       char * regex_string;
103 +       regexp * pattern;
104 +       struct pattern_cache * next;
105 +} * first_pattern_cache = NULL;
106 +
107 +DEFINE_SPINLOCK(l7_lock);
108 +
109 +static int total_acct_packets(struct nf_conn *ct)
110 +{
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);
114 +#else
115 +       struct nf_conn_counter *acct;
116 +
117 +       BUG_ON(ct == NULL);
118 +       acct = nf_conn_acct_find(ct);
119 +       if (!acct)
120 +               return 0;
121 +       return (atomic64_read(&acct[IP_CT_DIR_ORIGINAL].packets) + atomic64_read(&acct[IP_CT_DIR_REPLY].packets));
122 +#endif
123 +}
124 +
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)
129 +{
130 +       char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
131 +       int i;
132 +
133 +       if(!f) {
134 +               if (net_ratelimit())
135 +                       printk(KERN_ERR "layer7: out of memory in "
136 +                                       "friendly_print, bailing.\n");
137 +               return NULL;
138 +       }
139 +
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] = ' ';
143 +               else                            f[i] = '.';
144 +       }
145 +       f[i] = '\0';
146 +       return f;
147 +}
148 +
149 +static char dec2hex(int i)
150 +{
151 +       switch (i) {
152 +               case 0 ... 9:
153 +                       return (i + '0');
154 +                       break;
155 +               case 10 ... 15:
156 +                       return (i - 10 + 'a');
157 +                       break;
158 +               default:
159 +                       if (net_ratelimit())
160 +                               printk("layer7: Problem in dec2hex\n");
161 +                       return '\0';
162 +       }
163 +}
164 +
165 +static char * hex_print(unsigned char * s)
166 +{
167 +       char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
168 +       int i;
169 +
170 +       if(!g) {
171 +              if (net_ratelimit())
172 +                       printk(KERN_ERR "layer7: out of memory in hex_print, "
173 +                                       "bailing.\n");
174 +              return NULL;
175 +       }
176 +
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);
180 +               g[i*3 + 2] = ' ';
181 +       }
182 +       g[i*3] = '\0';
183 +
184 +       return g;
185 +}
186 +#endif // DEBUG
187 +
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)
192 +{
193 +       struct pattern_cache * node               = first_pattern_cache;
194 +       struct pattern_cache * last_pattern_cache = first_pattern_cache;
195 +       struct pattern_cache * tmp;
196 +       unsigned int len;
197 +
198 +       while (node != NULL) {
199 +               if (!strcmp(node->regex_string, regex_string))
200 +               return node->pattern;
201 +
202 +               last_pattern_cache = node;/* points at the last non-NULL node */
203 +               node = node->next;
204 +       }
205 +
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);
210 +
211 +       if(!tmp) {
212 +               if (net_ratelimit())
213 +                       printk(KERN_ERR "layer7: out of memory in "
214 +                                       "compile_and_cache, bailing.\n");
215 +               return NULL;
216 +       }
217 +
218 +       tmp->regex_string  = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
219 +       tmp->pattern       = kmalloc(sizeof(struct regexp),    GFP_ATOMIC);
220 +       tmp->next = NULL;
221 +
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);
228 +               kfree(tmp);
229 +               return NULL;
230 +       }
231 +
232 +       /* Ok.  The new node is all ready now. */
233 +       node = tmp;
234 +
235 +       if(first_pattern_cache == NULL) /* list is empty */
236 +               first_pattern_cache = node; /* make node the beginning */
237 +       else
238 +               last_pattern_cache->next = node; /* attach node to the end */
239 +
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 "
247 +                                       "\"%s\" (%s)\n", 
248 +                                       regex_string, protocol);
249 +               /* pattern is now cached as NULL, so we won't try again. */
250 +       }
251 +
252 +       strcpy(node->regex_string, regex_string);
253 +       return node->pattern;
254 +}
255 +
256 +static int can_handle(const struct sk_buff *skb)
257 +{
258 +       if(!ip_hdr(skb)) /* not IP */
259 +               return 0;
260 +       if(ip_hdr(skb)->protocol != IPPROTO_TCP &&
261 +          ip_hdr(skb)->protocol != IPPROTO_UDP &&
262 +          ip_hdr(skb)->protocol != IPPROTO_ICMP)
263 +               return 0;
264 +       return 1;
265 +}
266 +
267 +/* Returns offset the into the skb->data that the application data starts */
268 +static int app_data_offset(const struct sk_buff *skb)
269 +{
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;
273 +
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);
280 +
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 */
286 +       } else {
287 +               if (net_ratelimit())
288 +                       printk(KERN_ERR "layer7: tried to handle unknown "
289 +                                       "protocol!\n");
290 +               return ip_hl + 8; /* something reasonable */
291 +       }
292 +}
293 +
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)
300 +{
301 +       /* If we're in here, throw the app data away */
302 +       if(master_conntrack->layer7.app_data != NULL) {
303 +
304 +       #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
305 +               if(!master_conntrack->layer7.app_proto) {
306 +                       char * f = 
307 +                         friendly_print(master_conntrack->layer7.app_data);
308 +                       char * g = 
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);
313 +                       kfree(f);
314 +                       DPRINTK("In hex: %s\n", g);
315 +                       kfree(g);
316 +               }
317 +       #endif
318 +
319 +               kfree(master_conntrack->layer7.app_data);
320 +               master_conntrack->layer7.app_data = NULL; /* don't free again */
321 +       }
322 +
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, 
328 +                           GFP_ATOMIC);
329 +                       if(!conntrack->layer7.app_proto){
330 +                               if (net_ratelimit())
331 +                                       printk(KERN_ERR "layer7: out of memory "
332 +                                                       "in match_no_append, "
333 +                                                       "bailing.\n");
334 +                               return 1;
335 +                       }
336 +                       strcpy(conntrack->layer7.app_proto, 
337 +                               master_conntrack->layer7.app_proto);
338 +               }
339 +
340 +               return (!strcmp(master_conntrack->layer7.app_proto, 
341 +                               info->protocol));
342 +       }
343 +       else {
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");
352 +                       return 1;
353 +               }
354 +               strcpy(master_conntrack->layer7.app_proto, "unknown");
355 +               return 0;
356 +       }
357 +}
358 +
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)
362 +{
363 +       int length = 0, i;
364 +       int oldlength = master_conntrack->layer7.app_data_len;
365 +
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;
371 +
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];
381 +                       length++;
382 +               }
383 +       }
384 +
385 +       master_conntrack->layer7.app_data[length+oldlength] = '\0';
386 +       master_conntrack->layer7.app_data_len = length + oldlength;
387 +
388 +       return length;
389 +}
390 +
391 +/* taken from drivers/video/modedb.c */
392 +static int my_atoi(const char *s)
393 +{
394 +       int val = 0;
395 +
396 +       for (;; s++) {
397 +               switch (*s) {
398 +                       case '0'...'9':
399 +                       val = 10*val+(*s-'0');
400 +                       break;
401 +               default:
402 +                       return val;
403 +               }
404 +       }
405 +}
406 +
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)
410 +{
411 +       if(num_packets > 99 && net_ratelimit())
412 +               printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
413 +
414 +       page[0] = num_packets/10 + '0';
415 +       page[1] = num_packets%10 + '0';
416 +       page[2] = '\n';
417 +       page[3] = '\0';
418 +
419 +       *eof=1;
420 +
421 +       return 3;
422 +}
423 +
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)
427 +{
428 +       char * foo = kmalloc(count, GFP_ATOMIC);
429 +
430 +       if(!foo){
431 +               if (net_ratelimit())
432 +                       printk(KERN_ERR "layer7: out of memory, bailing. "
433 +                                       "num_packets unchanged.\n");
434 +               return count;
435 +       }
436 +
437 +       if(copy_from_user(foo, buffer, count)) {
438 +               return -EFAULT;
439 +       }
440 +
441 +
442 +       num_packets = my_atoi(foo);
443 +       kfree (foo);
444 +
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");
449 +               num_packets = 99;
450 +       } else if(num_packets < 1) {
451 +               printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
452 +               num_packets = 1;
453 +       }
454 +
455 +       return count;
456 +}
457 +
458 +static bool
459 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
460 +match(const struct sk_buff *skbin, const struct xt_match_param *par)
461 +#else
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,
467 +      int offset,
468 +      unsigned int protoff,
469 +      bool *hotdrop)
470 +#endif
471 +{
472 +       /* sidestep const without getting a compiler warning... */
473 +       struct sk_buff * skb = (struct sk_buff *)skbin; 
474 +
475 +       const struct xt_layer7_info * info = 
476 +       #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
477 +               par->matchinfo;
478 +       #else
479 +               matchinfo;
480 +       #endif
481 +
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;
487 +
488 +       /* Be paranoid/incompetent - lock the entire match function. */
489 +       spin_lock_bh(&l7_lock);
490 +
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;
495 +       }
496 +
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;
505 +       }
506 +
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);
510 +
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) {
514 +
515 +               pattern_result = match_no_append(conntrack, master_conntrack, 
516 +                                                ctinfo, master_ctinfo, info);
517 +
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 */
524 +
525 +               spin_unlock_bh(&l7_lock);
526 +               return (pattern_result ^ info->invert);
527 +       }
528 +
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;
536 +               }
537 +       }
538 +
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;
542 +
543 +       /* the return value gets checked later, when we're ready to use it */
544 +       comppattern = compile_and_cache(info->pattern, info->protocol);
545 +
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;
557 +               }
558 +
559 +               master_conntrack->layer7.app_data[0] = '\0';
560 +       }
561 +
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 */
567 +       }
568 +
569 +       if(!skb->cb[0]){
570 +               int newbytes;
571 +               newbytes = add_data(master_conntrack, app_data, appdatalen);
572 +
573 +               if(newbytes == 0) { /* didn't add any data */
574 +                       skb->cb[0] = 1;
575 +                       /* Didn't match before, not going to match now */
576 +                       spin_unlock_bh(&l7_lock);
577 +                       return info->invert;
578 +               }
579 +       }
580 +
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;
598 +
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);
608 +               }
609 +               strcpy(master_conntrack->layer7.app_proto, info->protocol);
610 +       } else if(pattern_result > 1) { /* cleanup from "unset" */
611 +               pattern_result = 1;
612 +       }
613 +
614 +       /* mark the packet seen */
615 +       skb->cb[0] = 1;
616 +
617 +       spin_unlock_bh(&l7_lock);
618 +       return (pattern_result ^ info->invert);
619 +}
620 +
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)
624 +{
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);
628 +#else
629 +static bool check(const char *tablename, const void *inf,
630 +                const struct xt_match *match, void *matchinfo,
631 +                unsigned int hook_mask)
632 +{
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);
636 +#endif
637 +                return 0;
638 +        }
639 +       return 1;
640 +}
641 +
642 +
643 +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
644 +       static void destroy(const struct xt_mtdtor_param *par)
645 +       {
646 +               nf_ct_l3proto_module_put(par->match->family);
647 +       }
648 +#else
649 +       static void destroy(const struct xt_match *match, void *matchinfo)
650 +       {
651 +               nf_ct_l3proto_module_put(match->family);
652 +       }
653 +#endif
654 +
655 +static struct xt_match xt_layer7_match[] __read_mostly = {
656 +{
657 +       .name           = "layer7",
658 +       .family         = AF_INET,
659 +       .checkentry     = check,
660 +       .match          = match,
661 +       .destroy        = destroy,
662 +       .matchsize      = sizeof(struct xt_layer7_info),
663 +       .me             = THIS_MODULE
664 +}
665 +};
666 +
667 +static void layer7_cleanup_proc(void)
668 +{
669 +       remove_proc_entry("layer7_numpackets", init_net.proc_net);
670 +}
671 +
672 +/* register the proc file */
673 +static void layer7_init_proc(void)
674 +{
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;
679 +}
680 +
681 +static int __init xt_layer7_init(void)
682 +{
683 +       need_conntrack();
684 +
685 +       layer7_init_proc();
686 +       if(maxdatalen < 1) {
687 +               printk(KERN_WARNING "layer7: maxdatalen can't be < 1, "
688 +                       "using 1\n");
689 +               maxdatalen = 1;
690 +       }
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, "
695 +                       "using 65536\n");
696 +               maxdatalen = 65536;
697 +       }
698 +       return xt_register_matches(xt_layer7_match,
699 +                                  ARRAY_SIZE(xt_layer7_match));
700 +}
701 +
702 +static void __exit xt_layer7_fini(void)
703 +{
704 +       layer7_cleanup_proc();
705 +       xt_unregister_matches(xt_layer7_match, ARRAY_SIZE(xt_layer7_match));
706 +}
707 +
708 +module_init(xt_layer7_init);
709 +module_exit(xt_layer7_fini);
710 --- /dev/null
711 +++ b/net/netfilter/regexp/regexp.c
712 @@ -0,0 +1,1197 @@
713 +/*
714 + * regcomp and regexec -- regsub and regerror are elsewhere
715 + * @(#)regexp.c        1.3 of 18 April 87
716 + *
717 + *     Copyright (c) 1986 by University of Toronto.
718 + *     Written by Henry Spencer.  Not derived from licensed software.
719 + *
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:
723 + *
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.
727 + *
728 + *     2. The origin of this software must not be misrepresented, either
729 + *             by explicit claim or by omission.
730 + *
731 + *     3. Altered versions must be plainly marked as such, and must not
732 + *             be misrepresented as being the original software.
733 + *
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.
737 + *
738 + * This code was modified by Ethan Sommer to work within the kernel
739 + * (it now uses kmalloc etc..)
740 + *
741 + * Modified slightly by Matthew Strait to use more modern C.
742 + */
743 +
744 +#include "regexp.h"
745 +#include "regmagic.h"
746 +
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... */
749 +#if __KERNEL__
750 +  #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
751 +#else
752 +  #define printk(format,args...) printf(format,##args)
753 +#endif
754 +
755 +void regerror(char * s)
756 +{
757 +        printk("<3>Regexp: %s\n", s);
758 +        /* NOTREACHED */
759 +}
760 +
761 +/*
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:
765 + *
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
770 + *
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
778 + * it anyway.
779 + */
780 +
781 +/*
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:
795 + */
796 +
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. */
813 +
814 +/*
815 + * Opcode notes:
816 + *
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.
824 + *
825 + * BACK                Normal "next" pointers all implicitly point forward; BACK
826 + *             exists to make loop structures possible.
827 + *
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.
832 + *
833 + * OPEN,CLOSE  ...are numbered at compile time.
834 + */
835 +
836 +/*
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.)
842 + *
843 + * Using two bytes for the "next" pointer is vast overkill for most things,
844 + * but allows patterns to get big without disasters.
845 + */
846 +#define        OP(p)   (*(p))
847 +#define        NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
848 +#define        OPERAND(p)      ((p) + 3)
849 +
850 +/*
851 + * See regmagic.h for one further detail of program structure.
852 + */
853 +
854 +
855 +/*
856 + * Utility definitions.
857 + */
858 +#ifndef CHARBITS
859 +#define        UCHARAT(p)      ((int)*(unsigned char *)(p))
860 +#else
861 +#define        UCHARAT(p)      ((int)*(p)&CHARBITS)
862 +#endif
863 +
864 +#define        FAIL(m) { regerror(m); return(NULL); }
865 +#define        ISMULT(c)       ((c) == '*' || (c) == '+' || (c) == '?')
866 +#define        META    "^$.[()|?+*\\"
867 +
868 +/*
869 + * Flags to be passed up and down.
870 + */
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. */
875 +
876 +/*
877 + * Global work variables for regcomp().
878 + */
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. */
886 +char regdummy;
887 +char *regcode;         /* Code-emit pointer; &regdummy = don't. */
888 +long regsize;          /* Code size. */
889 +};
890 +
891 +/*
892 + * Forward declarations for regcomp()'s friends.
893 + */
894 +#ifndef STATIC
895 +#define        STATIC  static
896 +#endif
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);
907 +
908 +
909 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
910 +{
911 +        char *scan1;
912 +        char *scan2;
913 +        int count;
914 +
915 +        count = 0;
916 +        for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
917 +                for (scan2 = (char *)s2; *scan2 != '\0';)       /* ++ moved down. */
918 +                        if (*scan1 == *scan2++)
919 +                                return(count);
920 +                count++;
921 +        }
922 +        return(count);
923 +}
924 +
925 +/*
926 + - regcomp - compile a regular expression into internal code
927 + *
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.)
936 + *
937 + * Beware that the optimization-preparation code in here knows about some
938 + * of the structure of the compiled regexp.
939 + */
940 +regexp *
941 +regcomp(char *exp,int *patternsize)
942 +{
943 +       register regexp *r;
944 +       register char *scan;
945 +       register char *longest;
946 +       register int len;
947 +       int flags;
948 +       struct match_globals g;
949 +       
950 +       /* commented out by ethan
951 +          extern char *malloc();
952 +       */
953 +
954 +       if (exp == NULL)
955 +               FAIL("NULL argument");
956 +
957 +       /* First pass: determine size, legality. */
958 +       g.regparse = exp;
959 +       g.regnpar = 1;
960 +       g.regsize = 0L;
961 +       g.regcode = &g.regdummy;
962 +       regc(&g, MAGIC);
963 +       if (reg(&g, 0, &flags) == NULL)
964 +               return(NULL);
965 +
966 +       /* Small enough for pointer-storage convention? */
967 +       if (g.regsize >= 32767L)                /* Probably could be 65535L. */
968 +               FAIL("regexp too big");
969 +
970 +       /* Allocate space. */
971 +       *patternsize=sizeof(regexp) + (unsigned)g.regsize;
972 +       r = (regexp *)malloc(sizeof(regexp) + (unsigned)g.regsize);
973 +       if (r == NULL)
974 +               FAIL("out of space");
975 +
976 +       /* Second pass: emit code. */
977 +       g.regparse = exp;
978 +       g.regnpar = 1;
979 +       g.regcode = r->program;
980 +       regc(&g, MAGIC);
981 +       if (reg(&g, 0, &flags) == NULL)
982 +               return(NULL);
983 +
984 +       /* Dig out information for optimizations. */
985 +       r->regstart = '\0';     /* Worst-case defaults. */
986 +       r->reganch = 0;
987 +       r->regmust = NULL;
988 +       r->regmlen = 0;
989 +       scan = r->program+1;                    /* First BRANCH. */
990 +       if (OP(regnext(&g, scan)) == END) {             /* Only one top-level choice. */
991 +               scan = OPERAND(scan);
992 +
993 +               /* Starting-point info. */
994 +               if (OP(scan) == EXACTLY)
995 +                       r->regstart = *OPERAND(scan);
996 +               else if (OP(scan) == BOL)
997 +                       r->reganch++;
998 +
999 +               /*
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.
1006 +                */
1007 +               if (flags&SPSTART) {
1008 +                       longest = NULL;
1009 +                       len = 0;
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));
1014 +                               }
1015 +                       r->regmust = longest;
1016 +                       r->regmlen = len;
1017 +               }
1018 +       }
1019 +
1020 +       return(r);
1021 +}
1022 +
1023 +/*
1024 + - reg - regular expression, i.e. main body or parenthesized thing
1025 + *
1026 + * Caller must absorb opening parenthesis.
1027 + *
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.
1031 + */
1032 +static char *
1033 +reg(struct match_globals *g, int paren, int *flagp /* Parenthesized? */ )
1034 +{
1035 +       register char *ret;
1036 +       register char *br;
1037 +       register char *ender;
1038 +       register int parno = 0; /* 0 makes gcc happy */
1039 +       int flags;
1040 +
1041 +       *flagp = HASWIDTH;      /* Tentatively. */
1042 +
1043 +       /* Make an OPEN node, if parenthesized. */
1044 +       if (paren) {
1045 +               if (g->regnpar >= NSUBEXP)
1046 +                       FAIL("too many ()");
1047 +               parno = g->regnpar;
1048 +               g->regnpar++;
1049 +               ret = regnode(g, OPEN+parno);
1050 +       } else
1051 +               ret = NULL;
1052 +
1053 +       /* Pick up the branches, linking them together. */
1054 +       br = regbranch(g, &flags);
1055 +       if (br == NULL)
1056 +               return(NULL);
1057 +       if (ret != NULL)
1058 +               regtail(g, ret, br);    /* OPEN -> first. */
1059 +       else
1060 +               ret = br;
1061 +       if (!(flags&HASWIDTH))
1062 +               *flagp &= ~HASWIDTH;
1063 +       *flagp |= flags&SPSTART;
1064 +       while (*g->regparse == '|') {
1065 +               g->regparse++;
1066 +               br = regbranch(g, &flags);
1067 +               if (br == NULL)
1068 +                       return(NULL);
1069 +               regtail(g, ret, br);    /* BRANCH -> BRANCH. */
1070 +               if (!(flags&HASWIDTH))
1071 +                       *flagp &= ~HASWIDTH;
1072 +               *flagp |= flags&SPSTART;
1073 +       }
1074 +
1075 +       /* Make a closing node, and hook it on the end. */
1076 +       ender = regnode(g, (paren) ? CLOSE+parno : END);        
1077 +       regtail(g, ret, ender);
1078 +
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);
1082 +
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 ()");
1089 +               } else
1090 +                       FAIL("junk on end");    /* "Can't happen". */
1091 +               /* NOTREACHED */
1092 +       }
1093 +
1094 +       return(ret);
1095 +}
1096 +
1097 +/*
1098 + - regbranch - one alternative of an | operator
1099 + *
1100 + * Implements the concatenation operator.
1101 + */
1102 +static char *
1103 +regbranch(struct match_globals *g, int *flagp)
1104 +{
1105 +       register char *ret;
1106 +       register char *chain;
1107 +       register char *latest;
1108 +       int flags;
1109 +
1110 +       *flagp = WORST;         /* Tentatively. */
1111 +
1112 +       ret = regnode(g, BRANCH);
1113 +       chain = NULL;
1114 +       while (*g->regparse != '\0' && *g->regparse != '|' && *g->regparse != ')') {
1115 +               latest = regpiece(g, &flags);
1116 +               if (latest == NULL)
1117 +                       return(NULL);
1118 +               *flagp |= flags&HASWIDTH;
1119 +               if (chain == NULL)      /* First piece. */
1120 +                       *flagp |= flags&SPSTART;
1121 +               else
1122 +                       regtail(g, chain, latest);
1123 +               chain = latest;
1124 +       }
1125 +       if (chain == NULL)      /* Loop ran zero times. */
1126 +               (void) regnode(g, NOTHING);
1127 +
1128 +       return(ret);
1129 +}
1130 +
1131 +/*
1132 + - regpiece - something followed by possible [*+?]
1133 + *
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.
1139 + */
1140 +static char *
1141 +regpiece(struct match_globals *g, int *flagp)
1142 +{
1143 +       register char *ret;
1144 +       register char op;
1145 +       register char *next;
1146 +       int flags;
1147 +
1148 +       ret = regatom(g, &flags);
1149 +       if (ret == NULL)
1150 +               return(NULL);
1151 +
1152 +       op = *g->regparse;
1153 +       if (!ISMULT(op)) {
1154 +               *flagp = flags;
1155 +               return(ret);
1156 +       }
1157 +
1158 +       if (!(flags&HASWIDTH) && op != '?')
1159 +               FAIL("*+ operand could be empty");
1160 +       *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
1161 +
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);
1187 +       }
1188 +       g->regparse++;
1189 +       if (ISMULT(*g->regparse))
1190 +               FAIL("nested *?+");
1191 +
1192 +       return(ret);
1193 +}
1194 +
1195 +/*
1196 + - regatom - the lowest level
1197 + *
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.
1202 + */
1203 +static char *
1204 +regatom(struct match_globals *g, int *flagp)
1205 +{
1206 +       register char *ret;
1207 +       int flags;
1208 +
1209 +       *flagp = WORST;         /* Tentatively. */
1210 +
1211 +       switch (*g->regparse++) {
1212 +       case '^':
1213 +               ret = regnode(g, BOL);
1214 +               break;
1215 +       case '$':
1216 +               ret = regnode(g, EOL);
1217 +               break;
1218 +       case '.':
1219 +               ret = regnode(g, ANY);
1220 +               *flagp |= HASWIDTH|SIMPLE;
1221 +               break;
1222 +       case '[': {
1223 +                       register int class;
1224 +                       register int classend;
1225 +
1226 +                       if (*g->regparse == '^') {      /* Complement of range. */
1227 +                               ret = regnode(g, ANYBUT);
1228 +                               g->regparse++;
1229 +                       } else
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 == '-') {
1235 +                                       g->regparse++;
1236 +                                       if (*g->regparse == ']' || *g->regparse == '\0')
1237 +                                               regc(g, '-');
1238 +                                       else {
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++)
1244 +                                                       regc(g, class);
1245 +                                               g->regparse++;
1246 +                                       }
1247 +                               } else
1248 +                                       regc(g, *g->regparse++);
1249 +                       }
1250 +                       regc(g, '\0');
1251 +                       if (*g->regparse != ']')
1252 +                               FAIL("unmatched []");
1253 +                       g->regparse++;
1254 +                       *flagp |= HASWIDTH|SIMPLE;
1255 +               }
1256 +               break;
1257 +       case '(':
1258 +               ret = reg(g, 1, &flags);
1259 +               if (ret == NULL)
1260 +                       return(NULL);
1261 +               *flagp |= flags&(HASWIDTH|SPSTART);
1262 +               break;
1263 +       case '\0':
1264 +       case '|':
1265 +       case ')':
1266 +               FAIL("internal urp");   /* Supposed to be caught earlier. */
1267 +               break;
1268 +       case '?':
1269 +       case '+':
1270 +       case '*':
1271 +               FAIL("?+* follows nothing");
1272 +               break;
1273 +       case '\\':
1274 +               if (*g->regparse == '\0')
1275 +                       FAIL("trailing \\");
1276 +               ret = regnode(g, EXACTLY);
1277 +               regc(g, *g->regparse++);
1278 +               regc(g, '\0');
1279 +               *flagp |= HASWIDTH|SIMPLE;
1280 +               break;
1281 +       default: {
1282 +                       register int len;
1283 +                       register char ender;
1284 +
1285 +                       g->regparse--;
1286 +                       len = my_strcspn((const char *)g->regparse, (const char *)META);
1287 +                       if (len <= 0)
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;
1293 +                       if (len == 1)
1294 +                               *flagp |= SIMPLE;
1295 +                       ret = regnode(g, EXACTLY);
1296 +                       while (len > 0) {
1297 +                               regc(g, *g->regparse++);
1298 +                               len--;
1299 +                       }
1300 +                       regc(g, '\0');
1301 +               }
1302 +               break;
1303 +       }
1304 +
1305 +       return(ret);
1306 +}
1307 +
1308 +/*
1309 + - regnode - emit a node
1310 + */
1311 +static char *                  /* Location. */
1312 +regnode(struct match_globals *g, char op)
1313 +{
1314 +       register char *ret;
1315 +       register char *ptr;
1316 +
1317 +       ret = g->regcode;
1318 +       if (ret == &g->regdummy) {
1319 +               g->regsize += 3;
1320 +               return(ret);
1321 +       }
1322 +
1323 +       ptr = ret;
1324 +       *ptr++ = op;
1325 +       *ptr++ = '\0';          /* Null "next" pointer. */
1326 +       *ptr++ = '\0';
1327 +       g->regcode = ptr;
1328 +
1329 +       return(ret);
1330 +}
1331 +
1332 +/*
1333 + - regc - emit (if appropriate) a byte of code
1334 + */
1335 +static void
1336 +regc(struct match_globals *g, char b)
1337 +{
1338 +       if (g->regcode != &g->regdummy)
1339 +               *g->regcode++ = b;
1340 +       else
1341 +               g->regsize++;
1342 +}
1343 +
1344 +/*
1345 + - reginsert - insert an operator in front of already-emitted operand
1346 + *
1347 + * Means relocating the operand.
1348 + */
1349 +static void
1350 +reginsert(struct match_globals *g, char op, char* opnd)
1351 +{
1352 +       register char *src;
1353 +       register char *dst;
1354 +       register char *place;
1355 +
1356 +       if (g->regcode == &g->regdummy) {
1357 +               g->regsize += 3;
1358 +               return;
1359 +       }
1360 +
1361 +       src = g->regcode;
1362 +       g->regcode += 3;
1363 +       dst = g->regcode;
1364 +       while (src > opnd)
1365 +               *--dst = *--src;
1366 +
1367 +       place = opnd;           /* Op node, where operand used to be. */
1368 +       *place++ = op;
1369 +       *place++ = '\0';
1370 +       *place++ = '\0';
1371 +}
1372 +
1373 +/*
1374 + - regtail - set the next-pointer at the end of a node chain
1375 + */
1376 +static void
1377 +regtail(struct match_globals *g, char *p, char *val)
1378 +{
1379 +       register char *scan;
1380 +       register char *temp;
1381 +       register int offset;
1382 +
1383 +       if (p == &g->regdummy)
1384 +               return;
1385 +
1386 +       /* Find last node. */
1387 +       scan = p;
1388 +       for (;;) {
1389 +               temp = regnext(g, scan);
1390 +               if (temp == NULL)
1391 +                       break;
1392 +               scan = temp;
1393 +       }
1394 +
1395 +       if (OP(scan) == BACK)
1396 +               offset = scan - val;
1397 +       else
1398 +               offset = val - scan;
1399 +       *(scan+1) = (offset>>8)&0377;
1400 +       *(scan+2) = offset&0377;
1401 +}
1402 +
1403 +/*
1404 + - regoptail - regtail on operand of first argument; nop if operandless
1405 + */
1406 +static void
1407 +regoptail(struct match_globals *g, char *p, char *val)
1408 +{
1409 +       /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1410 +       if (p == NULL || p == &g->regdummy || OP(p) != BRANCH)
1411 +               return;
1412 +       regtail(g, OPERAND(p), val);
1413 +}
1414 +
1415 +/*
1416 + * regexec and friends
1417 + */
1418 +
1419 +
1420 +/*
1421 + * Forwards.
1422 + */
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);
1426 +
1427 +#ifdef DEBUG
1428 +int regnarrate = 0;
1429 +void regdump();
1430 +STATIC char *regprop(char *op);
1431 +#endif
1432 +
1433 +/*
1434 + - regexec - match a regexp against a string
1435 + */
1436 +int
1437 +regexec(regexp *prog, char *string)
1438 +{
1439 +       register char *s;
1440 +       struct match_globals g;
1441 +
1442 +       /* Be paranoid... */
1443 +       if (prog == NULL || string == NULL) {
1444 +               printk("<3>Regexp: NULL parameter\n");
1445 +               return(0);
1446 +       }
1447 +
1448 +       /* Check validity of program. */
1449 +       if (UCHARAT(prog->program) != MAGIC) {
1450 +               printk("<3>Regexp: corrupted program\n");
1451 +               return(0);
1452 +       }
1453 +
1454 +       /* If there is a "must appear" string, look for it. */
1455 +       if (prog->regmust != NULL) {
1456 +               s = string;
1457 +               while ((s = strchr(s, prog->regmust[0])) != NULL) {
1458 +                       if (strncmp(s, prog->regmust, prog->regmlen) == 0)
1459 +                               break;  /* Found it. */
1460 +                       s++;
1461 +               }
1462 +               if (s == NULL)  /* Not present. */
1463 +                       return(0);
1464 +       }
1465 +
1466 +       /* Mark beginning of line for ^ . */
1467 +       g.regbol = string;
1468 +
1469 +       /* Simplest case:  anchored match need be tried only once. */
1470 +       if (prog->reganch)
1471 +               return(regtry(&g, prog, string));
1472 +
1473 +       /* Messy cases:  unanchored match. */
1474 +       s = string;
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))
1479 +                               return(1);
1480 +                       s++;
1481 +               }
1482 +       else
1483 +               /* We don't -- general case. */
1484 +               do {
1485 +                       if (regtry(&g, prog, s))
1486 +                               return(1);
1487 +               } while (*s++ != '\0');
1488 +
1489 +       /* Failure. */
1490 +       return(0);
1491 +}
1492 +
1493 +/*
1494 + - regtry - try match at specific point
1495 + */
1496 +static int                     /* 0 failure, 1 success */
1497 +regtry(struct match_globals *g, regexp *prog, char *string)
1498 +{
1499 +       register int i;
1500 +       register char **sp;
1501 +       register char **ep;
1502 +
1503 +       g->reginput = string;
1504 +       g->regstartp = prog->startp;
1505 +       g->regendp = prog->endp;
1506 +
1507 +       sp = prog->startp;
1508 +       ep = prog->endp;
1509 +       for (i = NSUBEXP; i > 0; i--) {
1510 +               *sp++ = NULL;
1511 +               *ep++ = NULL;
1512 +       }
1513 +       if (regmatch(g, prog->program + 1)) {
1514 +               prog->startp[0] = string;
1515 +               prog->endp[0] = g->reginput;
1516 +               return(1);
1517 +       } else
1518 +               return(0);
1519 +}
1520 +
1521 +/*
1522 + - regmatch - main matching routine
1523 + *
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
1529 + * by recursion.
1530 + */
1531 +static int                     /* 0 failure, 1 success */
1532 +regmatch(struct match_globals *g, char *prog)
1533 +{
1534 +       register char *scan = prog; /* Current node. */
1535 +       char *next;                 /* Next node. */
1536 +
1537 +#ifdef DEBUG
1538 +       if (scan != NULL && regnarrate)
1539 +               fprintf(stderr, "%s(\n", regprop(scan));
1540 +#endif
1541 +       while (scan != NULL) {
1542 +#ifdef DEBUG
1543 +               if (regnarrate)
1544 +                       fprintf(stderr, "%s...\n", regprop(scan));
1545 +#endif
1546 +               next = regnext(g, scan);
1547 +
1548 +               switch (OP(scan)) {
1549 +               case BOL:
1550 +                       if (g->reginput != g->regbol)
1551 +                               return(0);
1552 +                       break;
1553 +               case EOL:
1554 +                       if (*g->reginput != '\0')
1555 +                               return(0);
1556 +                       break;
1557 +               case ANY:
1558 +                       if (*g->reginput == '\0')
1559 +                               return(0);
1560 +                       g->reginput++;
1561 +                       break;
1562 +               case EXACTLY: {
1563 +                               register int len;
1564 +                               register char *opnd;
1565 +
1566 +                               opnd = OPERAND(scan);
1567 +                               /* Inline the first character, for speed. */
1568 +                               if (*opnd != *g->reginput)
1569 +                                       return(0);
1570 +                               len = strlen(opnd);
1571 +                               if (len > 1 && strncmp(opnd, g->reginput, len) != 0)
1572 +                                       return(0);
1573 +                               g->reginput += len;
1574 +                       }
1575 +                       break;
1576 +               case ANYOF:
1577 +                       if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) == NULL)
1578 +                               return(0);
1579 +                       g->reginput++;
1580 +                       break;
1581 +               case ANYBUT:
1582 +                       if (*g->reginput == '\0' || strchr(OPERAND(scan), *g->reginput) != NULL)
1583 +                               return(0);
1584 +                       g->reginput++;
1585 +                       break;
1586 +               case NOTHING:
1587 +               case BACK:
1588 +                       break;
1589 +               case OPEN+1:
1590 +               case OPEN+2:
1591 +               case OPEN+3:
1592 +               case OPEN+4:
1593 +               case OPEN+5:
1594 +               case OPEN+6:
1595 +               case OPEN+7:
1596 +               case OPEN+8:
1597 +               case OPEN+9: {
1598 +                               register int no;
1599 +                               register char *save;
1600 +
1601 +                               no = OP(scan) - OPEN;
1602 +                               save = g->reginput;
1603 +
1604 +                               if (regmatch(g, next)) {
1605 +                                       /*
1606 +                                        * Don't set startp if some later
1607 +                                        * invocation of the same parentheses
1608 +                                        * already has.
1609 +                                        */
1610 +                                       if (g->regstartp[no] == NULL)
1611 +                                               g->regstartp[no] = save;
1612 +                                       return(1);
1613 +                               } else
1614 +                                       return(0);
1615 +                       }
1616 +                       break;
1617 +               case CLOSE+1:
1618 +               case CLOSE+2:
1619 +               case CLOSE+3:
1620 +               case CLOSE+4:
1621 +               case CLOSE+5:
1622 +               case CLOSE+6:
1623 +               case CLOSE+7:
1624 +               case CLOSE+8:
1625 +               case CLOSE+9:
1626 +                       {
1627 +                               register int no;
1628 +                               register char *save;
1629 +
1630 +                               no = OP(scan) - CLOSE;
1631 +                               save = g->reginput;
1632 +
1633 +                               if (regmatch(g, next)) {
1634 +                                       /*
1635 +                                        * Don't set endp if some later
1636 +                                        * invocation of the same parentheses
1637 +                                        * already has.
1638 +                                        */
1639 +                                       if (g->regendp[no] == NULL)
1640 +                                               g->regendp[no] = save;
1641 +                                       return(1);
1642 +                               } else
1643 +                                       return(0);
1644 +                       }
1645 +                       break;
1646 +               case BRANCH: {
1647 +                               register char *save;
1648 +
1649 +                               if (OP(next) != BRANCH)         /* No choice. */
1650 +                                       next = OPERAND(scan);   /* Avoid recursion. */
1651 +                               else {
1652 +                                       do {
1653 +                                               save = g->reginput;
1654 +                                               if (regmatch(g, OPERAND(scan)))
1655 +                                                       return(1);
1656 +                                               g->reginput = save;
1657 +                                               scan = regnext(g, scan);
1658 +                                       } while (scan != NULL && OP(scan) == BRANCH);
1659 +                                       return(0);
1660 +                                       /* NOTREACHED */
1661 +                               }
1662 +                       }
1663 +                       break;
1664 +               case STAR:
1665 +               case PLUS: {
1666 +                               register char nextch;
1667 +                               register int no;
1668 +                               register char *save;
1669 +                               register int min;
1670 +
1671 +                               /*
1672 +                                * Lookahead to avoid useless match attempts
1673 +                                * when we know what character comes next.
1674 +                                */
1675 +                               nextch = '\0';
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))
1685 +                                                       return(1);
1686 +                                       /* Couldn't or didn't -- back up. */
1687 +                                       no--;
1688 +                                       g->reginput = save + no;
1689 +                               }
1690 +                               return(0);
1691 +                       }
1692 +                       break;
1693 +               case END:
1694 +                       return(1);      /* Success! */
1695 +                       break;
1696 +               default:
1697 +                       printk("<3>Regexp: memory corruption\n");
1698 +                       return(0);
1699 +                       break;
1700 +               }
1701 +
1702 +               scan = next;
1703 +       }
1704 +
1705 +       /*
1706 +        * We get here only if there's trouble -- normally "case END" is
1707 +        * the terminating point.
1708 +        */
1709 +       printk("<3>Regexp: corrupted pointers\n");
1710 +       return(0);
1711 +}
1712 +
1713 +/*
1714 + - regrepeat - repeatedly match something simple, report how many
1715 + */
1716 +static int
1717 +regrepeat(struct match_globals *g, char *p)
1718 +{
1719 +       register int count = 0;
1720 +       register char *scan;
1721 +       register char *opnd;
1722 +
1723 +       scan = g->reginput;
1724 +       opnd = OPERAND(p);
1725 +       switch (OP(p)) {
1726 +       case ANY:
1727 +               count = strlen(scan);
1728 +               scan += count;
1729 +               break;
1730 +       case EXACTLY:
1731 +               while (*opnd == *scan) {
1732 +                       count++;
1733 +                       scan++;
1734 +               }
1735 +               break;
1736 +       case ANYOF:
1737 +               while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1738 +                       count++;
1739 +                       scan++;
1740 +               }
1741 +               break;
1742 +       case ANYBUT:
1743 +               while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1744 +                       count++;
1745 +                       scan++;
1746 +               }
1747 +               break;
1748 +       default:                /* Oh dear.  Called inappropriately. */
1749 +               printk("<3>Regexp: internal foulup\n");
1750 +               count = 0;      /* Best compromise. */
1751 +               break;
1752 +       }
1753 +       g->reginput = scan;
1754 +
1755 +       return(count);
1756 +}
1757 +
1758 +/*
1759 + - regnext - dig the "next" pointer out of a node
1760 + */
1761 +static char*
1762 +regnext(struct match_globals *g, char *p)
1763 +{
1764 +       register int offset;
1765 +
1766 +       if (p == &g->regdummy)
1767 +               return(NULL);
1768 +
1769 +       offset = NEXT(p);
1770 +       if (offset == 0)
1771 +               return(NULL);
1772 +
1773 +       if (OP(p) == BACK)
1774 +               return(p-offset);
1775 +       else
1776 +               return(p+offset);
1777 +}
1778 +
1779 +#ifdef DEBUG
1780 +
1781 +STATIC char *regprop();
1782 +
1783 +/*
1784 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1785 + */
1786 +void
1787 +regdump(regexp *r)
1788 +{
1789 +       register char *s;
1790 +       register char op = EXACTLY;     /* Arbitrary non-END op. */
1791 +       register char *next;
1792 +       /* extern char *strchr(); */
1793 +
1794 +
1795 +       s = r->program + 1;
1796 +       while (op != END) {     /* While that wasn't END last time... */
1797 +               op = OP(s);
1798 +               printf("%2d%s", s-r->program, regprop(s));      /* Where, what. */
1799 +               next = regnext(s);
1800 +               if (next == NULL)               /* Next ptr. */
1801 +                       printf("(0)");
1802 +               else
1803 +                       printf("(%d)", (s-r->program)+(next-s));
1804 +               s += 3;
1805 +               if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1806 +                       /* Literal string, where present. */
1807 +                       while (*s != '\0') {
1808 +                               putchar(*s);
1809 +                               s++;
1810 +                       }
1811 +                       s++;
1812 +               }
1813 +               putchar('\n');
1814 +       }
1815 +
1816 +       /* Header fields of interest. */
1817 +       if (r->regstart != '\0')
1818 +               printf("start `%c' ", r->regstart);
1819 +       if (r->reganch)
1820 +               printf("anchored ");
1821 +       if (r->regmust != NULL)
1822 +               printf("must have \"%s\"", r->regmust);
1823 +       printf("\n");
1824 +}
1825 +
1826 +/*
1827 + - regprop - printable representation of opcode
1828 + */
1829 +static char *
1830 +regprop(char *op)
1831 +{
1832 +#define BUFLEN 50
1833 +       register char *p;
1834 +       static char buf[BUFLEN];
1835 +
1836 +       strcpy(buf, ":");
1837 +
1838 +       switch (OP(op)) {
1839 +       case BOL:
1840 +               p = "BOL";
1841 +               break;
1842 +       case EOL:
1843 +               p = "EOL";
1844 +               break;
1845 +       case ANY:
1846 +               p = "ANY";
1847 +               break;
1848 +       case ANYOF:
1849 +               p = "ANYOF";
1850 +               break;
1851 +       case ANYBUT:
1852 +               p = "ANYBUT";
1853 +               break;
1854 +       case BRANCH:
1855 +               p = "BRANCH";
1856 +               break;
1857 +       case EXACTLY:
1858 +               p = "EXACTLY";
1859 +               break;
1860 +       case NOTHING:
1861 +               p = "NOTHING";
1862 +               break;
1863 +       case BACK:
1864 +               p = "BACK";
1865 +               break;
1866 +       case END:
1867 +               p = "END";
1868 +               break;
1869 +       case OPEN+1:
1870 +       case OPEN+2:
1871 +       case OPEN+3:
1872 +       case OPEN+4:
1873 +       case OPEN+5:
1874 +       case OPEN+6:
1875 +       case OPEN+7:
1876 +       case OPEN+8:
1877 +       case OPEN+9:
1878 +               snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1879 +               p = NULL;
1880 +               break;
1881 +       case CLOSE+1:
1882 +       case CLOSE+2:
1883 +       case CLOSE+3:
1884 +       case CLOSE+4:
1885 +       case CLOSE+5:
1886 +       case CLOSE+6:
1887 +       case CLOSE+7:
1888 +       case CLOSE+8:
1889 +       case CLOSE+9:
1890 +               snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1891 +               p = NULL;
1892 +               break;
1893 +       case STAR:
1894 +               p = "STAR";
1895 +               break;
1896 +       case PLUS:
1897 +               p = "PLUS";
1898 +               break;
1899 +       default:
1900 +               printk("<3>Regexp: corrupted opcode\n");
1901 +               break;
1902 +       }
1903 +       if (p != NULL)
1904 +               strncat(buf, p, BUFLEN-strlen(buf));
1905 +       return(buf);
1906 +}
1907 +#endif
1908 +
1909 +
1910 --- /dev/null
1911 +++ b/net/netfilter/regexp/regexp.h
1912 @@ -0,0 +1,41 @@
1913 +/*
1914 + * Definitions etc. for regexp(3) routines.
1915 + *
1916 + * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
1917 + * not the System V one.
1918 + */
1919 +
1920 +#ifndef REGEXP_H
1921 +#define REGEXP_H
1922 +
1923 +
1924 +/*
1925 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h ,
1926 +which contains a version of this library, says:
1927 +
1928 + *
1929 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1930 + * will not work properly.
1931 + *
1932 +
1933 +However, it looks rather like this library is limited to 10.  If you think
1934 +otherwise, let us know.
1935 +*/
1936 +
1937 +#define NSUBEXP  10
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. */
1946 +} regexp;
1947 +
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);
1952 +
1953 +#endif
1954 --- /dev/null
1955 +++ b/net/netfilter/regexp/regmagic.h
1956 @@ -0,0 +1,5 @@
1957 +/*
1958 + * The first byte of the regexp internal "program" is actually this magic
1959 + * number; the start node begins in the second byte.
1960 + */
1961 +#define        MAGIC   0234
1962 --- /dev/null
1963 +++ b/net/netfilter/regexp/regsub.c
1964 @@ -0,0 +1,95 @@
1965 +/*
1966 + * regsub
1967 + * @(#)regsub.c        1.3 of 2 April 86
1968 + *
1969 + *     Copyright (c) 1986 by University of Toronto.
1970 + *     Written by Henry Spencer.  Not derived from licensed software.
1971 + *
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:
1975 + *
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.
1979 + *
1980 + *     2. The origin of this software must not be misrepresented, either
1981 + *             by explicit claim or by omission.
1982 + *
1983 + *     3. Altered versions must be plainly marked as such, and must not
1984 + *             be misrepresented as being the original software.
1985 + *
1986 + *
1987 + * This code was modified by Ethan Sommer to work within the kernel
1988 + * (it now uses kmalloc etc..)
1989 + *
1990 + */
1991 +#include "regexp.h"
1992 +#include "regmagic.h"
1993 +#include <linux/string.h>
1994 +
1995 +
1996 +#ifndef CHARBITS
1997 +#define        UCHARAT(p)      ((int)*(unsigned char *)(p))
1998 +#else
1999 +#define        UCHARAT(p)      ((int)*(p)&CHARBITS)
2000 +#endif
2001 +
2002 +#if 0
2003 +//void regerror(char * s)
2004 +//{
2005 +//        printk("regexp(3): %s", s);
2006 +//        /* NOTREACHED */
2007 +//}
2008 +#endif
2009 +
2010 +/*
2011 + - regsub - perform substitutions after a regexp match
2012 + */
2013 +void
2014 +regsub(regexp * prog, char * source, char * dest)
2015 +{
2016 +       register char *src;
2017 +       register char *dst;
2018 +       register char c;
2019 +       register int no;
2020 +       register int len;
2021 +       
2022 +       /* Not necessary and gcc doesn't like it -MLS */
2023 +       /*extern char *strncpy();*/
2024 +
2025 +       if (prog == NULL || source == NULL || dest == NULL) {
2026 +               regerror("NULL parm to regsub");
2027 +               return;
2028 +       }
2029 +       if (UCHARAT(prog->program) != MAGIC) {
2030 +               regerror("damaged regexp fed to regsub");
2031 +               return;
2032 +       }
2033 +
2034 +       src = source;
2035 +       dst = dest;
2036 +       while ((c = *src++) != '\0') {
2037 +               if (c == '&')
2038 +                       no = 0;
2039 +               else if (c == '\\' && '0' <= *src && *src <= '9')
2040 +                       no = *src++ - '0';
2041 +               else
2042 +                       no = -1;
2043 +
2044 +               if (no < 0) {   /* Ordinary character. */
2045 +                       if (c == '\\' && (*src == '\\' || *src == '&'))
2046 +                               c = *src++;
2047 +                       *dst++ = c;
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);
2051 +                       dst += len;
2052 +                       if (len != 0 && *(dst-1) == '\0') {     /* strncpy hit NUL. */
2053 +                               regerror("damaged match string");
2054 +                               return;
2055 +                       }
2056 +               }
2057 +       }
2058 +       *dst++ = '\0';
2059 +}
2060 --- a/net/netfilter/nf_conntrack_core.c
2061 +++ b/net/netfilter/nf_conntrack_core.c
2062 @@ -222,6 +222,13 @@ destroy_conntrack(struct nf_conntrack *n
2063          * too. */
2064         nf_ct_remove_expectations(ct);
2065  
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);
2071 +#endif
2072 +
2073         /* We overload first tuple to link into unconfirmed or dying list.*/
2074         BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
2075         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
2076 --- a/net/netfilter/nf_conntrack_standalone.c
2077 +++ b/net/netfilter/nf_conntrack_standalone.c
2078 @@ -239,6 +239,12 @@ static int ct_seq_show(struct seq_file *
2079         if (ct_show_delta_time(s, ct))
2080                 goto release;
2081  
2082 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
2083 +       if(ct->layer7.app_proto &&
2084 +           seq_printf(s, "l7proto=%s ", ct->layer7.app_proto))
2085 +               return -ENOSPC;
2086 +#endif
2087 +
2088         if (seq_printf(s, "use=%u\n", atomic_read(&ct->ct_general.use)))
2089                 goto release;
2090  
2091 --- a/include/net/netfilter/nf_conntrack.h
2092 +++ b/include/net/netfilter/nf_conntrack.h
2093 @@ -105,6 +105,22 @@ struct nf_conn {
2094         struct net *ct_net;
2095  #endif
2096  
2097 +#if defined(CONFIG_NETFILTER_XT_MATCH_LAYER7) || \
2098 +    defined(CONFIG_NETFILTER_XT_MATCH_LAYER7_MODULE)
2099 +       struct {
2100 +               /*
2101 +                * e.g. "http". NULL before decision. "unknown" after decision
2102 +                * if no match.
2103 +                */
2104 +               char *app_proto;
2105 +               /*
2106 +                * application layer data so far. NULL after match decision.
2107 +                */
2108 +               char *app_data;
2109 +               unsigned int app_data_len;
2110 +       } layer7;
2111 +#endif
2112 +
2113         /* Storage reserved for other modules, must be the last member */
2114         union nf_conntrack_proto proto;
2115  };
2116 --- /dev/null
2117 +++ b/include/linux/netfilter/xt_layer7.h
2118 @@ -0,0 +1,13 @@
2119 +#ifndef _XT_LAYER7_H
2120 +#define _XT_LAYER7_H
2121 +
2122 +#define MAX_PATTERN_LEN 8192
2123 +#define MAX_PROTOCOL_LEN 256
2124 +
2125 +struct xt_layer7_info {
2126 +    char protocol[MAX_PROTOCOL_LEN];
2127 +    char pattern[MAX_PATTERN_LEN];
2128 +    u_int8_t invert;
2129 +};
2130 +
2131 +#endif /* _XT_LAYER7_H */
2132 --- a/include/uapi/linux/netfilter/Kbuild
2133 +++ b/include/uapi/linux/netfilter/Kbuild
2134 @@ -53,6 +53,7 @@ header-y += xt_hashlimit.h
2135  header-y += xt_helper.h
2136  header-y += xt_iprange.h
2137  header-y += xt_ipvs.h
2138 +header-y += xt_layer7.h
2139  header-y += xt_length.h
2140  header-y += xt_limit.h
2141  header-y += xt_mac.h