replace libcgi with some code extracted from haserl - libcgi is too inflexible and...
[librecmc/librecmc.git] / package / busybox / patches / 920-awx.patch
1 diff -purN bb.old/editors/awk.c bb.dev/editors/awk.c
2 --- bb.old/editors/awk.c        2007-03-06 19:38:07.278092000 +0100
3 +++ bb.dev/editors/awk.c        2007-03-11 05:14:11.776304544 +0100
4 @@ -30,6 +30,11 @@
5  /* these flags are static, don't change them when value is changed */
6  #define        VF_DONTTOUCH (VF_ARRAY | VF_SPECIAL | VF_WALK | VF_CHILD | VF_DIRTY)
7  
8 +#ifdef CONFIG_AWX
9 +#define fputs(s, stream) fputs_hook(s, stream)
10 +static inline int fputs_hook (__const char *__restrict __s, FILE *__restrict __stream);
11 +#endif
12 +
13  /* Variable */
14  typedef struct var_s {
15         unsigned short type;            /* flags */
16 @@ -50,10 +55,15 @@ typedef struct chain_s {
17         char *programname;
18  } chain;
19  
20 +typedef var *(*awk_cfunc)(var *res, var *args, int nargs);
21  /* Function */
22  typedef struct func_s {
23         unsigned short nargs;
24 -       struct chain_s body;
25 +       enum { AWKFUNC, CFUNC } type;
26 +       union {
27 +               awk_cfunc cfunc;
28 +               struct chain_s body;
29 +       } x;
30  } func;
31  
32  /* I/O stream */
33 @@ -1312,7 +1322,8 @@ static void parse_program(char *p)
34                         next_token(TC_FUNCTION);
35                         pos++;
36                         f = newfunc(t.string);
37 -                       f->body.first = NULL;
38 +                       f->type = AWKFUNC;
39 +                       f->x.body.first = NULL;
40                         f->nargs = 0;
41                         while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
42                                 v = findvar(ahash, t.string);
43 @@ -1321,7 +1332,7 @@ static void parse_program(char *p)
44                                 if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
45                                         break;
46                         }
47 -                       seq = &(f->body);
48 +                       seq = &(f->x.body);
49                         chain_group();
50                         clear_array(ahash);
51  
52 @@ -2260,7 +2271,8 @@ static var *evaluate(node *op, var *res)
53                         break;
54  
55                 case XC( OC_FUNC ):
56 -                       if (! op->r.f->body.first)
57 +                       if ((op->r.f->type == AWKFUNC) &&
58 +                               !op->r.f->x.body.first)
59                                 runtime_error(EMSG_UNDEF_FUNC);
60  
61                         X.v = R.v = nvalloc(op->r.f->nargs+1);
62 @@ -2277,7 +2289,11 @@ static var *evaluate(node *op, var *res)
63                         fnargs = X.v;
64  
65                         L.s = programname;
66 -                       res = evaluate(op->r.f->body.first, res);
67 +                       if (op->r.f->type == AWKFUNC)
68 +                               res = evaluate(op->r.f->x.body.first, res);
69 +                       else if (op->r.f->type == CFUNC)
70 +                               res = op->r.f->x.cfunc(res, fnargs, op->r.f->nargs);
71 +
72                         programname = L.s;
73  
74                         nvfree(fnargs);
75 @@ -2637,6 +2653,11 @@ static rstream *next_input_file(void)
76         return &rsm;
77  }
78  
79 +#ifdef CONFIG_AWX
80 +static int is_awx = 0;
81 +#include "awx.c"
82 +#endif
83 +
84  int awk_main(int argc, char **argv)
85  {
86         int i, j, flen;
87 @@ -2693,6 +2714,10 @@ int awk_main(int argc, char **argv)
88                 free(s);
89         }
90  
91 +#ifdef CONFIG_AWX
92 +       do_awx(argc, argv);
93 +#endif
94 +
95         programname = NULL;
96         while((c = getopt(argc, argv, "F:v:f:W:")) != EOF) {
97                 switch (c) {
98 diff -purN bb.old/editors/awx.c bb.dev/editors/awx.c
99 --- bb.old/editors/awx.c        1970-01-01 01:00:00.000000000 +0100
100 +++ bb.dev/editors/awx.c        2007-03-11 19:03:27.417297384 +0100
101 @@ -0,0 +1,553 @@
102 +/*
103 + * awk web extension
104 + *
105 + * Copyright (C) 2007 by Felix Fietkau <nbd@openwrt.org>
106 + *
107 + * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
108 + */
109 +
110 +#include <cgi.h>
111 +#include <glob.h>
112 +
113 +#define LINE_BUF 2048
114 +#define HASH_MAX       1536
115 +#define TR_START       "@TR<<"
116 +#define TR_END         ">>"
117 +#define MAX_TR 32
118 +#define SSI_START "<%"
119 +#define SSI_END "%>"
120 +
121 +#undef fputs
122 +
123 +static xhash *lstr = NULL;
124 +static xhash *formvar = NULL;
125 +static int lang_inuse = 0;
126 +
127 +/* look up a translation symbol from the hash */
128 +static inline char *translate_lookup(char *str)
129 +{
130 +       char *name, *def, *p;
131 +       hash_item *hi;
132 +       var *v;
133 +
134 +       def = name = str;
135 +       if (((p = strchr(str, '|')) != NULL)
136 +               || ((p = strchr(str, '#')) != NULL)) {
137 +               def = p + 1;
138 +               *p = 0;
139 +       }
140 +       
141 +       hi = hash_search(lstr, name);
142 +       if (!hi)
143 +               return def;
144 +       
145 +       v = &hi->data.v;
146 +
147 +       return getvar_s(v);
148 +}
149 +
150 +/* look for translation markers in the line and return the translated string */
151 +static char *translate_line(char *line)
152 +{
153 +       char *tok[MAX_TR * 3];
154 +       char *l, *p, *p2, *res;
155 +       int len = 0, _pos = 0, i;
156 +
157 +       l = line;
158 +       while (l != NULL) {
159 +               if ((p = strstr(l, TR_START)) == NULL) {
160 +                       len += strlen((tok[_pos++] = l));
161 +                       break;
162 +               }
163 +
164 +               p2 = strstr(p, TR_END);
165 +               if (p2 == NULL)
166 +                       break;
167 +
168 +               *p = 0;
169 +               *p2 = 0;
170 +               len += strlen((tok[_pos++] = l));
171 +               len += strlen((tok[_pos++] = translate_lookup(p + strlen(TR_START))));
172 +
173 +               l = p2;
174 +               l += strlen(TR_END);
175 +       }
176 +       len++;
177 +
178 +       p = xmalloc(len + 1);
179 +       *p = 0;
180 +       res = p;
181 +       for (i = 0; i < _pos; i++) {
182 +               strcat(p, tok[i]);
183 +               p += strlen(tok[i]);
184 +       }
185 +
186 +       return res;
187 +}
188 +
189 +/* hook for intercepting awk's use of puts. used for running all printed strings
190 + * through the translation system */
191 +static inline int fputs_hook (__const char *__restrict __s, FILE *__restrict __stream)
192 +{
193 +       if (lang_inuse && (__stream == stdout)) {
194 +               int ret;
195 +               char *str;
196 +       
197 +               str = translate_line((char *) __s);
198 +               ret = fputs(str, __stream);
199 +               free(str);
200 +
201 +               return ret;
202 +       }
203 +
204 +       return fputs(__s, __stream);
205 +}
206 +
207 +static var *init_lang(var *res, var *args, int nargs)
208 +{
209 +       if (!lstr)
210 +               lstr = hash_init();
211 +
212 +       lang_inuse = 1;
213 +       return res;
214 +}
215 +
216 +
217 +/* load and parse language file */
218 +static void load_lang_file(char *file)
219 +{
220 +       FILE *f;
221 +       char *b, *name, *value;
222 +       char buf1[LINE_BUF];
223 +
224 +       if ((f = fopen(file, "r")) == NULL)
225 +               return;
226 +
227 +       while (!feof(f) && (fgets(buf1, LINE_BUF - 1, f) != NULL)) {
228 +               b = buf1;
229 +               if (*b == '#')
230 +                       continue; /* skip comments */
231 +
232 +               while (isspace(*b))
233 +                       b++; /* skip leading spaces */
234 +               if (!*b)
235 +                       continue;
236 +               
237 +               name = b;
238 +               if ((b = strstr(name, "=>")) == NULL)
239 +                       continue; /* separator not found */
240 +
241 +               value = b + 2;
242 +               if (!*value)
243 +                       continue;
244 +               
245 +               *b = 0;
246 +               for (b--; isspace(*b); b--)
247 +                       *b = 0; /* remove trailing spaces */
248 +               
249 +               while (isspace(*value))
250 +                       value++; /* skip leading spaces */
251 +
252 +               for (b = value + strlen(value) - 1; isspace(*b); b--)
253 +                       *b = 0; /* remove trailing spaces */
254 +               
255 +               if (!*value)
256 +                       continue;
257 +
258 +               setvar_s(findvar(lstr,name), value);
259 +       }
260 +
261 +       fclose(f);
262 +}
263 +
264 +static var *load_lang(var *res, var *args, int nargs)
265 +{
266 +       const char *langfmt = "/usr/lib/webif/lang/%s.txt";
267 +       char lbuf[LINE_BUF];
268 +       char *lang;
269 +
270 +       if (!lang_inuse)
271 +               init_lang(res, args, nargs);
272 +       
273 +       lang = getvar_s(args);
274 +       if (!lang || !strcmp(lang, ""))
275 +               return res;
276 +
277 +       sprintf(lbuf, langfmt, lang);
278 +       load_lang_file(lbuf);
279 +
280 +       return res;     
281 +}
282 +               
283 +/* read the contents of an entire file */
284 +static char *get_file(char *fname)
285 +{
286 +       FILE *F;
287 +       char *s = NULL;
288 +       int i, j, flen;
289 +
290 +       F = fopen(fname, "r");
291 +       if (!F) {
292 +               return NULL;
293 +       }
294 +
295 +       if (fseek(F, 0, SEEK_END) == 0) {
296 +               flen = ftell(F);
297 +               s = (char *)xmalloc(flen+4);
298 +               fseek(F, 0, SEEK_SET);
299 +               i = 1 + fread(s+1, 1, flen, F);
300 +       } else {
301 +               for (i=j=1; j>0; i+=j) {
302 +                       s = (char *)xrealloc(s, i+4096);
303 +                       j = fread(s+i, 1, 4094, F);
304 +               }
305 +       }
306 +
307 +       s[i] = '\0';
308 +       fclose(F);
309 +       return s;
310 +}
311 +
312 +
313 +/* parse_include():
314 + * 
315 + * taken from parse_program from awk.c
316 + * END{} is not parsed here, and BEGIN{} is executed immediately
317 + */
318 +static void parse_include(char *p)
319 +{
320 +       uint32_t tclass;
321 +       chain initseq;
322 +       func *f;
323 +       var *v, tv;
324 +       int has_init = 0;
325 +
326 +       pos = p;
327 +       t.lineno = 1;
328 +       memset(&initseq, 0, sizeof(initseq));
329 +       while ((tclass = next_token(TC_EOF | TC_OPSEQ |
330 +                               TC_OPTERM | TC_BEGIN | TC_FUNCDECL)) != TC_EOF) {
331 +               if (tclass & TC_OPTERM)
332 +                       continue;
333 +
334 +               seq = &initseq;
335 +               if (tclass & TC_BEGIN) {
336 +                       has_init = 1;
337 +                       chain_group();
338 +               } else if (tclass & TC_FUNCDECL) {
339 +                       next_token(TC_FUNCTION);
340 +                       pos++;
341 +                       f = newfunc(t.string);
342 +                       f->type = AWKFUNC;
343 +                       f->x.body.first = NULL;
344 +                       f->nargs = 0;
345 +                       while (next_token(TC_VARIABLE | TC_SEQTERM) & TC_VARIABLE) {
346 +                               v = findvar(ahash, t.string);
347 +                               v->x.aidx = (f->nargs)++;
348 +
349 +                               if (next_token(TC_COMMA | TC_SEQTERM) & TC_SEQTERM)
350 +                                       break;
351 +                       }
352 +                       seq = &(f->x.body);
353 +                       chain_group();
354 +                       clear_array(ahash);
355 +               }
356 +       }
357 +       if (has_init)
358 +               evaluate(initseq.first, &tv);
359 +}
360 +
361 +/* include an awk file and run its BEGIN{} section */
362 +static var *include(var *res, var *args, int nargs)
363 +{
364 +       static xhash *includes = NULL;
365 +       char *s;
366 +       var *v;
367 +
368 +       s = getvar_s(args);
369 +       if (!s)
370 +               return res;
371 +
372 +       if (!includes)
373 +               includes = hash_init();
374 +       
375 +       /* find out if the file has been included already */
376 +       v = findvar(includes, s);
377 +       if (istrue(v))
378 +               return res;
379 +       setvar_s(v, "1");
380 +
381 +       /* read include file */
382 +       s = get_file(s);
383 +       if (!s) {
384 +               fprintf(stderr, "Could not open file.\n");
385 +               return res;
386 +       }
387 +       parse_include(s+1);
388 +       free(s);
389 +
390 +       return res;
391 +}
392 +
393 +
394 +/* parse and evaluate an awk expression and return the result as string */
395 +static char *render_lookup(char *fname, int lnr, char *str)
396 +{
397 +       chain body;
398 +       var tv;
399 +
400 +       memset(&body, 0, sizeof(body));
401 +       zero_out_var(&tv);
402 +       pos = str;
403 +       seq = &body;
404 +       
405 +       /* end of expression, assume that there's going to be a free byte
406 +        * at the end of the string that can be used for the ')' */
407 +       strcat(str + strlen(str), ")");
408 +       return getvar_s(evaluate(parse_expr(TC_SEQTERM), &tv));
409 +}
410 +
411 +static inline void print_translate(char *s)
412 +{
413 +       char *str = s;
414 +       if (lang_inuse)
415 +               str = translate_line(s);
416 +       fputs(str, stdout);
417 +       fflush(stdout);
418 +       if (lang_inuse)
419 +               free(str);
420 +}
421 +
422 +/* process awk calls in a template line and print the output to stdout */
423 +static void render_line(char *fname, int lnr, char *line)
424 +{
425 +       char *tok[MAX_TR * 3];
426 +       char *l, *p, *p2, *res;
427 +       int len = 0, _pos = 0, i;
428 +
429 +       l = line;
430 +       while (l != NULL) {
431 +               if ((p = strstr(l, SSI_START)) == NULL) {
432 +                       len += strlen((tok[_pos++] = l));
433 +                       break;
434 +               }
435 +
436 +               p2 = strstr(p, SSI_END);
437 +               if (p2 == NULL) {
438 +                       fprintf(stderr, "Parse error in '%s', line '%d', unmatched %s\n", fname, lnr, SSI_END);
439 +                       break;
440 +               }
441 +
442 +               *p = 0;
443 +               *p2 = 0;
444 +               
445 +               len += strlen((tok[_pos++] = l));
446 +               len += strlen((tok[_pos++] = render_lookup(fname, lnr, p + strlen(SSI_START))));
447 +
448 +               l = p2;
449 +               l += strlen(SSI_END);
450 +       }
451 +       len++;
452 +
453 +       p = xmalloc(len + 1);
454 +       *p = 0;
455 +       res = p;
456 +       for (i = 0; i < _pos; i++) {
457 +               strcat(p, tok[i]);
458 +               p += strlen(tok[i]);
459 +       }
460 +       print_translate(res);
461 +       free(res);
462 +}
463 +
464 +/* awk method render(), which opens a template file and processes all awk ssi calls */
465 +static var *render(var *res, var *args, int nargs)
466 +{
467 +       char *s;
468 +       int lnr = 0;
469 +       FILE *f;
470 +       char *buf1;
471 +                       
472 +       buf1 = xmalloc(LINE_BUF);
473 +       s = getvar_s(args);
474 +       if (!s)
475 +               goto done;
476 +
477 +       f = fopen(s, "r");
478 +       if (!f)
479 +               goto done;
480 +
481 +       while (!feof(f) && (fgets(buf1, LINE_BUF - 1, f) != NULL)) {
482 +               render_line(s, ++lnr, buf1);
483 +       }
484 +       
485 +done:
486 +       free(buf1);
487 +       return res;
488 +}
489 +
490 +/* Call render, but only if this function hasn't been called already */
491 +static int layout_rendered = 0;
492 +static var *render_layout(var *res, var *args, int nargs)
493 +{
494 +       if (layout_rendered)
495 +               return res;
496 +       layout_rendered = 1;
497 +       return render(res, args, nargs);
498 +}
499 +
500 +/* registers a global c function for the awk interpreter */
501 +static void register_cfunc(char *name, awk_cfunc cfunc, int nargs)
502 +{
503 +       func *f;
504 +
505 +       f = newfunc(name);
506 +       f->type = CFUNC;
507 +       f->x.cfunc = cfunc;
508 +       f->nargs = nargs;
509 +}
510 +
511 +static void putvar(vartype type, char *name, char *value)
512 +{
513 +       if (type != FORM_VAR)
514 +               return;
515 +
516 +       setvar_u(findvar(formvar, name), value);
517 +}
518 +
519 +static char *cgi_getvar(char *name)
520 +{
521 +       if (!formvar) {
522 +               formvar = hash_init();
523 +               cgi_init(putvar);
524 +       }
525 +
526 +       if (!formvar || !name)
527 +               return NULL;
528 +       
529 +       return getvar_s(findvar(formvar, name));
530 +}
531 +
532 +/* function call for accessing cgi form variables */
533 +static var *getvar(var *res, var *args, int nargs)
534 +{
535 +       char *s;
536 +       char *svar;
537 +
538 +       s = getvar_s(args);
539 +       if (!s)
540 +               return res;
541 +       
542 +       svar = cgi_getvar(s);
543 +       if (!svar)
544 +               return res;
545 +
546 +       setvar_u(res, svar);
547 +
548 +       return res;
549 +}
550 +
551 +/* call an awk function without arguments by string reference */
552 +static var *call(var *res, var *args, int nargs)
553 +{
554 +       char *s = getvar_s(args);
555 +       func *f;
556 +
557 +       if (!s)
558 +               goto done;
559 +       
560 +       f = newfunc(s);
561 +       if (f && f->type == AWKFUNC && f->x.body.first)
562 +               return evaluate(f->x.body.first, res);
563 +
564 +done:
565 +       return res;
566 +}
567 +
568 +
569 +/* main awx processing function. called from awk_main() */
570 +static int do_awx(int argc, char **argv)
571 +{
572 +       int ret = -1;
573 +       var tv;
574 +       char *s = NULL;
575 +       var *layout;
576 +       var *action;
577 +       char *tmp;
578 +       int i;
579 +       
580 +       zero_out_var(&tv);
581 +
582 +       /* register awk C callbacks */
583 +       register_cfunc("getvar", getvar, 1);
584 +       register_cfunc("render", render, 1);
585 +       register_cfunc("render_layout", render_layout, 1);
586 +       register_cfunc("call", call, 1);
587 +       register_cfunc("include", include, 1);
588 +       register_cfunc("init_lang", init_lang, 1);
589 +       register_cfunc("load_lang", load_lang, 1);
590 +
591 +       if (!is_awx)
592 +               return 0;
593 +
594 +       /* fill in ARGV array */
595 +       programname = argv[1];
596 +       setvar_i(V[ARGC], argc + 1);
597 +       setari_u(V[ARGV], 0, "awx");
598 +       i = 0;
599 +       while (*argv)
600 +               setari_u(V[ARGV], ++i, *argv++);
601 +
602 +       if (argc < 2) {
603 +               fprintf(stderr, "Invalid argument.\n");
604 +               goto done;
605 +       }
606 +       
607 +       /* read the main controller source */
608 +       s = get_file(programname);
609 +       if (!s) {
610 +               fprintf(stderr, "Could not open file\n");
611 +               goto done;
612 +       }
613 +       parse_program(s+1);
614 +       free(s);
615 +
616 +
617 +       /* set some defaults for ACTION and LAYOUT, which will have special meaning */
618 +       layout = newvar("LAYOUT");
619 +       setvar_s(layout, "views/layout.ahtml");
620 +
621 +       /* run the BEGIN {} block */
622 +       evaluate(beginseq.first, &tv);
623 +
624 +       action = newvar("ACTION");
625 +       if (!(strlen(getvar_s(action)) > 0)) {
626 +               tmp = cgi_getvar("action");
627 +               if (!tmp || (strlen(tmp) <= 0))
628 +                       tmp = strdup("default");
629 +
630 +               setvar_p(action, tmp);
631 +       }
632 +       
633 +       /* call the action (precedence: begin block override > cgi parameter > "default") */
634 +       tmp = xmalloc(strlen(getvar_s(action)) + 7);
635 +       sprintf(tmp, "handle_%s", getvar_s(action));
636 +       setvar_s(action, tmp);
637 +       call(&tv, action, 1);
638 +       free(tmp);
639 +
640 +       /* render the selected layout, will do nothing if render_layout has been called from awk */
641 +       render_layout(&tv, layout, 1);
642 +
643 +       ret = 0;
644 +done:
645 +       exit(0);
646 +}
647 +
648 +/* entry point for awx applet */
649 +int awx_main(int argc, char **argv)
650 +{
651 +       is_awx = 1;
652 +       return awk_main(argc, argv);
653 +}
654 +
655 diff -purN bb.old/editors/Config.in bb.dev/editors/Config.in
656 --- bb.old/editors/Config.in    2007-01-24 22:34:50.000000000 +0100
657 +++ bb.dev/editors/Config.in    2007-03-11 06:19:51.469380160 +0100
658 @@ -12,6 +12,13 @@ config AWK
659           Awk is used as a pattern scanning and processing language.  This is
660           the BusyBox implementation of that programming language.
661  
662 +config AWX
663 +       bool "Enable awx (awk web extension)"
664 +       default n
665 +       depends on AWK
666 +       help
667 +         awx - awk web extension
668 +
669  config FEATURE_AWK_MATH
670         bool "Enable math functions (requires libm)"
671         default y
672 diff -purN bb.old/include/applets.h bb.dev/include/applets.h
673 --- bb.old/include/applets.h    2007-03-06 19:38:07.355081000 +0100
674 +++ bb.dev/include/applets.h    2007-03-07 02:12:24.280681880 +0100
675 @@ -60,6 +60,7 @@ USE_ARP(APPLET(arp, _BB_DIR_SBIN, _BB_SU
676  USE_ARPING(APPLET(arping, _BB_DIR_USR_BIN, _BB_SUID_NEVER))
677  USE_ASH(APPLET_NOUSAGE(ash, ash, _BB_DIR_BIN, _BB_SUID_NEVER))
678  USE_AWK(APPLET(awk, _BB_DIR_USR_BIN, _BB_SUID_NEVER))
679 +USE_AWX(APPLET_NOUSAGE(awx, awx, _BB_DIR_USR_BIN, _BB_SUID_NEVER)) 
680  USE_BASENAME(APPLET(basename, _BB_DIR_USR_BIN, _BB_SUID_NEVER))
681  USE_BBCONFIG(APPLET(bbconfig, _BB_DIR_BIN, _BB_SUID_NEVER))
682  //USE_BBSH(APPLET(bbsh, _BB_DIR_BIN, _BB_SUID_NEVER))
683 diff -purN bb.old/include/cgi.h bb.dev/include/cgi.h
684 --- bb.old/include/cgi.h        1970-01-01 01:00:00.000000000 +0100
685 +++ bb.dev/include/cgi.h        2007-03-11 18:58:10.708444448 +0100
686 @@ -0,0 +1,8 @@
687 +#ifndef CGI_H
688 +#define CGI_H
689 +
690 +typedef enum { FORM_VAR, COOKIE_VAR } vartype;
691 +typedef void (*var_handler) (vartype, char *, char *);
692 +int cgi_init(var_handler);
693 +
694 +#endif
695 diff -purN bb.old/libbb/cgi.c bb.dev/libbb/cgi.c
696 --- bb.old/libbb/cgi.c  1970-01-01 01:00:00.000000000 +0100
697 +++ bb.dev/libbb/cgi.c  2007-03-11 19:02:04.691873560 +0100
698 @@ -0,0 +1,457 @@
699 +/* --------------------------------------------------------------------------
700 + * functions for processing cgi form data
701 + * Copyright (C) 2007 by Felix Fietkau <nbd@openwrt.org>
702 + *
703 + * parts taken from the core of haserl.cgi - a poor-man's php for embedded/lightweight environments
704 + * $Id: haserl.c,v 1.13 2004/11/10 17:59:35 nangel Exp $ 
705 + * Copyright (c) 2003,2004    Nathan Angelacos (nangel@users.sourceforge.net)
706 + *
707 + * This program is free software; you can redistribute it and/or modify
708 + * it under the terms of the GNU General Public License as published by
709 + * the Free Software Foundation; either version 2 of the License, or
710 + * (at your option) any later version.
711 + *
712 + * This program is distributed in the hope that it will be useful,
713 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
714 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
715 + * General Public License for more details.
716 + *
717 + * You should have received a copy of the GNU General Public License
718 + * along with this program; if not, write to the Free Software
719 + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
720 + *
721 + * -----
722 + * The x2c() and unescape_url() routines were taken from  
723 + *  http://www.jmarshall.com/easy/cgi/getcgi.c.txt 
724 + * 
725 + * The comments in that text file state:
726 + *
727 + ***  Written in 1996 by James Marshall, james@jmarshall.com, except 
728 + ***  that the x2c() and unescape_url() routines were lifted directly 
729 + ***  from NCSA's sample program util.c, packaged with their HTTPD. 
730 + ***     For the latest, see http://www.jmarshall.com/easy/cgi/ 
731 + * -----
732 + *
733 + ------------------------------------------------------------------------- */
734 +
735 +#include <stdio.h>
736 +#include <unistd.h>
737 +#include <time.h>
738 +#include <sys/mman.h>
739 +#include <sys/types.h>
740 +#include <sys/wait.h>
741 +#include <sys/stat.h>
742 +#include <sys/fcntl.h>
743 +#include <stdlib.h>
744 +#include <string.h>
745 +#include <cgi.h>
746 +
747 +#ifndef MAX_UPLOAD_KB
748 +#define MAX_UPLOAD_KB 2048
749 +#endif
750 +#define TEMPDIR "/tmp"
751 +
752 +static int global_upload_size = 0;
753 +static int ReadMimeEncodedInput(char *qs);
754 +static var_handler do_putvar = NULL;
755 +
756 +/*
757 + * Convert 2 char hex string into char it represents
758 + * (from http://www.jmarshall.com/easy/cgi)
759 + */
760 +static char x2c (char *what) {
761 +       char digit;
762 +       
763 +       digit=(what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
764 +       digit *=16;
765 +       digit+=(what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
766 +
767 +       return digit;
768 +}
769 +
770 +/*
771 + * unsescape %xx to the characters they represent 
772 + */
773 +
774 +static void unescape_url (char *url) {
775 +       int  i,j;
776 +
777 +       for (i=0, j=0; url[j]; ++i, ++j) {
778 +               if ((url[i] = url[j]) == '%') {
779 +                       url[i] = x2c(&url[j+1]);
780 +                       j+=2;   
781 +               }
782 +       }
783 +       url[i]='\0';
784 +}
785 +
786 +static inline void put_var(vartype type, char *var)
787 +{
788 +       char *val;
789 +       
790 +       if (!do_putvar)
791 +               return;
792 +
793 +       val = strchr(var, '=');
794 +       if (!val)
795 +               return;
796 +       
797 +       *val = 0;
798 +       val++;
799 +       do_putvar(type, var, val);
800 +       
801 +       return;
802 +}
803 +
804 +
805 +/* CookieVars ()
806 + * if HTTP_COOKIE is passed as an environment variable,
807 + * attempt to parse its values into environment variables
808 + */
809 +static void CookieVars (void)
810 +{
811 +       char *qs;
812 +       char *token;
813 +
814 +       if (getenv("HTTP_COOKIE") != NULL)
815 +               qs=strdup(getenv("HTTP_COOKIE"));
816 +       else
817 +               return;
818 +       
819 +       /** split on; to extract name value pairs */
820 +       token=strtok(qs, ";");
821 +       while (token) {
822 +               // skip leading spaces 
823 +               while ( token[0] == ' ' ) 
824 +                       token++;
825 +               
826 +               put_var(COOKIE_VAR, token);
827 +               
828 +               token = strtok(NULL, ";");
829 +       }
830 +       free (qs);
831 +}
832 +
833 +/* 
834 + * Read cgi variables from query string, and put in environment
835 + */
836 +static int ReadCGIQueryString (void) 
837 +{
838 +       char *qs;
839 +       char *token;
840 +       int i;
841 +
842 +       if (getenv("QUERY_STRING") != NULL)
843 +               qs=strdup(getenv("QUERY_STRING"));
844 +       else
845 +               return 0;
846 +       
847 +       /* change plusses into spaces */
848 +       for (i=0; qs[i]; i++ ) { if (qs[i] == '+' ) { qs[i] = ' ';} };
849 +
850 +       /** split on & and ; to extract name value pairs */
851 +       
852 +       token=strtok(qs, "&;");
853 +       while (token) {
854 +               unescape_url(token);
855 +               put_var(FORM_VAR, token);
856 +               token=strtok(NULL, "&;");
857 +       }
858 +       free(qs);
859 +
860 +       return 0;
861 +}
862 +
863 +
864 +/* 
865 + * Read cgi variables from stdin (for POST queries)
866 + * (oh... and if its mime-encoded file upload, we save the
867 + * file to /tmp; and return the name of the tmp file
868 + * the cgi script is responsible for disposing of the tmp file
869 + */
870 +
871 +static int ReadCGIPOSTValues (void) {
872 +       char *qs;
873 +       int content_length;
874 +       int i;
875 +       char *token;
876 +
877 +
878 +       if (getenv("CONTENT_LENGTH") == NULL) 
879 +               return(-1);
880 +       else
881 +               content_length = atoi(getenv("CONTENT_LENGTH"));
882 +       
883 +       /* protect ourselves from 20GB file uploads */
884 +       if (content_length > MAX_UPLOAD_KB * 1024 ) {
885 +               /* But we need to finish reading the content */
886 +               while ( fread( &i, sizeof(int), 1, stdin) == 1 );
887 +               return -1;
888 +       }
889
890 +       if (!(qs=malloc(content_length+1)))
891 +               return -1;
892 +
893 +       /* set the buffer to null, so that a browser messing with less 
894 +          data than content_length won't buffer underrun us */
895 +       memset(qs, 0 ,content_length+1);
896 +
897 +       if ((!fread(qs,content_length,1,stdin) &&
898 +               (content_length > 0) 
899 +               && !feof(stdin))) {
900 +                       
901 +               free(qs);
902 +               return -1;
903 +       }
904 +
905 +       if (getenv("CONTENT_TYPE") && (strncasecmp(getenv("CONTENT_TYPE"), "multipart/form-data", 19) == 0)) {
906 +               /* This is a mime request, we need to go to the mime handler */
907 +               i=ReadMimeEncodedInput(qs);
908 +               free(qs);
909 +                       
910 +               return i;
911 +       }
912 +
913 +       /* change plusses into spaces */
914 +       for (i=0; qs[i]; i++ ) { if (qs[i] == '+' ) { qs[i] = ' ';} };
915 +
916 +       /** split on & and ; to extract name value pairs */
917 +       token=strtok(qs, "&;");
918 +       while (token) {
919 +               unescape_url(token);
920 +               put_var(FORM_VAR, token);
921 +               token=strtok(NULL, "&;");
922 +       }
923 +       
924 +       free(qs);
925 +       
926 +       return 0;
927 +}
928 +
929 +/*
930 + *  LineToStr - Scans char and replaces the first "\n" with a "\0";
931 + *  If it finds a "\r", it does that to; (fix DOS brokennes) returns
932 + *  the length of the string;
933 + */
934 +static int LineToStr (char *string, size_t max) {
935 +       size_t offset=0;
936 +
937 +       while ((offset < max) && (string[offset] != '\n') && (string[offset] != '\r'))
938 +               offset++;
939 +
940 +       if (string[offset] == '\r') {
941 +               string[offset]='\0';
942 +               offset++;
943 +       }
944 +       if (string[offset] == '\n') {
945 +               string[offset]='\0';
946 +               offset++;
947 +       }
948 +
949 +       return offset;
950 +}
951 +
952 +
953 +/*
954 + * ReadMimeEncodedInput - handles things that are mime encoded
955 + * takes a pointer to the input; returns 0 on success
956 + */
957 +
958 +static int ReadMimeEncodedInput(char *qs) 
959 +{
960 +       char    *boundary;
961 +       char    *ct;
962 +       int     i;
963 +       int     datastart;
964 +       size_t  cl;
965 +       size_t  offset;
966 +       char    *envname;
967 +       char    *filename;
968 +       char    *ptr;
969 +       int     line;
970 +       char    tmpname[] = TEMPDIR "/XXXXXX";
971 +       int     fd;
972 +       /* we should only get here if the content type was set. Segfaults happen
973 +          if Content_Type is null */
974 +
975 +       if (getenv("CONTENT_LENGTH") == NULL)
976 +               /* No content length?! */
977 +               return(-1);
978 +
979 +       cl=atoi(getenv("CONTENT_LENGTH"));
980 +       
981 +       /* we do this 'cause we can't mess with the real env. variable - it would
982 +        * overwrite the environment - I tried.
983 +        */
984 +       i=strlen(getenv("CONTENT_TYPE"))+1;
985 +       ct=malloc(i);
986 +       if (ct)
987 +               memcpy(ct, getenv("CONTENT_TYPE"), i);
988 +       else
989 +               return(-1);
990 +       
991 +       i=(int) NULL;
992 +       if (ct != NULL) {
993 +               while (i < strlen(ct) && (strncmp("boundary=", &ct[i], 9) != 0)) 
994 +                       i++;
995 +       }
996 +       if (i == strlen(ct)) {
997 +               /* no boundary informaiton found */
998 +               free(ct);
999 +               return -1;
1000 +       }
1001 +       boundary=&ct[i+7];
1002 +       /* add two leading -- to the boundary */
1003 +       boundary[0]='-';
1004 +       boundary[1]='-';
1005 +       
1006 +       /* begin the big loop.  Look for:
1007 +               --boundary
1008 +               Content-Disposition: form-data;  name="......." 
1009 +               ....
1010 +               <blank line>
1011 +               content
1012 +               --boundary
1013 +               Content-Disposition: form-data; name="....." filename="....."
1014 +               ...
1015 +               <blank line>
1016 +               --boundary--
1017 +               eof
1018 +       */
1019 +
1020 +       offset=0;
1021 +       while (offset < cl) {
1022 +               /* first look for boundary */
1023 +               while ((offset < cl) && (memcmp(&qs[offset], boundary, strlen(boundary)))) 
1024 +                       offset++;
1025 +
1026 +               /* if we got here and we ran off the end, its an error          */
1027 +               if (offset >= cl) { 
1028 +                       free(ct);
1029 +                       return -1;
1030 +               }
1031 +
1032 +               /* if the two characters following the boundary are --,         */ 
1033 +               /* then we are at the end, exit                                 */
1034 +               if (memcmp(&qs[offset+strlen(boundary)], "--", 2) == 0) {
1035 +                       offset+=2;
1036 +                       break;
1037 +               }
1038 +               /* find where the offset should be */
1039 +               line=LineToStr(&qs[offset], cl-offset);
1040 +               offset+=line;
1041 +                               
1042 +               /* Now we're going to look for content-disposition              */ 
1043 +               line=LineToStr(&qs[offset], cl-offset);
1044 +               if (strncasecmp(&qs[offset], "Content-Disposition", 19) != 0) {
1045 +                       /* hmm... content disposition was not where we expected it */
1046 +                       free(ct);
1047 +                       return -1;
1048 +               }
1049 +               /* Found it, so let's go find "name="                           */
1050 +               if (!(envname=strstr(&qs[offset], "name="))) {
1051 +                       /* now name= is missing?!                               */
1052 +                       free(ct);
1053 +                       return(-1);
1054 +               } else
1055 +                       envname+=6;
1056 +
1057 +               /* is there a filename tag?                                     */
1058 +               if ((filename=strstr(&qs[offset], "filename="))!= NULL)
1059 +                       filename+=10;
1060 +               else
1061 +                       filename=NULL;
1062 +               
1063 +               /* make envname and filename ASCIIZ                             */
1064 +               for (i=0; (envname[i] != '"') && (envname[i] != '\0'); i++);
1065 +               
1066 +               envname[i] = '\0';
1067 +               if (filename) {
1068 +                       for (i=0; (filename[i] != '"') && (filename[i] != '\0'); i++);
1069 +                       filename[i] = '\0';
1070 +               }
1071 +               offset+=line;
1072 +               
1073 +               /* Ok, by some miracle, we have the name; let's skip till we    */
1074 +               /* come to a blank line                                         */
1075 +               line=LineToStr(&qs[offset], cl-offset);
1076 +               while (strlen(&qs[offset]) > 1) {
1077 +                       offset+=line;
1078 +                       line=LineToStr(&qs[offset], cl-offset);
1079 +               }
1080 +               offset+=line;
1081 +               datastart=offset;
1082 +               /* And we go back to looking for a boundary */
1083 +               while ((offset < cl) && (memcmp(&qs[offset], boundary, strlen(boundary))))
1084 +                       offset++;
1085 +
1086 +               /* strip [cr] lf */
1087 +               if ((qs[offset-1] == '\n') && (qs[offset-2] == '\r'))
1088 +                       offset-=2; 
1089 +               else
1090 +                       offset-=1;
1091 +
1092 +               qs[offset]=0;
1093 +
1094 +               /* ok, at this point, we know where the name is, and we know    */
1095 +               /* where the content is... we have to do one of two things      */
1096 +               /* based on whether its a file or not                           */
1097 +               if (filename==NULL) { /* its not a file, so its easy            */
1098 +                       /* just jam the content after the name          */
1099 +                       memcpy(&envname[strlen(envname)+1], &qs[datastart], offset-datastart+1);
1100 +                       envname[strlen(envname)]='=';
1101 +                       put_var(FORM_VAR, envname);
1102 +               } else {        /* handle the fileupload case           */
1103 +                       if (offset-datastart) {  /* only if they uploaded */
1104 +                               if ( global_upload_size == 0 ) {
1105 +                                       return -1;
1106 +                               }
1107 +                               /*  stuff in the filename */
1108 +                               ptr= calloc ( sizeof (char), strlen(envname)+strlen(filename)+2+5 );
1109 +                               sprintf (ptr, "%s_name=%s", envname, filename);
1110 +                               put_var(FORM_VAR, ptr);
1111 +                               free(ptr);
1112 +                                               
1113 +                               fd=mkstemp(tmpname);
1114 +                               
1115 +                               if (fd == -1)
1116 +                                       return(-1);
1117 +
1118 +                               write(fd, &qs[datastart], offset-datastart);
1119 +                               close(fd);
1120 +                               ptr= calloc (sizeof(char), strlen(envname)+strlen(tmpname)+2);
1121 +                               sprintf (ptr, "%s=%s", envname, tmpname);
1122 +                               put_var(FORM_VAR, ptr);
1123 +                               free(ptr);
1124 +                       }
1125 +               }
1126 +       }
1127 +       free(ct);
1128 +       return 0;
1129 +}
1130 +
1131 +       
1132 +/*-------------------------------------------------------------------------
1133 + *
1134 + * Main 
1135 + *
1136 + *------------------------------------------------------------------------*/
1137 +
1138 +int cgi_init(var_handler putvar_handler)
1139 +{
1140 +       int     retval = 0;
1141 +       
1142 +       do_putvar = putvar_handler;
1143 +
1144 +       /* Read the current environment into our chain */
1145 +       CookieVars();
1146 +       if (getenv("REQUEST_METHOD")) {
1147 +               if (strcasecmp(getenv("REQUEST_METHOD"), "GET") == 0)
1148 +                       retval = ReadCGIQueryString();
1149 +
1150 +               if (strcasecmp(getenv("REQUEST_METHOD"), "POST") == 0)
1151 +                       retval = ReadCGIPOSTValues();
1152 +       }
1153 +
1154 +       return retval;
1155 +} 
1156 diff -purN bb.old/libbb/Kbuild bb.dev/libbb/Kbuild
1157 --- bb.old/libbb/Kbuild 2007-03-06 19:38:07.361080000 +0100
1158 +++ bb.dev/libbb/Kbuild 2007-03-11 18:40:51.384445712 +0100
1159 @@ -118,3 +118,6 @@ lib-$(CONFIG_GREP) += xregcomp.o
1160  lib-$(CONFIG_MDEV) += xregcomp.o
1161  lib-$(CONFIG_LESS) += xregcomp.o
1162  lib-$(CONFIG_DEVFSD) += xregcomp.o
1163 +
1164 +lib-$(CONFIG_AWX) += cgi.o
1165 +