more fixes for the network scripts
[openwrt.git] / target / linux / linux-2.4 / patches / generic / 602-netfilter_layer7.patch
1 diff -Nurp linux-2.4.30/Documentation/Configure.help linux-2.4.30-layer7/Documentation/Configure.help
2 --- linux-2.4.30/Documentation/Configure.help   2005-04-03 20:42:19.000000000 -0500
3 +++ linux-2.4.30-layer7/Documentation/Configure.help    2005-05-03 18:37:03.000000000 -0500
4 @@ -29056,6 +29056,23 @@ CONFIG_SOUND_WM97XX
5    
6    If unsure, say N.
7  
8 +CONFIG_IP_NF_MATCH_LAYER7
9 +   Say Y if you want to be able to classify connections (and their 
10 +   packets) based on regular expression matching of their application 
11 +   layer data.   This is one way to classify applications such as 
12 +   peer-to-peer filesharing systems that do not always use the same 
13 +   port.
14 +
15 +   To compile it as a module, choose M here.  If unsure, say N.
16 +
17 +CONFIG_IP_NF_MATCH_LAYER7_DEBUG
18 +   Say Y to get lots of debugging output.
19 +
20 +CONFIG_IP_NF_MATCH_LAYER7_MAXDATALEN
21 +   Size of the buffer that the application layer data is stored in.
22 +   Unless you know what you're doing, leave it at the default of 2048
23 +   Bytes.
24 +
25  #
26  # A couple of things I keep forgetting:
27  #   capitalize: AppleTalk, Ethernet, DOS, DMA, FAT, FTP, Internet,
28 diff -Nurp linux-2.4.30/include/linux/netfilter_ipv4/ip_conntrack.h linux-2.4.30-layer7/include/linux/netfilter_ipv4/ip_conntrack.h
29 --- linux-2.4.30/include/linux/netfilter_ipv4/ip_conntrack.h    2005-04-03 20:42:20.000000000 -0500
30 +++ linux-2.4.30-layer7/include/linux/netfilter_ipv4/ip_conntrack.h     2005-05-03 18:37:03.000000000 -0500
31 @@ -207,6 +207,17 @@ struct ip_conntrack
32         } nat;
33  #endif /* CONFIG_IP_NF_NAT_NEEDED */
34  
35 +#if defined(CONFIG_IP_NF_MATCH_LAYER7) || defined(CONFIG_IP_NF_MATCH_LAYER7_MODULE)
36 +       struct {
37 +               unsigned int numpackets; /* surely this is kept track of somewhere else, right? I can't find it... */
38 +               char * app_proto; /* "http", "ftp", etc.  NULL if unclassifed */
39 +               
40 +               /* the application layer data so far.  NULL if ->numpackets > numpackets */
41 +               char * app_data; 
42 +
43 +               unsigned int app_data_len;
44 +       } layer7;
45 +#endif
46  };
47  
48  /* get master conntrack via master expectation */
49 diff -Nurp linux-2.4.30/include/linux/netfilter_ipv4/ipt_layer7.h linux-2.4.30-layer7/include/linux/netfilter_ipv4/ipt_layer7.h
50 --- linux-2.4.30/include/linux/netfilter_ipv4/ipt_layer7.h      1969-12-31 18:00:00.000000000 -0600
51 +++ linux-2.4.30-layer7/include/linux/netfilter_ipv4/ipt_layer7.h       2005-05-03 18:37:03.000000000 -0500
52 @@ -0,0 +1,26 @@
53 +/* 
54 +  By Matthew Strait <quadong@users.sf.net>, Dec 2003.
55 +  http://l7-filter.sf.net
56 +
57 +  This program is free software; you can redistribute it and/or
58 +  modify it under the terms of the GNU General Public License
59 +  as published by the Free Software Foundation; either version
60 +  2 of the License, or (at your option) any later version.
61 +  http://www.gnu.org/licenses/gpl.txt
62 +*/
63 +
64 +#ifndef _IPT_LAYER7_H
65 +#define _IPT_LAYER7_H
66 +
67 +#define MAX_PATTERN_LEN 8192
68 +#define MAX_PROTOCOL_LEN 256
69 +
70 +typedef char *(*proc_ipt_search) (char *, char, char *);
71 +
72 +struct ipt_layer7_info {
73 +    char protocol[MAX_PROTOCOL_LEN];
74 +    char invert:1;
75 +    char pattern[MAX_PATTERN_LEN];
76 +};
77 +
78 +#endif /* _IPT_LAYER7_H */
79 diff -Nurp linux-2.4.30/net/ipv4/netfilter/Config.in linux-2.4.30-layer7/net/ipv4/netfilter/Config.in
80 --- linux-2.4.30/net/ipv4/netfilter/Config.in   2005-01-19 08:10:13.000000000 -0600
81 +++ linux-2.4.30-layer7/net/ipv4/netfilter/Config.in    2005-05-03 18:37:03.000000000 -0500
82 @@ -43,6 +43,10 @@ if [ "$CONFIG_IP_NF_IPTABLES" != "n" ]; 
83    if [ "$CONFIG_EXPERIMENTAL" = "y" ]; then
84      dep_tristate '  Unclean match support (EXPERIMENTAL)' CONFIG_IP_NF_MATCH_UNCLEAN $CONFIG_IP_NF_IPTABLES
85      dep_tristate '  Owner match support (EXPERIMENTAL)' CONFIG_IP_NF_MATCH_OWNER $CONFIG_IP_NF_IPTABLES
86 +    dep_tristate '  Layer 7 match support (EXPERIMENTAL)' CONFIG_IP_NF_MATCH_LAYER7 $CONFIG_IP_NF_CONNTRACK
87 +    dep_mbool '  Layer 7 debugging output (EXPERIMENTAL)' CONFIG_IP_NF_MATCH_LAYER7_DEBUG $CONFIG_IP_NF_MATCH_LAYER7
88 +    int  '  Buffer size for application layer data (256-65536)' CONFIG_IP_NF_MATCH_LAYER7_MAXDATALEN 2048
89
90    fi
91  # The targets
92    dep_tristate '  Packet filtering' CONFIG_IP_NF_FILTER $CONFIG_IP_NF_IPTABLES 
93 diff -Nurp linux-2.4.30/net/ipv4/netfilter/Makefile linux-2.4.30-layer7/net/ipv4/netfilter/Makefile
94 --- linux-2.4.30/net/ipv4/netfilter/Makefile    2003-08-25 06:44:44.000000000 -0500
95 +++ linux-2.4.30-layer7/net/ipv4/netfilter/Makefile     2005-05-03 18:44:12.000000000 -0500
96 @@ -86,6 +86,7 @@ obj-$(CONFIG_IP_NF_MATCH_STATE) += ipt_s
97  obj-$(CONFIG_IP_NF_MATCH_CONNTRACK) += ipt_conntrack.o
98  obj-$(CONFIG_IP_NF_MATCH_UNCLEAN) += ipt_unclean.o
99  obj-$(CONFIG_IP_NF_MATCH_TCPMSS) += ipt_tcpmss.o
100 +obj-$(CONFIG_IP_NF_MATCH_LAYER7) += ipt_layer7.o
101  
102  # targets
103  obj-$(CONFIG_IP_NF_TARGET_REJECT) += ipt_REJECT.o
104 diff -Nurp linux-2.4.30/net/ipv4/netfilter/ip_conntrack_core.c linux-2.4.30-layer7/net/ipv4/netfilter/ip_conntrack_core.c
105 --- linux-2.4.30/net/ipv4/netfilter/ip_conntrack_core.c 2005-04-03 20:42:20.000000000 -0500
106 +++ linux-2.4.30-layer7/net/ipv4/netfilter/ip_conntrack_core.c  2005-05-03 18:37:03.000000000 -0500
107 @@ -346,6 +346,14 @@ destroy_conntrack(struct nf_conntrack *n
108                 }
109                 kfree(ct->master);
110         }
111 +
112 +       #if defined(CONFIG_IP_NF_MATCH_LAYER7) || defined(CONFIG_IP_NF_MATCH_LAYER7_MODULE)
113 +       if(ct->layer7.app_proto)
114 +               kfree(ct->layer7.app_proto);
115 +       if(ct->layer7.app_data)
116 +               kfree(ct->layer7.app_data);
117 +       #endif
118 +       
119         WRITE_UNLOCK(&ip_conntrack_lock);
120  
121         if (master)
122 diff -Nurp linux-2.4.30/net/ipv4/netfilter/ip_conntrack_standalone.c linux-2.4.30-layer7/net/ipv4/netfilter/ip_conntrack_standalone.c
123 --- linux-2.4.30/net/ipv4/netfilter/ip_conntrack_standalone.c   2005-04-03 20:42:20.000000000 -0500
124 +++ linux-2.4.30-layer7/net/ipv4/netfilter/ip_conntrack_standalone.c    2005-05-03 18:37:03.000000000 -0500
125 @@ -107,6 +107,13 @@ print_conntrack(char *buffer, struct ip_
126                 len += sprintf(buffer + len, "[ASSURED] ");
127         len += sprintf(buffer + len, "use=%u ",
128                        atomic_read(&conntrack->ct_general.use));
129 +
130 +       #if defined(CONFIG_IP_NF_MATCH_LAYER7) || defined(CONFIG_IP_NF_MATCH_LAYER7_MODULE)
131 +       if(conntrack->layer7.app_proto)
132 +               len += sprintf(buffer + len, "l7proto=%s ",
133 +                               conntrack->layer7.app_proto); 
134 +       #endif
135 +
136         len += sprintf(buffer + len, "\n");
137  
138         return len;
139 diff -Nurp linux-2.4.30/net/ipv4/netfilter/ipt_layer7.c linux-2.4.30-layer7/net/ipv4/netfilter/ipt_layer7.c
140 --- linux-2.4.30/net/ipv4/netfilter/ipt_layer7.c        1969-12-31 18:00:00.000000000 -0600
141 +++ linux-2.4.30-layer7/net/ipv4/netfilter/ipt_layer7.c 2005-05-03 18:37:03.000000000 -0500
142 @@ -0,0 +1,557 @@
143 +/* 
144 +  Kernel module to match application layer (OSI layer 7) 
145 +  data in connections.
146 +  
147 +  http://l7-filter.sf.net
148 +
149 +  By Matthew Strait and Ethan Sommer, 2003-2005.
150 +
151 +  This program is free software; you can redistribute it and/or
152 +  modify it under the terms of the GNU General Public License
153 +  as published by the Free Software Foundation; either version
154 +  2 of the License, or (at your option) any later version.
155 +  http://www.gnu.org/licenses/gpl.txt
156 +
157 +  Based on ipt_string.c (C) 2000 Emmanuel Roger <winfield@freegates.be>
158 +  and cls_layer7.c (C) 2003 Matthew Strait, Ethan Sommer, Justin Levandoski
159 +*/
160 +
161 +#include <linux/module.h>
162 +#include <linux/skbuff.h>
163 +#include <linux/netfilter_ipv4/ip_conntrack.h>
164 +#include <linux/proc_fs.h>
165 +#include <linux/ctype.h>
166 +#include <net/ip.h>
167 +#include <net/tcp.h>
168 +#include <linux/netfilter_ipv4/lockhelp.h>
169 +
170 +#include "regexp/regexp.c"
171 +
172 +#include <linux/netfilter_ipv4/ipt_layer7.h>
173 +#include <linux/netfilter_ipv4/ip_tables.h>
174 +
175 +MODULE_AUTHOR("Matthew Strait <quadong@users.sf.net>, Ethan Sommer <sommere@users.sf.net>");
176 +MODULE_LICENSE("GPL");
177 +MODULE_DESCRIPTION("iptables application layer match module");
178 +
179 +#if defined(CONFIG_IP_NF_MATCH_LAYER7_DEBUG)
180 +       #define DPRINTK(format,args...) printk(format,##args)
181 +#else
182 +       #define DPRINTK(format,args...)
183 +#endif
184 +
185 +#define TOTAL_PACKETS master_conntrack->layer7.numpackets
186 +
187 +/* Number of packets whose data we look at.
188 +This can be modified through /proc/net/layer7_numpackets */
189 +static int num_packets = 8;
190 +
191 +static struct pattern_cache {
192 +       char * regex_string;
193 +       regexp * pattern;
194 +       struct pattern_cache * next;
195 +} * first_pattern_cache = NULL;
196 +
197 +/* I'm new to locking.  Here are my assumptions:
198 +
199 +- No one will write to /proc/net/layer7_numpackets over and over very fast; 
200 +  if they did, nothing awful would happen.
201 +
202 +- This code will never be processing the same packet twice at the same time,
203 +  because iptables rules are traversed in order.
204 +
205 +- It doesn't matter if two packets from different connections are in here at 
206 +  the same time, because they don't share any data.
207 +
208 +- It _does_ matter if two packets from the same connection are here at the same
209 +  time.  In this case, we have to protect the conntracks and the list of 
210 +  compiled patterns.
211 +*/
212 +DECLARE_RWLOCK(ct_lock);
213 +DECLARE_LOCK(list_lock);
214 +
215 +#if CONFIG_IP_NF_MATCH_LAYER7_DEBUG
216 +/* Converts an unfriendly string into a friendly one by 
217 +replacing unprintables with periods and all whitespace with " ". */
218 +static char * friendly_print(unsigned char * s)
219 +{
220 +       char * f = kmalloc(strlen(s) + 1, GFP_ATOMIC);
221 +       int i;
222 +
223 +       if(!f) {
224 +               if (net_ratelimit()) 
225 +                       printk(KERN_ERR "layer7: out of memory in friendly_print, bailing.\n");
226 +               return NULL;
227 +       }
228 +
229 +       for(i = 0; i < strlen(s); i++){
230 +               if(isprint(s[i]) && s[i] < 128) f[i] = s[i];
231 +               else if(isspace(s[i]))          f[i] = ' ';
232 +               else                            f[i] = '.';
233 +       }
234 +       f[i] = '\0';
235 +       return f;
236 +}
237 +
238 +static char dec2hex(int i)
239 +{
240 +       switch (i) {
241 +               case 0 ... 9:
242 +                       return (char)(i + '0');
243 +                       break;
244 +               case 10 ... 15:
245 +                       return (char)(i - 10 + 'a');
246 +                       break;
247 +               default:
248 +                       if (net_ratelimit()) 
249 +                               printk("Problem in dec2hex\n");
250 +                       return '\0';
251 +       }
252 +}
253 +
254 +static char * hex_print(unsigned char * s)
255 +{
256 +       char * g = kmalloc(strlen(s)*3 + 1, GFP_ATOMIC);
257 +       int i;
258 +
259 +       if(!g) {
260 +               if (net_ratelimit()) 
261 +                       printk(KERN_ERR "layer7: out of memory in hex_print, bailing.\n");
262 +               return NULL;
263 +       }
264 +
265 +       for(i = 0; i < strlen(s); i++) {
266 +               g[i*3    ] = dec2hex(s[i]/16);
267 +               g[i*3 + 1] = dec2hex(s[i]%16);
268 +               g[i*3 + 2] = ' ';
269 +       }
270 +       g[i*3] = '\0';
271 +
272 +       return g;
273 +}
274 +#endif // DEBUG
275 +
276 +/* Use instead of regcomp.  As we expect to be seeing the same regexps over and
277 +over again, it make sense to cache the results. */
278 +static regexp * compile_and_cache(char * regex_string, char * protocol) 
279 +{
280 +       struct pattern_cache * node               = first_pattern_cache;
281 +       struct pattern_cache * last_pattern_cache = first_pattern_cache;
282 +       struct pattern_cache * tmp;
283 +       unsigned int len;
284 +
285 +       while (node != NULL) {
286 +               if (!strcmp(node->regex_string, regex_string)) 
287 +                       return node->pattern;
288 +
289 +               last_pattern_cache = node;/* points at the last non-NULL node */
290 +               node = node->next;
291 +       }
292 +
293 +       /* If we reach the end of the list, then we have not yet cached
294 +          the pattern for this regex. Let's do that now. 
295 +          Be paranoid about running out of memory to avoid list corruption. */
296 +       tmp = kmalloc(sizeof(struct pattern_cache), GFP_ATOMIC);
297 +
298 +       if(!tmp) {
299 +               if (net_ratelimit()) 
300 +                       printk(KERN_ERR "layer7: out of memory in compile_and_cache, bailing.\n");
301 +               return NULL;
302 +       }
303 +
304 +       tmp->regex_string  = kmalloc(strlen(regex_string) + 1, GFP_ATOMIC);
305 +       tmp->pattern       = kmalloc(sizeof(struct regexp),    GFP_ATOMIC);
306 +       tmp->next = NULL;
307 +
308 +       if(!tmp->regex_string || !tmp->pattern) {
309 +               if (net_ratelimit()) 
310 +                       printk(KERN_ERR "layer7: out of memory in compile_and_cache, bailing.\n");
311 +               kfree(tmp->regex_string);
312 +               kfree(tmp->pattern);
313 +               kfree(tmp);
314 +               return NULL;
315 +       }
316 +
317 +       /* Ok.  The new node is all ready now. */
318 +       node = tmp;
319 +
320 +       if(first_pattern_cache == NULL) /* list is empty */
321 +               first_pattern_cache = node; /* make node the beginning */
322 +       else
323 +               last_pattern_cache->next = node; /* attach node to the end */
324 +
325 +       /* copy the string and compile the regex */
326 +       len = strlen(regex_string);
327 +       DPRINTK("About to compile this: \"%s\"\n", regex_string);
328 +       node->pattern = regcomp(regex_string, &len);
329 +       if ( !node->pattern ) {
330 +               if (net_ratelimit()) 
331 +                       printk(KERN_ERR "layer7: Error compiling regexp \"%s\" (%s)\n", regex_string, protocol);
332 +               /* pattern is now cached as NULL, so we won't try again. */
333 +       }
334 +
335 +       strcpy(node->regex_string, regex_string);
336 +       return node->pattern;
337 +}
338 +
339 +static int can_handle(const struct sk_buff *skb)
340 +{
341 +       if(!skb->nh.iph) /* not IP */
342 +               return 0;
343 +       if(skb->nh.iph->protocol != IPPROTO_TCP &&
344 +          skb->nh.iph->protocol != IPPROTO_UDP &&
345 +          skb->nh.iph->protocol != IPPROTO_ICMP)
346 +               return 0;
347 +       return 1;
348 +}
349 +
350 +/* Returns offset the into the skb->data that the application data starts */
351 +static int app_data_offset(const struct sk_buff *skb)
352 +{
353 +       /* In case we are ported somewhere (ebtables?) where skb->nh.iph 
354 +       isn't set, this can be gotten from 4*(skb->data[0] & 0x0f) as well. */
355 +       int ip_hl = 4*skb->nh.iph->ihl;
356 +
357 +       if( skb->nh.iph->protocol == IPPROTO_TCP ) {
358 +               /* 12 == offset into TCP header for the header length field. 
359 +               Can't get this with skb->h.th->doff because the tcphdr 
360 +               struct doesn't get set when routing (this is confirmed to be 
361 +               true in Netfilter as well as QoS.) */
362 +               int tcp_hl = 4*(skb->data[ip_hl + 12] >> 4);
363 +
364 +               return ip_hl + tcp_hl;
365 +       } else if( skb->nh.iph->protocol == IPPROTO_UDP  ) {
366 +               return ip_hl + 8; /* UDP header is always 8 bytes */
367 +       } else if( skb->nh.iph->protocol == IPPROTO_ICMP ) {
368 +               return ip_hl + 8; /* ICMP header is 8 bytes */
369 +       } else {
370 +               if (net_ratelimit()) 
371 +                       printk(KERN_ERR "layer7: tried to handle unknown protocol!\n");
372 +               return ip_hl + 8; /* something reasonable */
373 +       }
374 +}
375 +
376 +/* handles whether there's a match when we aren't appending data anymore */
377 +static int match_no_append(struct ip_conntrack * conntrack, struct ip_conntrack * master_conntrack,
378 +                       enum ip_conntrack_info ctinfo, enum ip_conntrack_info master_ctinfo,
379 +                       struct ipt_layer7_info * info)
380 +{
381 +       /* If we're in here, throw the app data away */
382 +       WRITE_LOCK(&ct_lock);
383 +       if(master_conntrack->layer7.app_data != NULL) {
384 +
385 +       #ifdef CONFIG_IP_NF_MATCH_LAYER7_DEBUG
386 +               if(!master_conntrack->layer7.app_proto) {
387 +                       char * f = friendly_print(master_conntrack->layer7.app_data);
388 +                       char * g = hex_print(master_conntrack->layer7.app_data);
389 +                       DPRINTK("\nl7-filter gave up after %d bytes (%d packets):\n%s\n",
390 +                               strlen(f), 
391 +                               TOTAL_PACKETS, f);
392 +                       kfree(f); 
393 +                       DPRINTK("In hex: %s\n", g);
394 +                       kfree(g);
395 +               }
396 +       #endif
397 +
398 +               kfree(master_conntrack->layer7.app_data);
399 +               master_conntrack->layer7.app_data = NULL; /* don't free again */
400 +       }
401 +       WRITE_UNLOCK(&ct_lock);
402 +
403 +       if(master_conntrack->layer7.app_proto){
404 +               /* Here child connections set their .app_proto (for /proc/net/ip_conntrack) */
405 +               WRITE_LOCK(&ct_lock);
406 +               if(!conntrack->layer7.app_proto) {
407 +                       conntrack->layer7.app_proto = kmalloc(strlen(master_conntrack->layer7.app_proto)+1, GFP_ATOMIC);
408 +                       if(!conntrack->layer7.app_proto){
409 +                               if (net_ratelimit()) 
410 +                                       printk(KERN_ERR "layer7: out of memory in match_no_append, bailing.\n");
411 +                               WRITE_UNLOCK(&ct_lock);
412 +                               return 1;
413 +                       }
414 +                       strcpy(conntrack->layer7.app_proto, master_conntrack->layer7.app_proto);
415 +               }
416 +               WRITE_UNLOCK(&ct_lock);
417 +       
418 +               return (!strcmp(master_conntrack->layer7.app_proto, info->protocol));
419 +       }
420 +       else {
421 +               /* If not classified, set to "unknown" to distinguish from 
422 +               connections that are still being tested. */
423 +               WRITE_LOCK(&ct_lock);
424 +               master_conntrack->layer7.app_proto = kmalloc(strlen("unknown")+1, GFP_ATOMIC);
425 +               if(!master_conntrack->layer7.app_proto){
426 +                       if (net_ratelimit()) 
427 +                               printk(KERN_ERR "layer7: out of memory in match_no_append, bailing.\n");
428 +                       WRITE_UNLOCK(&ct_lock);
429 +                       return 1;
430 +               }
431 +               strcpy(master_conntrack->layer7.app_proto, "unknown");
432 +               WRITE_UNLOCK(&ct_lock);
433 +               return 0;
434 +       }
435 +}
436 +
437 +/* add the new app data to the conntrack.  Return number of bytes added. */
438 +static int add_data(struct ip_conntrack * master_conntrack, 
439 +                       char * app_data, int appdatalen)
440 +{
441 +       int length = 0, i;
442 +       int oldlength = master_conntrack->layer7.app_data_len;
443 +
444 +       /* Strip nulls. Make everything lower case (our regex lib doesn't
445 +       do case insensitivity).  Add it to the end of the current data. */
446 +       for(i = 0; i < CONFIG_IP_NF_MATCH_LAYER7_MAXDATALEN-oldlength-1 && 
447 +                  i < appdatalen; i++) {
448 +               if(app_data[i] != '\0') {
449 +                       master_conntrack->layer7.app_data[length+oldlength] = 
450 +                               /* the kernel version of tolower mungs 'upper ascii' */
451 +                               isascii(app_data[i])? tolower(app_data[i]) : app_data[i];
452 +                       length++;
453 +               }
454 +       }
455 +
456 +       master_conntrack->layer7.app_data[length+oldlength] = '\0';
457 +       master_conntrack->layer7.app_data_len = length + oldlength;
458 +
459 +       return length;
460 +}
461 +
462 +/* Returns true on match and false otherwise.  */
463 +static int match(/* const */struct sk_buff *skb, const struct net_device *in,
464 +                const struct net_device *out, const void *matchinfo,
465 +                int offset,               int *hotdrop)
466 +{
467 +       struct ipt_layer7_info * info = (struct ipt_layer7_info *)matchinfo;
468 +       enum ip_conntrack_info master_ctinfo, ctinfo;
469 +       struct ip_conntrack *master_conntrack, *conntrack;
470 +       unsigned char * app_data;  
471 +       unsigned int pattern_result, appdatalen;
472 +       regexp * comppattern;
473 +
474 +       if(!can_handle(skb)){
475 +               DPRINTK("layer7: This is some protocol I can't handle.\n");
476 +               return info->invert;
477 +       }
478 +
479 +       /* Treat the parent and all its children together as one connection, 
480 +       except for the purpose of setting conntrack->layer7.app_proto in the 
481 +       actual connection. This makes /proc/net/ip_conntrack somewhat more 
482 +       satisfying. */
483 +       if(!(conntrack  = ip_conntrack_get((struct sk_buff *)skb, &ctinfo)) ||
484 +          !(master_conntrack = ip_conntrack_get((struct sk_buff *)skb, &master_ctinfo))) {
485 +               DPRINTK("layer7: packet is not from a known connection, giving up.\n");
486 +               return info->invert;
487 +       }
488 +       
489 +       /* Try to get a master conntrack (and its master etc) for FTP, etc. */
490 +       while (master_ct(master_conntrack) != NULL)
491 +               master_conntrack = master_ct(master_conntrack);
492 +
493 +       if(!skb->cb[0]){
494 +               WRITE_LOCK(&ct_lock);
495 +               master_conntrack->layer7.numpackets++;/*starts at 0 via memset*/
496 +               WRITE_UNLOCK(&ct_lock);
497 +       }
498 +
499 +       /* if we've classified it or seen too many packets */
500 +       if(TOTAL_PACKETS > num_packets || 
501 +          master_conntrack->layer7.app_proto) {
502 +       
503 +               pattern_result = match_no_append(conntrack, master_conntrack, ctinfo, master_ctinfo, info);
504 +       
505 +               /* skb->cb[0] == seen. Avoid doing things twice if there are two l7 
506 +               rules. I'm not sure that using cb for this purpose is correct, although
507 +               it says "put your private variables there". But it doesn't look like it
508 +               is being used for anything else in the skbs that make it here. How can
509 +               I write to cb without making the compiler angry? */
510 +               skb->cb[0] = 1; /* marking it seen here is probably irrelevant, but consistant */
511 +
512 +               return (pattern_result ^ info->invert);
513 +       }
514 +
515 +       if(skb_is_nonlinear(skb)){
516 +               if(skb_linearize(skb, GFP_ATOMIC) != 0){
517 +                       if (net_ratelimit()) 
518 +                               printk(KERN_ERR "layer7: failed to linearize packet, bailing.\n");
519 +                       return info->invert;
520 +               }
521 +       }
522 +       
523 +       /* now that the skb is linearized, it's safe to set these. */
524 +       app_data = skb->data + app_data_offset(skb);
525 +       appdatalen = skb->tail - app_data;
526 +
527 +       LOCK_BH(&list_lock);
528 +       /* the return value gets checked later, when we're ready to use it */
529 +       comppattern = compile_and_cache(info->pattern, info->protocol);
530 +       UNLOCK_BH(&list_lock);
531 +
532 +       /* On the first packet of a connection, allocate space for app data */
533 +       WRITE_LOCK(&ct_lock);
534 +       if(TOTAL_PACKETS == 1 && !skb->cb[0] && !master_conntrack->layer7.app_data) {
535 +               master_conntrack->layer7.app_data = kmalloc(CONFIG_IP_NF_MATCH_LAYER7_MAXDATALEN, GFP_ATOMIC);
536 +               if(!master_conntrack->layer7.app_data){
537 +                       if (net_ratelimit())
538 +                               printk(KERN_ERR "layer7: out of memory in match, bailing.\n");
539 +                       WRITE_UNLOCK(&ct_lock);
540 +                       return info->invert;
541 +               }
542 +
543 +               master_conntrack->layer7.app_data[0] = '\0';
544 +       }
545 +       WRITE_UNLOCK(&ct_lock);
546 +
547 +       /* Can be here, but unallocated, if numpackets is increased near 
548 +       the beginning of a connection */
549 +       if(master_conntrack->layer7.app_data == NULL)
550 +               return (info->invert); /* unmatched */
551 +
552 +       if(!skb->cb[0]){
553 +               int newbytes;
554 +               WRITE_LOCK(&ct_lock);
555 +               newbytes = add_data(master_conntrack, app_data, appdatalen);
556 +               WRITE_UNLOCK(&ct_lock);
557 +
558 +               if(newbytes == 0) { /* didn't add any data */
559 +                       skb->cb[0] = 1;
560 +                       /* Didn't match before, not going to match now */
561 +                       return info->invert;
562 +               }
563 +       }
564 +
565 +       /* If looking for "unknown", then never match.  "Unknown" means that
566 +       we've given up; we're still trying with these packets. */
567 +       if(!strcmp(info->protocol, "unknown")) {
568 +               pattern_result = 0;
569 +       /* If the regexp failed to compile, don't bother running it */
570 +       } else if(comppattern && regexec(comppattern, master_conntrack->layer7.app_data)) {
571 +               DPRINTK("layer7: regexec positive: %s!\n", info->protocol);
572 +               pattern_result = 1;
573 +       } else pattern_result = 0;
574 +
575 +       if(pattern_result) {
576 +               WRITE_LOCK(&ct_lock);
577 +               master_conntrack->layer7.app_proto = kmalloc(strlen(info->protocol)+1, GFP_ATOMIC);
578 +               if(!master_conntrack->layer7.app_proto){
579 +                       if (net_ratelimit()) 
580 +                               printk(KERN_ERR "layer7: out of memory in match, bailing.\n");
581 +                       WRITE_UNLOCK(&ct_lock);
582 +                       return (pattern_result ^ info->invert);
583 +               }
584 +               strcpy(master_conntrack->layer7.app_proto, info->protocol);
585 +               WRITE_UNLOCK(&ct_lock);
586 +       }
587 +
588 +       /* mark the packet seen */
589 +       skb->cb[0] = 1;
590 +
591 +       return (pattern_result ^ info->invert);
592 +}
593 +
594 +static int checkentry(const char *tablename, const struct ipt_ip *ip,
595 +          void *matchinfo, unsigned int matchsize, unsigned int hook_mask)
596 +{
597 +       if (matchsize != IPT_ALIGN(sizeof(struct ipt_layer7_info))) 
598 +               return 0;
599 +       return 1;
600 +}
601 +
602 +static struct ipt_match layer7_match = { 
603 +       .name = "layer7", 
604 +       .match = &match, 
605 +       .checkentry = &checkentry, 
606 +       .me = THIS_MODULE 
607 +};
608 +
609 +/* taken from drivers/video/modedb.c */
610 +static int my_atoi(const char *s)
611 +{
612 +       int val = 0;
613 +
614 +       for (;; s++) {
615 +               switch (*s) {
616 +               case '0'...'9':
617 +                       val = 10*val+(*s-'0');
618 +                       break;
619 +               default:
620 +                       return val;
621 +               }
622 +       }
623 +}
624 +
625 +/* write out num_packets to userland. */
626 +static int layer7_read_proc(char* page, char ** start, off_t off, int count, 
627 +                    int* eof, void * data) 
628 +{
629 +       if(num_packets > 99 && net_ratelimit()) 
630 +               printk(KERN_ERR "layer7: NOT REACHED. num_packets too big\n");
631 +       
632 +       page[0] = num_packets/10 + '0';
633 +       page[1] = num_packets%10 + '0';
634 +       page[2] = '\n';
635 +       page[3] = '\0';
636 +               
637 +       *eof=1;
638 +
639 +       return 3;
640 +}
641 +
642 +/* Read in num_packets from userland */
643 +static int layer7_write_proc(struct file* file, const char* buffer, 
644 +                     unsigned long count, void *data) 
645 +{
646 +       char * foo = kmalloc(count, GFP_ATOMIC);
647 +
648 +       if(!foo){
649 +               if (net_ratelimit()) 
650 +                       printk(KERN_ERR "layer7: out of memory, bailing. num_packets unchanged.\n");
651 +               return count;
652 +       }
653 +
654 +       copy_from_user(foo, buffer, count);
655 +
656 +       num_packets = my_atoi(foo);
657 +       kfree (foo);
658 +
659 +       /* This has an arbitrary limit to make the math easier. I'm lazy. 
660 +       But anyway, 99 is a LOT! If you want more, you're doing it wrong! */
661 +       if(num_packets > 99) {
662 +               printk(KERN_WARNING "layer7: num_packets can't be > 99.\n");
663 +               num_packets = 99;
664 +       } else if(num_packets < 1) {
665 +               printk(KERN_WARNING "layer7: num_packets can't be < 1.\n");
666 +               num_packets = 1;
667 +       }
668 +       
669 +       return count;
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, proc_net);
677 +       entry->read_proc = layer7_read_proc;
678 +       entry->write_proc = layer7_write_proc;
679 +}
680 +
681 +static void layer7_cleanup_proc(void)
682 +{
683 +       remove_proc_entry("layer7_numpackets", proc_net);
684 +}
685 +
686 +static int __init init(void)
687 +{
688 +       layer7_init_proc();
689 +       return ipt_register_match(&layer7_match);
690 +}
691 +
692 +static void __exit fini(void)
693 +{
694 +       layer7_cleanup_proc();
695 +       ipt_unregister_match(&layer7_match);
696 +}
697 +
698 +module_init(init);
699 +module_exit(fini);
700 diff -Nurp linux-2.4.30/net/ipv4/netfilter/regexp/regexp.c linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regexp.c
701 --- linux-2.4.30/net/ipv4/netfilter/regexp/regexp.c     1969-12-31 18:00:00.000000000 -0600
702 +++ linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regexp.c      2005-05-03 18:37:03.000000000 -0500
703 @@ -0,0 +1,1195 @@
704 +/*
705 + * regcomp and regexec -- regsub and regerror are elsewhere
706 + * @(#)regexp.c        1.3 of 18 April 87
707 + *
708 + *     Copyright (c) 1986 by University of Toronto.
709 + *     Written by Henry Spencer.  Not derived from licensed software.
710 + *
711 + *     Permission is granted to anyone to use this software for any
712 + *     purpose on any computer system, and to redistribute it freely,
713 + *     subject to the following restrictions:
714 + *
715 + *     1. The author is not responsible for the consequences of use of
716 + *             this software, no matter how awful, even if they arise
717 + *             from defects in it.
718 + *
719 + *     2. The origin of this software must not be misrepresented, either
720 + *             by explicit claim or by omission.
721 + *
722 + *     3. Altered versions must be plainly marked as such, and must not
723 + *             be misrepresented as being the original software.
724 + *
725 + * Beware that some of this code is subtly aware of the way operator
726 + * precedence is structured in regular expressions.  Serious changes in
727 + * regular-expression syntax might require a total rethink.
728 + *
729 + * This code was modified by Ethan Sommer to work within the kernel
730 + * (it now uses kmalloc etc..)
731 + * 
732 + * Modified slightly by Matthew Strait to use more modern C.
733 + */
734 +
735 +#include "regexp.h"
736 +#include "regmagic.h"
737 +
738 +/* added by ethan and matt.  Lets it work in both kernel and user space.
739 +(So iptables can use it, for instance.)  Yea, it goes both ways... */
740 +#if __KERNEL__
741 +  #define malloc(foo) kmalloc(foo,GFP_ATOMIC)
742 +#else
743 +  #define printk(format,args...) printf(format,##args)
744 +#endif
745 +
746 +void regerror(char * s)
747 +{
748 +        printk("<3>Regexp: %s\n", s);
749 +        /* NOTREACHED */
750 +}
751 +
752 +/*
753 + * The "internal use only" fields in regexp.h are present to pass info from
754 + * compile to execute that permits the execute phase to run lots faster on
755 + * simple cases.  They are:
756 + *
757 + * regstart    char that must begin a match; '\0' if none obvious
758 + * reganch     is the match anchored (at beginning-of-line only)?
759 + * regmust     string (pointer into program) that match must include, or NULL
760 + * regmlen     length of regmust string
761 + *
762 + * Regstart and reganch permit very fast decisions on suitable starting points
763 + * for a match, cutting down the work a lot.  Regmust permits fast rejection
764 + * of lines that cannot possibly match.  The regmust tests are costly enough
765 + * that regcomp() supplies a regmust only if the r.e. contains something
766 + * potentially expensive (at present, the only such thing detected is * or +
767 + * at the start of the r.e., which can involve a lot of backup).  Regmlen is
768 + * supplied because the test in regexec() needs it and regcomp() is computing
769 + * it anyway.
770 + */
771 +
772 +/*
773 + * Structure for regexp "program".  This is essentially a linear encoding
774 + * of a nondeterministic finite-state machine (aka syntax charts or
775 + * "railroad normal form" in parsing technology).  Each node is an opcode
776 + * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
777 + * all nodes except BRANCH implement concatenation; a "next" pointer with
778 + * a BRANCH on both ends of it is connecting two alternatives.  (Here we
779 + * have one of the subtle syntax dependencies:  an individual BRANCH (as
780 + * opposed to a collection of them) is never concatenated with anything
781 + * because of operator precedence.)  The operand of some types of node is
782 + * a literal string; for others, it is a node leading into a sub-FSM.  In
783 + * particular, the operand of a BRANCH node is the first node of the branch.
784 + * (NB this is *not* a tree structure:  the tail of the branch connects
785 + * to the thing following the set of BRANCHes.)  The opcodes are:
786 + */
787 +
788 +/* definition  number  opnd?   meaning */
789 +#define        END     0       /* no   End of program. */
790 +#define        BOL     1       /* no   Match "" at beginning of line. */
791 +#define        EOL     2       /* no   Match "" at end of line. */
792 +#define        ANY     3       /* no   Match any one character. */
793 +#define        ANYOF   4       /* str  Match any character in this string. */
794 +#define        ANYBUT  5       /* str  Match any character not in this string. */
795 +#define        BRANCH  6       /* node Match this alternative, or the next... */
796 +#define        BACK    7       /* no   Match "", "next" ptr points backward. */
797 +#define        EXACTLY 8       /* str  Match this string. */
798 +#define        NOTHING 9       /* no   Match empty string. */
799 +#define        STAR    10      /* node Match this (simple) thing 0 or more times. */
800 +#define        PLUS    11      /* node Match this (simple) thing 1 or more times. */
801 +#define        OPEN    20      /* no   Mark this point in input as start of #n. */
802 +                       /*      OPEN+1 is number 1, etc. */
803 +#define        CLOSE   30      /* no   Analogous to OPEN. */
804 +
805 +/*
806 + * Opcode notes:
807 + *
808 + * BRANCH      The set of branches constituting a single choice are hooked
809 + *             together with their "next" pointers, since precedence prevents
810 + *             anything being concatenated to any individual branch.  The
811 + *             "next" pointer of the last BRANCH in a choice points to the
812 + *             thing following the whole choice.  This is also where the
813 + *             final "next" pointer of each individual branch points; each
814 + *             branch starts with the operand node of a BRANCH node.
815 + *
816 + * BACK                Normal "next" pointers all implicitly point forward; BACK
817 + *             exists to make loop structures possible.
818 + *
819 + * STAR,PLUS   '?', and complex '*' and '+', are implemented as circular
820 + *             BRANCH structures using BACK.  Simple cases (one character
821 + *             per match) are implemented with STAR and PLUS for speed
822 + *             and to minimize recursive plunges.
823 + *
824 + * OPEN,CLOSE  ...are numbered at compile time.
825 + */
826 +
827 +/*
828 + * A node is one char of opcode followed by two chars of "next" pointer.
829 + * "Next" pointers are stored as two 8-bit pieces, high order first.  The
830 + * value is a positive offset from the opcode of the node containing it.
831 + * An operand, if any, simply follows the node.  (Note that much of the
832 + * code generation knows about this implicit relationship.)
833 + *
834 + * Using two bytes for the "next" pointer is vast overkill for most things,
835 + * but allows patterns to get big without disasters.
836 + */
837 +#define        OP(p)   (*(p))
838 +#define        NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
839 +#define        OPERAND(p)      ((p) + 3)
840 +
841 +/*
842 + * See regmagic.h for one further detail of program structure.
843 + */
844 +
845 +
846 +/*
847 + * Utility definitions.
848 + */
849 +#ifndef CHARBITS
850 +#define        UCHARAT(p)      ((int)*(unsigned char *)(p))
851 +#else
852 +#define        UCHARAT(p)      ((int)*(p)&CHARBITS)
853 +#endif
854 +
855 +#define        FAIL(m) { regerror(m); return(NULL); }
856 +#define        ISMULT(c)       ((c) == '*' || (c) == '+' || (c) == '?')
857 +#define        META    "^$.[()|?+*\\"
858 +
859 +/*
860 + * Flags to be passed up and down.
861 + */
862 +#define        HASWIDTH        01      /* Known never to match null string. */
863 +#define        SIMPLE          02      /* Simple enough to be STAR/PLUS operand. */
864 +#define        SPSTART         04      /* Starts with * or +. */
865 +#define        WORST           0       /* Worst case. */
866 +
867 +/*
868 + * Global work variables for regcomp().
869 + */
870 +static char *regparse;         /* Input-scan pointer. */
871 +static int regnpar;            /* () count. */
872 +static char regdummy;
873 +static char *regcode;          /* Code-emit pointer; &regdummy = don't. */
874 +static long regsize;           /* Code size. */
875 +
876 +/*
877 + * Forward declarations for regcomp()'s friends.
878 + */
879 +#ifndef STATIC
880 +#define        STATIC  static
881 +#endif
882 +STATIC char *reg(int paren,int *flagp);
883 +STATIC char *regbranch(int *flagp);
884 +STATIC char *regpiece(int *flagp);
885 +STATIC char *regatom(int *flagp);
886 +STATIC char *regnode(char op);
887 +STATIC char *regnext(char *p);
888 +STATIC void regc(char b);
889 +STATIC void reginsert(char op, char *opnd);
890 +STATIC void regtail(char *p, char *val);
891 +STATIC void regoptail(char *p, char *val);
892 +
893 +
894 +__kernel_size_t my_strcspn(const char *s1,const char *s2)
895 +{
896 +        char *scan1;
897 +        char *scan2;
898 +        int count;
899 +
900 +        count = 0;
901 +        for (scan1 = (char *)s1; *scan1 != '\0'; scan1++) {
902 +                for (scan2 = (char *)s2; *scan2 != '\0';)       /* ++ moved down. */
903 +                        if (*scan1 == *scan2++)
904 +                                return(count);
905 +                count++;
906 +        }
907 +        return(count);
908 +}
909 +
910 +/*
911 + - regcomp - compile a regular expression into internal code
912 + *
913 + * We can't allocate space until we know how big the compiled form will be,
914 + * but we can't compile it (and thus know how big it is) until we've got a
915 + * place to put the code.  So we cheat:  we compile it twice, once with code
916 + * generation turned off and size counting turned on, and once "for real".
917 + * This also means that we don't allocate space until we are sure that the
918 + * thing really will compile successfully, and we never have to move the
919 + * code and thus invalidate pointers into it.  (Note that it has to be in
920 + * one piece because free() must be able to free it all.)
921 + *
922 + * Beware that the optimization-preparation code in here knows about some
923 + * of the structure of the compiled regexp.
924 + */
925 +regexp *
926 +regcomp(char *exp,int *patternsize)
927 +{
928 +       register regexp *r;
929 +       register char *scan;
930 +       register char *longest;
931 +       register int len;
932 +       int flags;
933 +       /* commented out by ethan
934 +          extern char *malloc();
935 +       */
936 +
937 +       if (exp == NULL)
938 +               FAIL("NULL argument");
939 +
940 +       /* First pass: determine size, legality. */
941 +       regparse = exp;
942 +       regnpar = 1;
943 +       regsize = 0L;
944 +       regcode = &regdummy;
945 +       regc(MAGIC);
946 +       if (reg(0, &flags) == NULL)
947 +               return(NULL);
948 +
949 +       /* Small enough for pointer-storage convention? */
950 +       if (regsize >= 32767L)          /* Probably could be 65535L. */
951 +               FAIL("regexp too big");
952 +
953 +       /* Allocate space. */
954 +       *patternsize=sizeof(regexp) + (unsigned)regsize;
955 +       r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
956 +       if (r == NULL)
957 +               FAIL("out of space");
958 +
959 +       /* Second pass: emit code. */
960 +       regparse = exp;
961 +       regnpar = 1;
962 +       regcode = r->program;
963 +       regc(MAGIC);
964 +       if (reg(0, &flags) == NULL)
965 +               return(NULL);
966 +
967 +       /* Dig out information for optimizations. */
968 +       r->regstart = '\0';     /* Worst-case defaults. */
969 +       r->reganch = 0;
970 +       r->regmust = NULL;
971 +       r->regmlen = 0;
972 +       scan = r->program+1;                    /* First BRANCH. */
973 +       if (OP(regnext(scan)) == END) {         /* Only one top-level choice. */
974 +               scan = OPERAND(scan);
975 +
976 +               /* Starting-point info. */
977 +               if (OP(scan) == EXACTLY)
978 +                       r->regstart = *OPERAND(scan);
979 +               else if (OP(scan) == BOL)
980 +                       r->reganch++;
981 +
982 +               /*
983 +                * If there's something expensive in the r.e., find the
984 +                * longest literal string that must appear and make it the
985 +                * regmust.  Resolve ties in favor of later strings, since
986 +                * the regstart check works with the beginning of the r.e.
987 +                * and avoiding duplication strengthens checking.  Not a
988 +                * strong reason, but sufficient in the absence of others.
989 +                */
990 +               if (flags&SPSTART) {
991 +                       longest = NULL;
992 +                       len = 0;
993 +                       for (; scan != NULL; scan = regnext(scan))
994 +                               if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
995 +                                       longest = OPERAND(scan);
996 +                                       len = strlen(OPERAND(scan));
997 +                               }
998 +                       r->regmust = longest;
999 +                       r->regmlen = len;
1000 +               }
1001 +       }
1002 +
1003 +       return(r);
1004 +}
1005 +
1006 +/*
1007 + - reg - regular expression, i.e. main body or parenthesized thing
1008 + *
1009 + * Caller must absorb opening parenthesis.
1010 + *
1011 + * Combining parenthesis handling with the base level of regular expression
1012 + * is a trifle forced, but the need to tie the tails of the branches to what
1013 + * follows makes it hard to avoid.
1014 + */
1015 +static char *
1016 +reg(int paren, int *flagp /* Parenthesized? */ )
1017 +{
1018 +       register char *ret;
1019 +       register char *br;
1020 +       register char *ender;
1021 +       register int parno = 0; /* 0 makes gcc happy */
1022 +       int flags;
1023 +
1024 +       *flagp = HASWIDTH;      /* Tentatively. */
1025 +
1026 +       /* Make an OPEN node, if parenthesized. */
1027 +       if (paren) {
1028 +               if (regnpar >= NSUBEXP)
1029 +                       FAIL("too many ()");
1030 +               parno = regnpar;
1031 +               regnpar++;
1032 +               ret = regnode(OPEN+parno);
1033 +       } else
1034 +               ret = NULL;
1035 +
1036 +       /* Pick up the branches, linking them together. */
1037 +       br = regbranch(&flags);
1038 +       if (br == NULL)
1039 +               return(NULL);
1040 +       if (ret != NULL)
1041 +               regtail(ret, br);       /* OPEN -> first. */
1042 +       else
1043 +               ret = br;
1044 +       if (!(flags&HASWIDTH))
1045 +               *flagp &= ~HASWIDTH;
1046 +       *flagp |= flags&SPSTART;
1047 +       while (*regparse == '|') {
1048 +               regparse++;
1049 +               br = regbranch(&flags);
1050 +               if (br == NULL)
1051 +                       return(NULL);
1052 +               regtail(ret, br);       /* BRANCH -> BRANCH. */
1053 +               if (!(flags&HASWIDTH))
1054 +                       *flagp &= ~HASWIDTH;
1055 +               *flagp |= flags&SPSTART;
1056 +       }
1057 +
1058 +       /* Make a closing node, and hook it on the end. */
1059 +       ender = regnode((paren) ? CLOSE+parno : END);   
1060 +       regtail(ret, ender);
1061 +
1062 +       /* Hook the tails of the branches to the closing node. */
1063 +       for (br = ret; br != NULL; br = regnext(br))
1064 +               regoptail(br, ender);
1065 +
1066 +       /* Check for proper termination. */
1067 +       if (paren && *regparse++ != ')') {
1068 +               FAIL("unmatched ()");
1069 +       } else if (!paren && *regparse != '\0') {
1070 +               if (*regparse == ')') {
1071 +                       FAIL("unmatched ()");
1072 +               } else
1073 +                       FAIL("junk on end");    /* "Can't happen". */
1074 +               /* NOTREACHED */
1075 +       }
1076 +
1077 +       return(ret);
1078 +}
1079 +
1080 +/*
1081 + - regbranch - one alternative of an | operator
1082 + *
1083 + * Implements the concatenation operator.
1084 + */
1085 +static char *
1086 +regbranch(int *flagp)
1087 +{
1088 +       register char *ret;
1089 +       register char *chain;
1090 +       register char *latest;
1091 +       int flags;
1092 +
1093 +       *flagp = WORST;         /* Tentatively. */
1094 +
1095 +       ret = regnode(BRANCH);
1096 +       chain = NULL;
1097 +       while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
1098 +               latest = regpiece(&flags);
1099 +               if (latest == NULL)
1100 +                       return(NULL);
1101 +               *flagp |= flags&HASWIDTH;
1102 +               if (chain == NULL)      /* First piece. */
1103 +                       *flagp |= flags&SPSTART;
1104 +               else
1105 +                       regtail(chain, latest);
1106 +               chain = latest;
1107 +       }
1108 +       if (chain == NULL)      /* Loop ran zero times. */
1109 +               (void) regnode(NOTHING);
1110 +
1111 +       return(ret);
1112 +}
1113 +
1114 +/*
1115 + - regpiece - something followed by possible [*+?]
1116 + *
1117 + * Note that the branching code sequences used for ? and the general cases
1118 + * of * and + are somewhat optimized:  they use the same NOTHING node as
1119 + * both the endmarker for their branch list and the body of the last branch.
1120 + * It might seem that this node could be dispensed with entirely, but the
1121 + * endmarker role is not redundant.
1122 + */
1123 +static char *
1124 +regpiece(int *flagp)
1125 +{
1126 +       register char *ret;
1127 +       register char op;
1128 +       register char *next;
1129 +       int flags;
1130 +
1131 +       ret = regatom(&flags);
1132 +       if (ret == NULL)
1133 +               return(NULL);
1134 +
1135 +       op = *regparse;
1136 +       if (!ISMULT(op)) {
1137 +               *flagp = flags;
1138 +               return(ret);
1139 +       }
1140 +
1141 +       if (!(flags&HASWIDTH) && op != '?')
1142 +               FAIL("*+ operand could be empty");
1143 +       *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
1144 +
1145 +       if (op == '*' && (flags&SIMPLE))
1146 +               reginsert(STAR, ret);
1147 +       else if (op == '*') {
1148 +               /* Emit x* as (x&|), where & means "self". */
1149 +               reginsert(BRANCH, ret);                 /* Either x */
1150 +               regoptail(ret, regnode(BACK));          /* and loop */
1151 +               regoptail(ret, ret);                    /* back */
1152 +               regtail(ret, regnode(BRANCH));          /* or */
1153 +               regtail(ret, regnode(NOTHING));         /* null. */
1154 +       } else if (op == '+' && (flags&SIMPLE))
1155 +               reginsert(PLUS, ret);
1156 +       else if (op == '+') {
1157 +               /* Emit x+ as x(&|), where & means "self". */
1158 +               next = regnode(BRANCH);                 /* Either */
1159 +               regtail(ret, next);
1160 +               regtail(regnode(BACK), ret);            /* loop back */
1161 +               regtail(next, regnode(BRANCH));         /* or */
1162 +               regtail(ret, regnode(NOTHING));         /* null. */
1163 +       } else if (op == '?') {
1164 +               /* Emit x? as (x|) */
1165 +               reginsert(BRANCH, ret);                 /* Either x */
1166 +               regtail(ret, regnode(BRANCH));          /* or */
1167 +               next = regnode(NOTHING);                /* null. */
1168 +               regtail(ret, next);
1169 +               regoptail(ret, next);
1170 +       }
1171 +       regparse++;
1172 +       if (ISMULT(*regparse))
1173 +               FAIL("nested *?+");
1174 +
1175 +       return(ret);
1176 +}
1177 +
1178 +/*
1179 + - regatom - the lowest level
1180 + *
1181 + * Optimization:  gobbles an entire sequence of ordinary characters so that
1182 + * it can turn them into a single node, which is smaller to store and
1183 + * faster to run.  Backslashed characters are exceptions, each becoming a
1184 + * separate node; the code is simpler that way and it's not worth fixing.
1185 + */
1186 +static char *
1187 +regatom(int *flagp)
1188 +{
1189 +       register char *ret;
1190 +       int flags;
1191 +
1192 +       *flagp = WORST;         /* Tentatively. */
1193 +
1194 +       switch (*regparse++) {
1195 +       case '^':
1196 +               ret = regnode(BOL);
1197 +               break;
1198 +       case '$':
1199 +               ret = regnode(EOL);
1200 +               break;
1201 +       case '.':
1202 +               ret = regnode(ANY);
1203 +               *flagp |= HASWIDTH|SIMPLE;
1204 +               break;
1205 +       case '[': {
1206 +                       register int class;
1207 +                       register int classend;
1208 +
1209 +                       if (*regparse == '^') { /* Complement of range. */
1210 +                               ret = regnode(ANYBUT);
1211 +                               regparse++;
1212 +                       } else
1213 +                               ret = regnode(ANYOF);
1214 +                       if (*regparse == ']' || *regparse == '-')
1215 +                               regc(*regparse++);
1216 +                       while (*regparse != '\0' && *regparse != ']') {
1217 +                               if (*regparse == '-') {
1218 +                                       regparse++;
1219 +                                       if (*regparse == ']' || *regparse == '\0')
1220 +                                               regc('-');
1221 +                                       else {
1222 +                                               class = UCHARAT(regparse-2)+1;
1223 +                                               classend = UCHARAT(regparse);
1224 +                                               if (class > classend+1)
1225 +                                                       FAIL("invalid [] range");
1226 +                                               for (; class <= classend; class++)
1227 +                                                       regc(class);
1228 +                                               regparse++;
1229 +                                       }
1230 +                               } else
1231 +                                       regc(*regparse++);
1232 +                       }
1233 +                       regc('\0');
1234 +                       if (*regparse != ']')
1235 +                               FAIL("unmatched []");
1236 +                       regparse++;
1237 +                       *flagp |= HASWIDTH|SIMPLE;
1238 +               }
1239 +               break;
1240 +       case '(':
1241 +               ret = reg(1, &flags);
1242 +               if (ret == NULL)
1243 +                       return(NULL);
1244 +               *flagp |= flags&(HASWIDTH|SPSTART);
1245 +               break;
1246 +       case '\0':
1247 +       case '|':
1248 +       case ')':
1249 +               FAIL("internal urp");   /* Supposed to be caught earlier. */
1250 +               break;
1251 +       case '?':
1252 +       case '+':
1253 +       case '*':
1254 +               FAIL("?+* follows nothing");
1255 +               break;
1256 +       case '\\':
1257 +               if (*regparse == '\0')
1258 +                       FAIL("trailing \\");
1259 +               ret = regnode(EXACTLY);
1260 +               regc(*regparse++);
1261 +               regc('\0');
1262 +               *flagp |= HASWIDTH|SIMPLE;
1263 +               break;
1264 +       default: {
1265 +                       register int len;
1266 +                       register char ender;
1267 +
1268 +                       regparse--;
1269 +                       len = my_strcspn((const char *)regparse, (const char *)META);
1270 +                       if (len <= 0)
1271 +                               FAIL("internal disaster");
1272 +                       ender = *(regparse+len);
1273 +                       if (len > 1 && ISMULT(ender))
1274 +                               len--;          /* Back off clear of ?+* operand. */
1275 +                       *flagp |= HASWIDTH;
1276 +                       if (len == 1)
1277 +                               *flagp |= SIMPLE;
1278 +                       ret = regnode(EXACTLY);
1279 +                       while (len > 0) {
1280 +                               regc(*regparse++);
1281 +                               len--;
1282 +                       }
1283 +                       regc('\0');
1284 +               }
1285 +               break;
1286 +       }
1287 +
1288 +       return(ret);
1289 +}
1290 +
1291 +/*
1292 + - regnode - emit a node
1293 + */
1294 +static char *                  /* Location. */
1295 +regnode(char op)
1296 +{
1297 +       register char *ret;
1298 +       register char *ptr;
1299 +
1300 +       ret = regcode;
1301 +       if (ret == &regdummy) {
1302 +               regsize += 3;
1303 +               return(ret);
1304 +       }
1305 +
1306 +       ptr = ret;
1307 +       *ptr++ = op;
1308 +       *ptr++ = '\0';          /* Null "next" pointer. */
1309 +       *ptr++ = '\0';
1310 +       regcode = ptr;
1311 +
1312 +       return(ret);
1313 +}
1314 +
1315 +/*
1316 + - regc - emit (if appropriate) a byte of code
1317 + */
1318 +static void
1319 +regc(char b)
1320 +{
1321 +       if (regcode != &regdummy)
1322 +               *regcode++ = b;
1323 +       else
1324 +               regsize++;
1325 +}
1326 +
1327 +/*
1328 + - reginsert - insert an operator in front of already-emitted operand
1329 + *
1330 + * Means relocating the operand.
1331 + */
1332 +static void
1333 +reginsert(char op, char* opnd)
1334 +{
1335 +       register char *src;
1336 +       register char *dst;
1337 +       register char *place;
1338 +
1339 +       if (regcode == &regdummy) {
1340 +               regsize += 3;
1341 +               return;
1342 +       }
1343 +
1344 +       src = regcode;
1345 +       regcode += 3;
1346 +       dst = regcode;
1347 +       while (src > opnd)
1348 +               *--dst = *--src;
1349 +
1350 +       place = opnd;           /* Op node, where operand used to be. */
1351 +       *place++ = op;
1352 +       *place++ = '\0';
1353 +       *place++ = '\0';
1354 +}
1355 +
1356 +/*
1357 + - regtail - set the next-pointer at the end of a node chain
1358 + */
1359 +static void
1360 +regtail(char *p, char *val)
1361 +{
1362 +       register char *scan;
1363 +       register char *temp;
1364 +       register int offset;
1365 +
1366 +       if (p == &regdummy)
1367 +               return;
1368 +
1369 +       /* Find last node. */
1370 +       scan = p;
1371 +       for (;;) {
1372 +               temp = regnext(scan);
1373 +               if (temp == NULL)
1374 +                       break;
1375 +               scan = temp;
1376 +       }
1377 +
1378 +       if (OP(scan) == BACK)
1379 +               offset = scan - val;
1380 +       else
1381 +               offset = val - scan;
1382 +       *(scan+1) = (offset>>8)&0377;
1383 +       *(scan+2) = offset&0377;
1384 +}
1385 +
1386 +/*
1387 + - regoptail - regtail on operand of first argument; nop if operandless
1388 + */
1389 +static void
1390 +regoptail(char *p, char *val)
1391 +{
1392 +       /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1393 +       if (p == NULL || p == &regdummy || OP(p) != BRANCH)
1394 +               return;
1395 +       regtail(OPERAND(p), val);
1396 +}
1397 +
1398 +/*
1399 + * regexec and friends
1400 + */
1401 +
1402 +/*
1403 + * Global work variables for regexec().
1404 + */
1405 +static char *reginput;         /* String-input pointer. */
1406 +static char *regbol;           /* Beginning of input, for ^ check. */
1407 +static char **regstartp;       /* Pointer to startp array. */
1408 +static char **regendp;         /* Ditto for endp. */
1409 +
1410 +/*
1411 + * Forwards.
1412 + */
1413 +STATIC int regtry(regexp *prog, char *string);
1414 +STATIC int regmatch(char *prog);
1415 +STATIC int regrepeat(char *p);
1416 +
1417 +#ifdef DEBUG
1418 +int regnarrate = 0;
1419 +void regdump();
1420 +STATIC char *regprop(char *op);
1421 +#endif
1422 +
1423 +/*
1424 + - regexec - match a regexp against a string
1425 + */
1426 +int
1427 +regexec(regexp *prog, char *string)
1428 +{
1429 +       register char *s;
1430 +
1431 +       /* Be paranoid... */
1432 +       if (prog == NULL || string == NULL) {
1433 +               printk("<3>Regexp: NULL parameter\n");
1434 +               return(0);
1435 +       }
1436 +
1437 +       /* Check validity of program. */
1438 +       if (UCHARAT(prog->program) != MAGIC) {
1439 +               printk("<3>Regexp: corrupted program\n");
1440 +               return(0);
1441 +       }
1442 +
1443 +       /* If there is a "must appear" string, look for it. */
1444 +       if (prog->regmust != NULL) {
1445 +               s = string;
1446 +               while ((s = strchr(s, prog->regmust[0])) != NULL) {
1447 +                       if (strncmp(s, prog->regmust, prog->regmlen) == 0)
1448 +                               break;  /* Found it. */
1449 +                       s++;
1450 +               }
1451 +               if (s == NULL)  /* Not present. */
1452 +                       return(0);
1453 +       }
1454 +
1455 +       /* Mark beginning of line for ^ . */
1456 +       regbol = string;
1457 +
1458 +       /* Simplest case:  anchored match need be tried only once. */
1459 +       if (prog->reganch)
1460 +               return(regtry(prog, string));
1461 +
1462 +       /* Messy cases:  unanchored match. */
1463 +       s = string;
1464 +       if (prog->regstart != '\0')
1465 +               /* We know what char it must start with. */
1466 +               while ((s = strchr(s, prog->regstart)) != NULL) {
1467 +                       if (regtry(prog, s))
1468 +                               return(1);
1469 +                       s++;
1470 +               }
1471 +       else
1472 +               /* We don't -- general case. */
1473 +               do {
1474 +                       if (regtry(prog, s))
1475 +                               return(1);
1476 +               } while (*s++ != '\0');
1477 +
1478 +       /* Failure. */
1479 +       return(0);
1480 +}
1481 +
1482 +/*
1483 + - regtry - try match at specific point
1484 + */
1485 +static int                     /* 0 failure, 1 success */
1486 +regtry(regexp *prog, char *string)
1487 +{
1488 +       register int i;
1489 +       register char **sp;
1490 +       register char **ep;
1491 +
1492 +       reginput = string;
1493 +       regstartp = prog->startp;
1494 +       regendp = prog->endp;
1495 +
1496 +       sp = prog->startp;
1497 +       ep = prog->endp;
1498 +       for (i = NSUBEXP; i > 0; i--) {
1499 +               *sp++ = NULL;
1500 +               *ep++ = NULL;
1501 +       }
1502 +       if (regmatch(prog->program + 1)) {
1503 +               prog->startp[0] = string;
1504 +               prog->endp[0] = reginput;
1505 +               return(1);
1506 +       } else
1507 +               return(0);
1508 +}
1509 +
1510 +/*
1511 + - regmatch - main matching routine
1512 + *
1513 + * Conceptually the strategy is simple:  check to see whether the current
1514 + * node matches, call self recursively to see whether the rest matches,
1515 + * and then act accordingly.  In practice we make some effort to avoid
1516 + * recursion, in particular by going through "ordinary" nodes (that don't
1517 + * need to know whether the rest of the match failed) by a loop instead of
1518 + * by recursion.
1519 + */
1520 +static int                     /* 0 failure, 1 success */
1521 +regmatch(char *prog)
1522 +{
1523 +       register char *scan = prog; /* Current node. */
1524 +       char *next;                 /* Next node. */
1525 +
1526 +#ifdef DEBUG
1527 +       if (scan != NULL && regnarrate)
1528 +               fprintf(stderr, "%s(\n", regprop(scan));
1529 +#endif
1530 +       while (scan != NULL) {
1531 +#ifdef DEBUG
1532 +               if (regnarrate)
1533 +                       fprintf(stderr, "%s...\n", regprop(scan));
1534 +#endif
1535 +               next = regnext(scan);
1536 +
1537 +               switch (OP(scan)) {
1538 +               case BOL:
1539 +                       if (reginput != regbol)
1540 +                               return(0);
1541 +                       break;
1542 +               case EOL:
1543 +                       if (*reginput != '\0')
1544 +                               return(0);
1545 +                       break;
1546 +               case ANY:
1547 +                       if (*reginput == '\0')
1548 +                               return(0);
1549 +                       reginput++;
1550 +                       break;
1551 +               case EXACTLY: {
1552 +                               register int len;
1553 +                               register char *opnd;
1554 +
1555 +                               opnd = OPERAND(scan);
1556 +                               /* Inline the first character, for speed. */
1557 +                               if (*opnd != *reginput)
1558 +                                       return(0);
1559 +                               len = strlen(opnd);
1560 +                               if (len > 1 && strncmp(opnd, reginput, len) != 0)
1561 +                                       return(0);
1562 +                               reginput += len;
1563 +                       }
1564 +                       break;
1565 +               case ANYOF:
1566 +                       if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
1567 +                               return(0);
1568 +                       reginput++;
1569 +                       break;
1570 +               case ANYBUT:
1571 +                       if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
1572 +                               return(0);
1573 +                       reginput++;
1574 +                       break;
1575 +               case NOTHING:
1576 +               case BACK:
1577 +                       break;
1578 +               case OPEN+1:
1579 +               case OPEN+2:
1580 +               case OPEN+3:
1581 +               case OPEN+4:
1582 +               case OPEN+5:
1583 +               case OPEN+6:
1584 +               case OPEN+7:
1585 +               case OPEN+8:
1586 +               case OPEN+9: {
1587 +                               register int no;
1588 +                               register char *save;
1589 +
1590 +                               no = OP(scan) - OPEN;
1591 +                               save = reginput;
1592 +
1593 +                               if (regmatch(next)) {
1594 +                                       /*
1595 +                                        * Don't set startp if some later
1596 +                                        * invocation of the same parentheses
1597 +                                        * already has.
1598 +                                        */
1599 +                                       if (regstartp[no] == NULL)
1600 +                                               regstartp[no] = save;
1601 +                                       return(1);
1602 +                               } else
1603 +                                       return(0);
1604 +                       }
1605 +                       break;
1606 +               case CLOSE+1:
1607 +               case CLOSE+2:
1608 +               case CLOSE+3:
1609 +               case CLOSE+4:
1610 +               case CLOSE+5:
1611 +               case CLOSE+6:
1612 +               case CLOSE+7:
1613 +               case CLOSE+8:
1614 +               case CLOSE+9:
1615 +                       {
1616 +                               register int no;
1617 +                               register char *save;
1618 +
1619 +                               no = OP(scan) - CLOSE;
1620 +                               save = reginput;
1621 +
1622 +                               if (regmatch(next)) {
1623 +                                       /*
1624 +                                        * Don't set endp if some later
1625 +                                        * invocation of the same parentheses
1626 +                                        * already has.
1627 +                                        */
1628 +                                       if (regendp[no] == NULL)
1629 +                                               regendp[no] = save;
1630 +                                       return(1);
1631 +                               } else
1632 +                                       return(0);
1633 +                       }
1634 +                       break;
1635 +               case BRANCH: {
1636 +                               register char *save;
1637 +
1638 +                               if (OP(next) != BRANCH)         /* No choice. */
1639 +                                       next = OPERAND(scan);   /* Avoid recursion. */
1640 +                               else {
1641 +                                       do {
1642 +                                               save = reginput;
1643 +                                               if (regmatch(OPERAND(scan)))
1644 +                                                       return(1);
1645 +                                               reginput = save;
1646 +                                               scan = regnext(scan);
1647 +                                       } while (scan != NULL && OP(scan) == BRANCH);
1648 +                                       return(0);
1649 +                                       /* NOTREACHED */
1650 +                               }
1651 +                       }
1652 +                       break;
1653 +               case STAR:
1654 +               case PLUS: {
1655 +                               register char nextch;
1656 +                               register int no;
1657 +                               register char *save;
1658 +                               register int min;
1659 +
1660 +                               /*
1661 +                                * Lookahead to avoid useless match attempts
1662 +                                * when we know what character comes next.
1663 +                                */
1664 +                               nextch = '\0';
1665 +                               if (OP(next) == EXACTLY)
1666 +                                       nextch = *OPERAND(next);
1667 +                               min = (OP(scan) == STAR) ? 0 : 1;
1668 +                               save = reginput;
1669 +                               no = regrepeat(OPERAND(scan));
1670 +                               while (no >= min) {
1671 +                                       /* If it could work, try it. */
1672 +                                       if (nextch == '\0' || *reginput == nextch)
1673 +                                               if (regmatch(next))
1674 +                                                       return(1);
1675 +                                       /* Couldn't or didn't -- back up. */
1676 +                                       no--;
1677 +                                       reginput = save + no;
1678 +                               }
1679 +                               return(0);
1680 +                       }
1681 +                       break;
1682 +               case END:
1683 +                       return(1);      /* Success! */
1684 +                       break;
1685 +               default:
1686 +                       printk("<3>Regexp: memory corruption\n");
1687 +                       return(0);
1688 +                       break;
1689 +               }
1690 +
1691 +               scan = next;
1692 +       }
1693 +
1694 +       /*
1695 +        * We get here only if there's trouble -- normally "case END" is
1696 +        * the terminating point.
1697 +        */
1698 +       printk("<3>Regexp: corrupted pointers\n");
1699 +       return(0);
1700 +}
1701 +
1702 +/*
1703 + - regrepeat - repeatedly match something simple, report how many
1704 + */
1705 +static int
1706 +regrepeat(char *p)
1707 +{
1708 +       register int count = 0;
1709 +       register char *scan;
1710 +       register char *opnd;
1711 +
1712 +       scan = reginput;
1713 +       opnd = OPERAND(p);
1714 +       switch (OP(p)) {
1715 +       case ANY:
1716 +               count = strlen(scan);
1717 +               scan += count;
1718 +               break;
1719 +       case EXACTLY:
1720 +               while (*opnd == *scan) {
1721 +                       count++;
1722 +                       scan++;
1723 +               }
1724 +               break;
1725 +       case ANYOF:
1726 +               while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1727 +                       count++;
1728 +                       scan++;
1729 +               }
1730 +               break;
1731 +       case ANYBUT:
1732 +               while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1733 +                       count++;
1734 +                       scan++;
1735 +               }
1736 +               break;
1737 +       default:                /* Oh dear.  Called inappropriately. */
1738 +               printk("<3>Regexp: internal foulup\n");
1739 +               count = 0;      /* Best compromise. */
1740 +               break;
1741 +       }
1742 +       reginput = scan;
1743 +
1744 +       return(count);
1745 +}
1746 +
1747 +/*
1748 + - regnext - dig the "next" pointer out of a node
1749 + */
1750 +static char* 
1751 +regnext(char *p)
1752 +{
1753 +       register int offset;
1754 +
1755 +       if (p == &regdummy)
1756 +               return(NULL);
1757 +
1758 +       offset = NEXT(p);
1759 +       if (offset == 0)
1760 +               return(NULL);
1761 +
1762 +       if (OP(p) == BACK)
1763 +               return(p-offset);
1764 +       else
1765 +               return(p+offset);
1766 +}
1767 +
1768 +#ifdef DEBUG
1769 +
1770 +STATIC char *regprop();
1771 +
1772 +/*
1773 + - regdump - dump a regexp onto stdout in vaguely comprehensible form
1774 + */
1775 +void
1776 +regdump(regexp *r)
1777 +{
1778 +       register char *s;
1779 +       register char op = EXACTLY;     /* Arbitrary non-END op. */
1780 +       register char *next;
1781 +       /* extern char *strchr(); */
1782 +
1783 +
1784 +       s = r->program + 1;
1785 +       while (op != END) {     /* While that wasn't END last time... */
1786 +               op = OP(s);
1787 +               printf("%2d%s", s-r->program, regprop(s));      /* Where, what. */
1788 +               next = regnext(s);
1789 +               if (next == NULL)               /* Next ptr. */
1790 +                       printf("(0)");
1791 +               else 
1792 +                       printf("(%d)", (s-r->program)+(next-s));
1793 +               s += 3;
1794 +               if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1795 +                       /* Literal string, where present. */
1796 +                       while (*s != '\0') {
1797 +                               putchar(*s);
1798 +                               s++;
1799 +                       }
1800 +                       s++;
1801 +               }
1802 +               putchar('\n');
1803 +       }
1804 +
1805 +       /* Header fields of interest. */
1806 +       if (r->regstart != '\0')
1807 +               printf("start `%c' ", r->regstart);
1808 +       if (r->reganch)
1809 +               printf("anchored ");
1810 +       if (r->regmust != NULL)
1811 +               printf("must have \"%s\"", r->regmust);
1812 +       printf("\n");
1813 +}
1814 +
1815 +/*
1816 + - regprop - printable representation of opcode
1817 + */
1818 +static char *
1819 +regprop(char *op)
1820 +{
1821 +#define BUFLEN 50
1822 +       register char *p;
1823 +       static char buf[BUFLEN];
1824 +
1825 +       strcpy(buf, ":");
1826 +
1827 +       switch (OP(op)) {
1828 +       case BOL:
1829 +               p = "BOL";
1830 +               break;
1831 +       case EOL:
1832 +               p = "EOL";
1833 +               break;
1834 +       case ANY:
1835 +               p = "ANY";
1836 +               break;
1837 +       case ANYOF:
1838 +               p = "ANYOF";
1839 +               break;
1840 +       case ANYBUT:
1841 +               p = "ANYBUT";
1842 +               break;
1843 +       case BRANCH:
1844 +               p = "BRANCH";
1845 +               break;
1846 +       case EXACTLY:
1847 +               p = "EXACTLY";
1848 +               break;
1849 +       case NOTHING:
1850 +               p = "NOTHING";
1851 +               break;
1852 +       case BACK:
1853 +               p = "BACK";
1854 +               break;
1855 +       case END:
1856 +               p = "END";
1857 +               break;
1858 +       case OPEN+1:
1859 +       case OPEN+2:
1860 +       case OPEN+3:
1861 +       case OPEN+4:
1862 +       case OPEN+5:
1863 +       case OPEN+6:
1864 +       case OPEN+7:
1865 +       case OPEN+8:
1866 +       case OPEN+9:
1867 +               snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "OPEN%d", OP(op)-OPEN);
1868 +               p = NULL;
1869 +               break;
1870 +       case CLOSE+1:
1871 +       case CLOSE+2:
1872 +       case CLOSE+3:
1873 +       case CLOSE+4:
1874 +       case CLOSE+5:
1875 +       case CLOSE+6:
1876 +       case CLOSE+7:
1877 +       case CLOSE+8:
1878 +       case CLOSE+9:
1879 +               snprintf(buf+strlen(buf),BUFLEN-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1880 +               p = NULL;
1881 +               break;
1882 +       case STAR:
1883 +               p = "STAR";
1884 +               break;
1885 +       case PLUS:
1886 +               p = "PLUS";
1887 +               break;
1888 +       default:
1889 +               printk("<3>Regexp: corrupted opcode\n");
1890 +               break;
1891 +       }
1892 +       if (p != NULL)
1893 +               strncat(buf, p, BUFLEN-strlen(buf));
1894 +       return(buf);
1895 +}
1896 +#endif
1897 +
1898 +
1899 diff -Nurp linux-2.4.30/net/ipv4/netfilter/regexp/regexp.h linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regexp.h
1900 --- linux-2.4.30/net/ipv4/netfilter/regexp/regexp.h     1969-12-31 18:00:00.000000000 -0600
1901 +++ linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regexp.h      2005-05-03 18:37:03.000000000 -0500
1902 @@ -0,0 +1,40 @@
1903 +/*
1904 + * Definitions etc. for regexp(3) routines.
1905 + *
1906 + * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
1907 + * not the System V one.
1908 + */
1909 +
1910 +#ifndef REGEXP_H
1911 +#define REGEXP_H
1912 +
1913 +/* 
1914 +http://www.opensource.apple.com/darwinsource/10.3/expect-1/expect/expect.h , 
1915 +which contains a version of this library, says:
1916 +
1917 + *
1918 + * NSUBEXP must be at least 10, and no greater than 117 or the parser
1919 + * will not work properly.
1920 + *
1921 +
1922 +However, it looks rather like this library is limited to 10.  If you think
1923 +otherwise, let us know.
1924 +*/
1925 +
1926 +#define NSUBEXP  10
1927 +typedef struct regexp {
1928 +       char *startp[NSUBEXP];
1929 +       char *endp[NSUBEXP];
1930 +       char regstart;          /* Internal use only. */
1931 +       char reganch;           /* Internal use only. */
1932 +       char *regmust;          /* Internal use only. */
1933 +       int regmlen;            /* Internal use only. */
1934 +       char program[1];        /* Unwarranted chumminess with compiler. */
1935 +} regexp;
1936 +
1937 +regexp * regcomp(char *exp, int *patternsize);
1938 +int regexec(regexp *prog, char *string);
1939 +void regsub(regexp *prog, char *source, char *dest);
1940 +void regerror(char *s);
1941 +
1942 +#endif
1943 diff -Nurp linux-2.4.30/net/ipv4/netfilter/regexp/regmagic.h linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regmagic.h
1944 --- linux-2.4.30/net/ipv4/netfilter/regexp/regmagic.h   1969-12-31 18:00:00.000000000 -0600
1945 +++ linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regmagic.h    2005-05-03 18:37:03.000000000 -0500
1946 @@ -0,0 +1,5 @@
1947 +/*
1948 + * The first byte of the regexp internal "program" is actually this magic
1949 + * number; the start node begins in the second byte.
1950 + */
1951 +#define        MAGIC   0234
1952 diff -Nurp linux-2.4.30/net/ipv4/netfilter/regexp/regsub.c linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regsub.c
1953 --- linux-2.4.30/net/ipv4/netfilter/regexp/regsub.c     1969-12-31 18:00:00.000000000 -0600
1954 +++ linux-2.4.30-layer7/net/ipv4/netfilter/regexp/regsub.c      2005-05-03 18:37:03.000000000 -0500
1955 @@ -0,0 +1,95 @@
1956 +/*
1957 + * regsub
1958 + * @(#)regsub.c        1.3 of 2 April 86
1959 + *
1960 + *     Copyright (c) 1986 by University of Toronto.
1961 + *     Written by Henry Spencer.  Not derived from licensed software.
1962 + *
1963 + *     Permission is granted to anyone to use this software for any
1964 + *     purpose on any computer system, and to redistribute it freely,
1965 + *     subject to the following restrictions:
1966 + *
1967 + *     1. The author is not responsible for the consequences of use of
1968 + *             this software, no matter how awful, even if they arise
1969 + *             from defects in it.
1970 + *
1971 + *     2. The origin of this software must not be misrepresented, either
1972 + *             by explicit claim or by omission.
1973 + *
1974 + *     3. Altered versions must be plainly marked as such, and must not
1975 + *             be misrepresented as being the original software.
1976 + *
1977 + *
1978 + * This code was modified by Ethan Sommer to work within the kernel
1979 + * (it now uses kmalloc etc..)
1980 + *
1981 + */
1982 +#include "regexp.h"
1983 +#include "regmagic.h"
1984 +#include <linux/string.h>
1985 +
1986 +
1987 +#ifndef CHARBITS
1988 +#define        UCHARAT(p)      ((int)*(unsigned char *)(p))
1989 +#else
1990 +#define        UCHARAT(p)      ((int)*(p)&CHARBITS)
1991 +#endif
1992 +
1993 +#if 0
1994 +//void regerror(char * s)
1995 +//{
1996 +//        printk("regexp(3): %s", s);
1997 +//        /* NOTREACHED */
1998 +//}
1999 +#endif
2000 +
2001 +/*
2002 + - regsub - perform substitutions after a regexp match
2003 + */
2004 +void
2005 +regsub(regexp * prog, char * source, char * dest)
2006 +{
2007 +       register char *src;
2008 +       register char *dst;
2009 +       register char c;
2010 +       register int no;
2011 +       register int len;
2012 +       
2013 +       /* Not necessary and gcc doesn't like it -MLS */
2014 +       /*extern char *strncpy();*/
2015 +
2016 +       if (prog == NULL || source == NULL || dest == NULL) {
2017 +               regerror("NULL parm to regsub");
2018 +               return;
2019 +       }
2020 +       if (UCHARAT(prog->program) != MAGIC) {
2021 +               regerror("damaged regexp fed to regsub");
2022 +               return;
2023 +       }
2024 +
2025 +       src = source;
2026 +       dst = dest;
2027 +       while ((c = *src++) != '\0') {
2028 +               if (c == '&')
2029 +                       no = 0;
2030 +               else if (c == '\\' && '0' <= *src && *src <= '9')
2031 +                       no = *src++ - '0';
2032 +               else
2033 +                       no = -1;
2034 +
2035 +               if (no < 0) {   /* Ordinary character. */
2036 +                       if (c == '\\' && (*src == '\\' || *src == '&'))
2037 +                               c = *src++;
2038 +                       *dst++ = c;
2039 +               } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
2040 +                       len = prog->endp[no] - prog->startp[no];
2041 +                       (void) strncpy(dst, prog->startp[no], len);
2042 +                       dst += len;
2043 +                       if (len != 0 && *(dst-1) == '\0') {     /* strncpy hit NUL. */
2044 +                               regerror("damaged match string");
2045 +                               return;
2046 +                       }
2047 +               }
2048 +       }
2049 +       *dst++ = '\0';
2050 +}