File: cgi.pike

package info (click to toggle)
roxen 1.2beta2-3
  • links: PTS
  • area: contrib
  • in suites: slink
  • size: 16,920 kB
  • ctags: 8,589
  • sloc: ansic: 89,632; asm: 8,431; sh: 2,915; makefile: 1,784; cpp: 377
file content (942 lines) | stat: -rw-r--r-- 25,381 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
// This is a roxen module. Copyright  1996 - 1998, Idonex AB.

// Support for the <a
// href="http://hoohoo.ncsa.uiuc.edu/docs/cgi/interface.html">CGI/1.1
// interface</a> (and more, the documented interface does _not_ cover
// the current implementation in NCSA/Apache)

string cvs_version = "$Id: cgi.pike,v 1.87 1998/05/22 21:03:59 grubba Exp $";
int thread_safe=1;

#include <module.h>

inherit "module";
inherit "roxenlib";

// #define CGI_DEBUG

import Simulate;

static mapping env=([]);
static array runuser;

import String;
import Stdio;

mapping my_build_env_vars(string f, object id, string|void path_info)
{
  mapping new = build_env_vars(f, id, path_info);

  if(QUERY(Enhancements))
    new |= build_roxen_env_vars(id);
  
  if(id->misc->ssi_env)
    new |= id->misc->ssi_env;
  
  if(QUERY(rawauth) && id->rawauth) {
    new["HTTP_AUTHORIZATION"] = (string)id->rawauth;
  } else {
    m_delete(new, "HTTP_AUTHORIZATION");
  }
  if(QUERY(clearpass) && id->auth && id->realauth ) {
    new["REMOTE_USER"] = (id->realauth/":")[0];
    new["REMOTE_PASSWORD"] = (id->realauth/":")[1];
  } else {
    m_delete(new, "REMOTE_PASSWORD");
  }

  new["AUTH_TYPE"] = "Basic";

  return new|env|(QUERY(env)?getenv():([]));
}


void nil(){}

#define ipaddr(x,y) (((x)/" ")[y])

int uid_was_zero()
{
  return !(getuid() == 0); // Somewhat misnamed function.. :-)
}

int run_as_user_enabled()
{
  // Return 0 if run_as_user is enabled...
  return(uid_was_zero() || !QUERY(user));
}

void create()
{
  defvar("Enhancements", 1, "Roxen CGI Enhancements", TYPE_FLAG|VAR_MORE,
	 "If defined, Roxen will export a few extra varaibles, namely "
	 "VAR_variable_name: Parsed form variable (like CGI parse)<br>"
	 "QUERY_variable_name: Parsed form variable<br>"
	 "VARIABLES: A space separated list of all form variables<br>"
	 "PRESTATE_name: True if the prestate is present<br>"
	 "PRESTATES: A space separated list of all states");

  defvar("mountpoint", "/cgi-bin/", "CGI-bin path", TYPE_LOCATION, 
	 "This is where the module will be inserted in the "
	 "namespace of your server. The module will, per default, also"
	 " service one or more extensions, from anywhere in the "
	 "namespace.");

  defvar("searchpath", "NONE/", "Search path", TYPE_DIR,
	 "This is where the module will find the files in the <b>real</b> "
	 "file system.");

  defvar("noexec", 1, "Ignore non-executable files", TYPE_FLAG,
	 "If this flag is set, non-executable files will be returned "
	 "as normal files to the client.");

  defvar("ls", 0, "Allow listing of cgi-bin directory", TYPE_FLAG,
	 "If set, the users can get a listing of all files in the CGI-bin "
	 "directory.");

  defvar("ex", 1, "Handle *.cgi", TYPE_FLAG,
	 "Also handle all '.cgi' files as CGI-scripts, as well "
	 " as files in the cgi-bin directory. This emulates the behaviour "
	 "of the NCSA server (the extensions to handle can be set in the "
	 "CGI-script extensions variable).");

  defvar("ext", ({"cgi"}), "CGI-script extensions", TYPE_STRING_LIST,
	 "All files ending with these extensions, will be parsed as "+
	 "CGI-scripts.");

  defvar("env", 0, "Pass environment variables", TYPE_FLAG|VAR_MORE,
	 "If this is set, all environment variables will be passed to CGI "
	 "scripts, not only those defined in the CGI/1.1 standard (with "
	 "Roxen CGI enhancements added, if defined). This include LOGNAME "
	 "and all the other ones (For a quick test, try this script with "
	 "and without this variable set:"
	 "<pre>"
	 "#!/bin/sh\n\n"
         "echo Content-type: text/plain\n"
	 "echo ''\n"
	 "env\n"
	 "</pre>)");

  defvar("err", 0, "Send stderr to client", TYPE_FLAG|VAR_MORE,
	 "It you set this, standard error from the scripts will be redirected"
	 " to the client instead of the logs/debug/[name-of-configdir].1 "
	 "log.\n");

  defvar("rawauth", 0, "Raw user info", TYPE_FLAG|VAR_MORE,
	 "If set, the raw, unparsed, user info will be sent to the script, "
	 " in the HTTP_AUTHORIZATION environment variable. This is not "
	 "recommended, but some scripts need it. Please note that this "
	 "will give the scripts access to the password used.");

  defvar("clearpass", 0, "Send decoded password", TYPE_FLAG|VAR_MORE,
	 "If set, the variable REMOTE_PASSWORD will be set to the decoded "
	 "password value.");

  defvar("use_wrapper", (getcwd()==""?0:1), "Use cgi wrapper", 
	 TYPE_FLAG|VAR_EXPERT,
	 "If set, an external wrapper will be used to start the CGI script.\n"
	 "<br>This will:<ul>\n"
	 "<li>Enable Roxen to send redirects from cgi scripts\n"
	 "<li>Work around the fact that stdout is set to nonblocking mode\n"
	 "    for the script. It simply will _not_ work for most scripts\n"
	 "<li>Make scripts start somewhat slower...\n"
	 "</ul>"
	 "<p>"
	 "You only need this if you plan to send more than 8Kb of data from "
	 " a script, or use Location: headers in a non-nph script.\n"
	 "<p>More or less always, that is..");

  defvar("wrapper", "bin/cgi", "The wrapper to use",
	 TYPE_STRING|VAR_EXPERT,
	 "This is the pathname of the wrapper to use.\n");
  
  defvar("runuser", "", "Run scripts as", TYPE_STRING,
	 "If you start roxen as root, and this variable is set, CGI scripts "
	 "will be run as this user. You can use either the user name or the "
	 "UID. Note however, that if you don't have a working user database "
	 "enabled, only UID's will work correctly. If unset, scripts will "
	 "be run as nobody.", 0, uid_was_zero);

  defvar("user", 1, "Run user scripts as owner", TYPE_FLAG,
	 "If set, scripts in the home-dirs of users will be run as the "
	 "user. This overrides the Run scripts as variable.", 0, uid_was_zero);

#if constant(Process.create_process)
  defvar("setgroups", 1, "Set the supplementary group access list", TYPE_FLAG,
	 "If set, the supplementary group access list will be set for "
	 "the CGI scripts. This can slow down CGI-scripts significantly "
	 "if you are using eg NIS+. If not set, the supplementary group "
	 "access list will be cleared.");
#endif /* constant(Process.create_process) */

  defvar("allow_symlinks", 1, "Allow symlinks", TYPE_FLAG,
	 "If set, allows symbolic links to binaries owned by the directory "
	 "owner. Other symlinks are still disabled.<br>\n"
	 "NOTE: This option only has effect if scripts are run as owner.",
	 0, run_as_user_enabled);

  defvar("nice", 1, "Nice value", TYPE_INT|VAR_MORE,
	 "The nice level to use when running scripts. "
	 "20 is nicest, and 0 is the most aggressive available to "
	 "normal users.");
  
  defvar("coresize", 0, "Limits: Core dump size", TYPE_INT|VAR_MORE,
	 "The maximum size of a core-dump, in 512 byte blocks."
	 " -2 is unlimited.");

  defvar("maxtime", 60, "Limits: Maximum CPU time", TYPE_INT_LIST|VAR_MORE,
	 "The maximum CPU time the script might use in seconds. -2 is unlimited.",
	 ({ -2, 10, 30, 60, 120, 240 }));

  defvar("kill_call_out", 0, "Limits: Time before killing scripts",
	 TYPE_INT_LIST|VAR_EXPERT,
	 "The maximum real time the script might run in minutes before it's "
	 "killed. 0 means unlimited.", ({ 0, 1, 2, 3, 4, 5, 7, 10, 15 }));

  defvar("datasize", -2, "Limits: Memory size", TYPE_INT|VAR_EXPERT,
	 "The maximum size of the memory used, in Kb. -2 is unlimited.");

  defvar("filesize", -2, "Limits: Maximum file size", TYPE_INT|VAR_EXPERT,
	 "The maximum size of any file created, in 512 byte blocks. -2 "
	 "is unlimited.");

  defvar("open_files", 64, "Limits: Maximum number of open files",
	 TYPE_INT_LIST|VAR_MORE,
	 "The maximum number of files the script can keep open at any time.",
	 ({64,128,256,512,1024,2048}));

  defvar("stack", -2, "Limits: Stack size", TYPE_INT|VAR_EXPERT,
	 "The maximum size of the stack used, in b. -2 is unlimited.");

  defvar("extra_env", "", "Extra environment variables", TYPE_TEXT_FIELD|VAR_MORE,
	 "Extra variables to be sent to the script, format:<pre>"
	 "NAME=value\n"
	 "NAME=value\n"
	 "</pre>Please note that normal CGI variables will override these.");
}


mixed *register_module()
{
  return ({ 
    MODULE_LAST | MODULE_LOCATION | MODULE_FILE_EXTENSION,
    "CGI executable support", 
    "Support for the <a href=\"http://hoohoo.ncsa.uiuc.edu/docs/cgi/"
      "interface.html\">CGI/1.1 interface</a>, and more. It is too bad "
      "that the CGI specification is a moving target, it is hard to "
      "implement a fully compatible copy of it."
    });
}

string check_variable(string name, string value)
{
  if(name == "mountpoint" && value[-1] != '/')
    call_out(set, 0, "mountpoint", value+"/");
}

static string search_path;

void start(int n, object conf)
{
  if(n==2) return;

  if(intp(QUERY(wrapper)))
    QUERY(wrapper)="bin/cgi";

  if(!conf) conf=roxen->current_configuration;
  if(!conf) return;

  string tmp;
  array us;
  if(!conf) // When reloading, no conf is sent.
    return; 
  search_path = query("searchpath");
#if efun(getpwnam)
  if(us = getpwnam(  QUERY(runuser) ))
    runuser = ({ (int)us[2], (int)us[3] });
  else
#endif
    if(strlen(QUERY(runuser)))
      if (sizeof(us = (QUERY(runuser)/":")) == 2) 
	runuser = ({ (int)us[0], (int)us[1] });
      else
	runuser = ({ (int)QUERY(runuser), (int)QUERY(runuser) });

  
  tmp=conf->query("MyWorldLocation");
  sscanf(tmp, "%*s//%s", tmp);
  sscanf(tmp, "%s:", tmp);
  sscanf(tmp, "%s/", tmp);

  env["SERVER_NAME"]=tmp;
  env["SERVER_SOFTWARE"]=roxen->version();
  env["GATEWAY_INTERFACE"]="CGI/1.1";
  env["SERVER_PROTOCOL"]="HTTP/1.0";
  env["SERVER_URL"]=conf->query("MyWorldLocation");
  env["AUTH_TYPE"]="Basic";
  env["ROXEN_CGI_NICE_LEVEL"] = (string)query("nice");
  env["ROXEN_CGI_LIMITS"] = ("core_dump_size:"+query("coresize")+
			     ";time_cpu:"+query("maxtime")+
			     ";data_size:"+query("datasize")+
			     ";file_size:"+query("filesize")+
			     ";open_files:"+query("open_files")+
			     ";stack_size:"+query("stack"));
  
  us = ({ "", "" });

  foreach(query("extra_env")/"\n", tmp)
    if(sscanf(tmp, "%s=%s", us[0], us[1])==2)
      env[us[0]] = us[1];
}

string query_location() 
{ 
  return QUERY(mountpoint); 
}

string query_name() 
{ 
  return sprintf("CGI-bin path: <i>%s</i>, CGI-searchpath: <i>%s</i>"+
		 (QUERY(ex)?", CGI-extensions: <i>%s</i>":""),
		 QUERY(mountpoint), QUERY(searchpath),
		 implode_nicely(QUERY(ext)));
}

static inline array make_args( string rest_query )
{
  if(!rest_query || !strlen(rest_query))
    return (array (string))({});  return replace(rest_query,"\000", " ")/" ";
}

array stat_file(string f, object id) 
{
#ifdef CGI_DEBUG
  roxen_perror("CGI: stat_file(\"" + f + "\")\n");
#endif /* CGI_DEBUG */

  return file_stat(search_path+f);
}

string real_file( mixed f, mixed id )
{
#ifdef CGI_DEBUG
  roxen_perror("CGI: real_file(\"" + f + "\")\n");
#endif /* CGI_DEBUG */

  if(stat_file( f, id )) 
    return search_path+f;
}

array find_dir(string f, object id) 
{
#ifdef CGI_DEBUG
  roxen_perror("CGI: find_dir(\"" + f + "\")\n");
#endif /* CGI_DEBUG */

  if(QUERY(ls)) 
    return get_dir(search_path+f);
}


array extract_path_info(string f, string path)
{
  string hmm, tmp_path=path, path_info="";
  int found = 0;
  
  foreach(f/"/", hmm)
  {
    if(!found)
    {
      switch(file_size(tmp_path + hmm))
      {
       case -1:
	return 0;

       case -2:
	 tmp_path += hmm + "/";
	break;
	
       default:
	f = tmp_path + hmm;
	found = 1;
	break;
      }
    } else {
      path_info += "/" + hmm;
    }
  }
  if(!found)  return 0;
  return ({ path_info, f });
}

class spawn_cgi
{
  // This program asserts that fork() is called from the backend to
  // avoid some problems with threads, fork() and buggy OS's.
  string wrapper;
  string f;
  array(string) args;
  mapping env;
  string wd;
  int|string uid;
  object pipe1, pipe2;	// Stdout/Stderr for the CGI
  object pipe3, pipe4;	// Stdin for the CGI
  int kill_call_out;
  int dup_err;
  int setgroups;

  void got_some_data(object to, string d)
  {
    to->write( d );
  }

  void cgi_fail(int errcode, string err)
  {
    string to_write = sprintf("HTTP/1.0 %d %s\r\n"
			      "\r\n"
			      "<title>%s</title>\n"
			      "<h2>%s</h2>\n", errcode, err, err, err);

    object(Stdio.File) output = Stdio.File("stdout");
    int bytes;
    
    while ((bytes = output->write(to_write)) > 0) {
      if ((to_write = to_write[bytes..]) == "") {
	break;
      }
    }

    exit(0);
  }
  
  void do_cgi()
  {
    int pid;
#ifdef CGI_DEBUG
    roxen_perror("do_cgi()\n");
#endif /* CGI_DEBUG */

#if constant(Process.create_process)

    if(wrapper) {
      array us;
      wrapper = combine_path(getcwd(), wrapper);

      if(!(us = file_stat(wrapper)) ||
	 !(us[0]&0111)) {
	report_error(sprintf("Wrapper \"%s\" doesn't exist, or "
			     "is not executable\n", wrapper));
	return;
      }
      args = ({ wrapper, f }) + args;
    } else {
      args = ({ f }) + args;
    }

    /* Be sure they are closed in the forked copy */
    pipe2->set_close_on_exec(1);
    pipe4->set_close_on_exec(1);
    mapping options = ([ "cwd":wd,
			 "stdin":pipe3,
			 "stdout":pipe1,
			 "env":env,
    ]);

    if (!getuid()) {
      options["uid"] = uid || 65534;
    }

    if (dup_err) {
      options["stderr"] = pipe1;
    }

    if (!setgroups) {
      options["noinitgroups"] = 1;
#if constant(cleargroups)
      options["setgroups"] = ({});
#endif /* constant(cleargroups) */
    }

#ifdef CGI_DEBUG
    roxen_perror(sprintf("create_process(%O, %O)...\n", args, options));
#endif /* CGI_DEBUG */

    object proc;
    mixed err = catch {
      proc = Process.create_process(args, options);
    };

    /* We don't want to keep these. */
    pipe1->close();
    pipe3->close();

    if (err) {
      int e = errno();
#if constant(strerror)
      report_error(sprintf("CGI: create_process() failed:\n"
			   "errno: %d: %s\n"
			   "%s\n",
			   e, strerror(e),
			   describe_backtrace(err)));
#else /* !constant(strerror) */
      report_error(sprintf("CGI: create_process() failed:\n"
			   "errno: %d\n"
			   "%s\n",
			   e, describe_backtrace(err)));
#endif /* constant(strerror) */
    }

    if(proc && kill_call_out) {
      call_out(lambda (object proc) {
	object privs;
	catch(privs = Privs("Killing CGI script."));
	int killed;
	
	killed = kill(proc, signum("SIGINTR"));
	if(!killed)
	  killed = kill(proc, signum("SIGHUP"));
	if(!killed)
	  killed = kill(proc, signum("SIGKILL"));
	if(killed)
	  roxen_perror("Killed CGI pid "+proc->pid()+"\n");
      }, kill_call_out * 60 , proc);
    }
#else /* !constant(Process.create_process) */
    if (!(pid = fork())) {
      mixed err = catch {
	array us;
	/* The COREDUMPSIZE should be set to zero here !!
	 * This should be done at least before the change of directory
	 */
	string oldwd = getcwd() + "/";
	destruct(pipe2);
	if (pipe4)
	  destruct(pipe4);
	
	pipe3->dup2(Stdio.File("stdin"));
	destruct(pipe3);

	object privs;
	if (!getuid()) {
	  // We are running as root -- change!
	  privs = Privs("CGI script", uid || 65534);
	} else {
	  // Try to change user anyway, but don't throw an error if we fail.
	  catch(privs = Privs("CGI script", uid || 65534));
	}
	int uid = geteuid() || 65534;
	int gid = getegid() || 65534;
	// Can't change uid & gid to euid & egid directly on some OS's
	// -- stupid.
	seteuid(0);
	setgid(gid);
	setegid(gid);
	setuid(uid);
	seteuid(uid);

	// Moved here to avoid output by Privs().
	pipe1->dup2(Stdio.File("stdout"));
	if(dup_err)
	  pipe1->dup2(Stdio.File("stderr"));
	destruct(pipe1);

#ifdef DEBUG
	if (getuid() != uid) {
	  roxen_perror("CGI: Failed to change uid! uid:%d target uid:%d\n",
		       getuid(), uid);
	}
	if (getgid() != gid) {
	  roxen_perror("CGI: Failed to change gid! gid:%d target gid:%d\n",
		       getgid(), gid);
	}
#endif /* DEBUG */
	
	/* Now that the correct privileges are set, the current working
	 * directory can be changed. This implies a check for user permissions
	 * Also some technical requirements for execution can be checked
	 * before control is given to the wrapper or the script.
	 */
	if(!cd(wd) ||
	   !(us = file_stat(f)) ||
	   !((us[0]&0111) ||
	     ((us[0]&0100) && (uid == us[5])) ||
	     (us[0]&0444) ||
	     ((us[0]&0400) && (uid == us[5])))) {
	  cgi_fail(403, "File exists, but access forbidden by user");
	}
	
	if(wrapper) {
	  if(!(us = file_stat(combine_path(oldwd, wrapper))) ||
	     !(us[0]&0111)) {
	    cgi_fail(403,
		     "Wrapper exists, but access forbidden for user");
	  }
	  exece(combine_path(oldwd, wrapper), ({ f }) + args, env);
	} else {
	  exece(f, args, env);
	}
      };
      catch(roxen_perror("CGI: Exec failed!\n%O\n",
			 describe_backtrace((array)err)));
      exit(0);
    } else if (pid == -1) {
      // fork() failed!
      int e = errno();
#if constant(strerror)
      report_error(sprintf("CGI: fork() failed. No more processes?\n"
			   "errno: %d: %s\n", e, strerror(e)));
#else /* !constant(strerror) */
      report_error(sprintf("CGI: fork() failed. No more processes?\n"
			   "errno: %d\n", e));
#endif /* constant(strerror) */
      pipe1->write("HTTP/1.0 500 No more processes\r\n"
		   "\r\n"
		   "<title>CGI failed: No more processes</title>\n"
		   "<h2>CGI failed: No more processes</title>\n");
      destruct(pipe1);
      destruct(pipe2);
      destruct(pipe3);
      destruct(pipe4);
      return;
    }

    destruct(pipe1);
    destruct(pipe3);

    if(kill_call_out) {
      call_out(lambda (int pid) {
	object privs;
	catch(privs = Privs("Killing CGI script."));
	int killed;
	killed = kill(pid, signum("SIGINTR"));
	if(!killed)
	  killed = kill(pid, signum("SIGHUP"));
	if(!killed)
	  killed = kill(pid, signum("SIGKILL"));
	if(killed)
	  roxen_perror("Killed CGI pid "+pid+"\n");
      }, kill_call_out * 60 , pid);
    }
#endif /* !constant(Process.create_process) */

  }
  
  void create(string wrapper_, string f_, array(string) args_, mapping env_,
	      string wd_, int|string uid_, object pipe1_, object pipe2_,
	      object pipe3_, object pipe4_, int dup_err_, int kill_call_out_,
	      int setgroups_)
  {
#ifdef CGI_DEBUG
    roxen_perror(sprintf("spawn_cgi(%O, %O, %O, %O, "
			 "%O, %O, X, X, "
			 "X, X, %O, %O, %O)\n",
			 wrapper_, f_, args_, env_,
			 wd_, uid_, dup_err_, kill_call_out_, setgroups_));
#endif /* CGI_DEBUG */
    wrapper = wrapper_;
    f = f_;
    args = args_;
    env = env_;
    wd = wd_;
    uid = uid_;
    pipe1 = pipe1_;
    pipe2 = pipe2_;
    pipe3 = pipe3_;
    pipe4 = pipe4_;
    dup_err = dup_err_;
    kill_call_out = kill_call_out_;
    setgroups = setgroups_;
#ifdef THREADS
    call_out(do_cgi, 0);
#else /* THREADS */
    do_cgi();
#endif /* THREADS */
  }
};

// Used to close the stdin of the CGI-script.
class closer
{
  object fd;
  void close_cb()
  {
    fd->close();
  }
  void create(object fd_)
  {
    fd = fd_;
    fd->set_nonblocking(close_cb, close_cb, close_cb);
  }
};

// Used to send some data to the CGI-script.
class sender
{
  string to_send;
  object fd;

  void write_cb()
  {
    if (sizeof(to_send)) {
      int len = fd->write(to_send);
      if ((to_send = to_send[len..]) == "") {
	fd->close();
      }
    } else {
      fd->close();
    }
  }
  void close_cb()
  {
    fd->close();
  }
  void create(object fd_, string to_send_)
  {
    fd = fd_;
    // fd->close("r");	// We aren't interrested in reading from the fd.
    to_send = to_send_;
    fd->set_nonblocking(0, write_cb, close_cb);
  }
};

mixed low_find_file(string f, object id, string path)
{
  array tmp2;
  object pipe1, pipe2;
  object pipe3, pipe4;
  string path_info, wd;
  int pid;

#ifdef CGI_DEBUG
  roxen_perror("CGI: find_file(\"" + f + "\")...\n");
#endif /* CGI_DEBUG */

  if(id->misc->path_info && strlen(id->misc->path_info))
    // From last_try code below..
    path_info = id->misc->path_info;
  else 
  {
    if(!(tmp2 = extract_path_info( f, path )))
    {
      if(file_size( path + f ) == -2)
	return -1; // It's a directory...
      return 0;
    }
    path_info = tmp2[0];
    f = tmp2[1];
  }
  
#ifdef CGI_DEBUG
  roxen_perror("CGI: Starting '"+f+"'...\n");
#endif

  wd = dirname(f);
  if ((!(pipe1=Stdio.File())) || (!(pipe2=pipe1->pipe()))) {
    int e = errno();
#if constant(strerror)
    report_error(sprintf("cgi->find_file(\"%s\"): Can't open pipe "
			 "-- Out of fd's?\n"
			 "errno: %d: %s\n", f, e, strerror(e)));
#else /* !constant(strerror) */
    report_error(sprintf("cgi->find_file(\"%s\"): Can't open pipe "
			 "-- Out of fd's?\n"
			 "errno: %d\n", f, e));
#endif /* constant(strerror) */
    return(0);
  }
  pipe2->set_blocking(); pipe1->set_blocking();
  pipe2->set_id(pipe2);

  if ((!(pipe3=Stdio.File())) || (!(pipe4=pipe3->pipe()))) {
    int e = errno();
#if constant(strerror)
    report_error(sprintf("cgi->find_file(\"%s\"): Can't open input pipe "
			 "-- Out of fd's?\n"
			 "errno: %d: %s\n", f, e, strerror(e)));
#else /* !constant(strerror) */
    report_error(sprintf("cgi->find_file(\"%s\"): Can't open input pipe "
			 "-- Out of fd's?\n"
			 "errno: %d\n", f, e));
#endif /* constant(strerror) */
    return(0);
  }
  pipe4->set_blocking(); pipe3->set_blocking();
  pipe4->set_id(pipe4);

  mixed uid;
  array us;
  if(query("noexec"))
  {
    us = file_stat(f);
    if(us && !(us[0]&0111)) // Not executable...
      return open(f,"r");
  }
  
  if(!getuid())
  {
    if(QUERY(user) && id->misc->is_user &&
       (us = file_stat(id->misc->is_user)) &&
       (us[5] >= 10)) {
      // Scan for symlinks
      string fname = "";
      array a,b;
      foreach(id->misc->is_user/"/", string part) {
	fname += part;
	if ((fname != "") &&
	    ((!(a = file_stat(fname, 1))) ||
	     ((< -3, -4 >)[a[1]]))) {
	  // Symlink or device encountered.
	  // Don't allow symlinks from directories not owned by the
	  // same user as the file itself.
	  // Assume that symlinks from directories owned by users 1-9 are safe.
	  if (!a || (a[1] == -4) ||
	      !b || ((b[5] != us[5]) && (b[5] >= 10)) ||
	      !QUERY(allow_symlinks)) {
	    report_notice(sprintf("CGI: Bad symlink or device encountered: "
				  "\"%s\"\n", fname));
	    fname = 0;
	    break;
	  }
	  a = file_stat(fname);		// Get the permissions from the directory.
	} else {
	  a = file_stat("/");
	}
	b = a;
	fname += "/";
      }
      if (fname) {
	uid = us[5..6];
      }
    }
    else if(runuser)
      uid = runuser;
  }
  if(!uid)
    uid = "nobody";

  if (arrayp(uid)) {
    uid = uid[0];
  }

  object cgi = spawn_cgi(QUERY(use_wrapper) && (QUERY(wrapper) || "/bin/cgi"),
			 f, make_args(id->rest_query),
			 my_build_env_vars(f, id, path_info),
			 wd, uid, pipe1, pipe2, pipe3, pipe4, QUERY(err),
			 QUERY(kill_call_out),
#if constant(Process.create_process)
			 QUERY(setgroups)
#else /* !constant(Process.create_process) */
			 /* Ignored anyway */
			 0
#endif /* constant(Process.create_process) */
	  );
  
  if(id->my_fd && id->data) {
    sender(pipe4, id->data);

    id->my_fd->set_id( pipe4 );                       // for put.. post?
    id->my_fd->set_read_callback(cgi->got_some_data); // lets try, atleast..
    id->my_fd->set_nonblocking();
  } else {
    closer(pipe4);
  }
  return http_stream(pipe2);
}

mixed find_file(string f, object id)
{
  return(low_find_file(f, id, search_path));
}

array (string) query_file_extensions()
{
  return query("ext");
}

mapping handle_file_extension(object o, string e, object id)
{
  string f, q, w;
  mixed toret;
  string path;
  mixed err;


  if(!QUERY(ex))
    return 0;

  if(QUERY(noexec) && !(o->stat()[0]&0111))
    return 0;

  if(id->realfile) 
  {
    array c;

    c=id->realfile/"/";
    
    // Handle the request with the location code.
    // This is done by setting the cgi-bin dir to the path of the 
    // script, and then calling the location dependant code.
    //
    // This isn't thread-safe (discovered by Wilhelm Khler), so send
    // the path to be used directly to find_file() instead.
    destruct( o );
    o = 0;
    path=c[0..sizeof(c)-2]*"/" + "/";

    //  use full path in case of path_info                         1-Nov-96-wk
    if(id->misc->path_info)
      err=catch(toret = low_find_file(id->realfile, id, path));
    else
      err=catch(toret = low_find_file(c[-1], id, path));

    if(err) throw(err);
    return toret;
  }

  // Fallback for odd location modules that does not set the
  // realfile entry in the id object.
  // This could be useful when the data is not really a file, but instead
  // generated internally, or if it is a socket.
#ifdef CGI_DEBUG
  roxen_perror("CGI: Handling "+e+" by copying to /tmp/....\n");
#endif
  
  o->set_blocking();
  f=o->read(0x7ffffff);         // We really hope that this is not located on 
                               // a NFS server far-far away...
  destruct(o);
  q="/tmp/"+(w=(((id->not_query/"/")[-1][0..2])+"Roxen_tmp"));
  rm(q);
  write_file(q, f);

  popen("chmod u+x "+q);
  err=catch(toret = low_find_file(w, id, "/tmp/"));

  if(err) throw(err);
  return toret;
}

mapping last_resort(object id)
{
  if(QUERY(ex)) // Handle path_info for *.ext files as well.
  {            // but only if extensions are used.
    string a, b, e;
    object fid; // As in fake id.. :-)
    mapping res;

    foreach(query_file_extensions(), e)
    {
      if(strlen(e) && sscanf(id->not_query, "%s."+e+"%s", a, b))
      {
	if (sizeof(b) && !((<'?','/'>)[b[0]])) {
	  continue;
	}
	fid = id->clone_me();
	fid->not_query = a+"."+e;
	fid->misc->path_info = b;
	res = id->conf->get_file(fid); // Recurse.
	if(res) return res;
      }
    }
  }
}