File: cgi.ml

package info (click to toggle)
netstring 0.10.1-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,000 kB
  • ctags: 895
  • sloc: ml: 8,389; xml: 416; makefile: 188; sh: 103
file content (1492 lines) | stat: -rw-r--r-- 42,327 bytes parent folder | download
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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
(* $Id: cgi.ml,v 1.9 2001/08/30 19:45:19 gerd Exp $
 * ----------------------------------------------------------------------
 *
 *)

(**********************************************************************)
(* Types and exceptions                                               *)
(**********************************************************************)

exception Resources_exceeded

type argument_processing = Memory | File | Automatic;;

type argument =
    { mutable arg_name : string;
      mutable arg_processing : argument_processing;
      mutable arg_buf_value : Buffer.t;
      mutable arg_mem_value : string option;
              (* Here, the value is stored if it must be kept in memory *)
      mutable arg_disk_value : string Weak.t;
              (* This component is used iff arg_mem_value = None. The
	       * weak array has a length of 1, and the single element stores
	       * the value (if any).
	       *)
      mutable arg_file : string option;
              (* The filename of the temporary file storing the value *)
      mutable arg_fd : out_channel option;
              (* The file descriptor of the temp file (if open) *)
      mutable arg_mimetype : string;
      mutable arg_filename : string option;
      mutable arg_header : (string * string) list;
              (* For the last three components, see the description of the
	       * corresponding functions in the mli file.
	       *)
    }
;;

type workaround =
    Work_around_MSIE_Content_type_bug
  | Work_around_backslash_bug
;;

type config =
    { maximum_content_length : int;
      how_to_process_arguments : argument -> argument_processing;
      tmp_directory : string;
      tmp_prefix : string;
      workarounds : workaround list;
      enable_testing : bool;
    }
;;

type state =
    { mutable args : (string * argument) list;
      mutable args_set : bool;
              (* Whether args has been set (parse_arguments or set_arguments) *)
      mutable using_temp_files : bool;
              (* Whether files are temporary and cleanup may delete them. 
	       * This feature is disabled if files are specified on the 
	       * command line.
	       *)
      mutable env  : (string * string Lazy.t) list;  
              (* contains only the known environment variables *)
      mutable get_env : string -> string;
              (* how to get unknown environment variables *)
      mutable input_ch : in_channel;
      mutable input_ch_parsed : bool;
      mutable content_type : string;
      mutable content_length : int option;
      mutable config : config;
    }
;;

type status =   (* Status codes from RFC 2616 *)
  (* 2xx: (successful) *)
  [ `Ok
  | `Created
  | `Accepted
  | `Non_authoritative
  | `No_content
  | `Reset_content
  | `Partial_content
  (* 3xx: (redirection) *)
  | `Multiple_choices
  | `Moved_permanently
  | `Found
  | `See_other
  | `Not_modified
  | `Use_proxy
  | `Temporary_redirect
  (* 4xx: (client error) *)
  | `Bad_request
  | `Unauthorized
  | `Payment_required
  | `Forbidden
  | `Not_found
  | `Method_not_allowed
  | `Not_acceptable
  | `Proxy_auth_required
  | `Request_timeout
  | `Conflict
  | `Gone
  | `Length_required
  | `Precondition_failed
  | `Request_entity_too_large
  | `Request_uri_too_long
  | `Unsupported_media_type
  | `Requested_range_not_satisfiable
  | `Expectation_failed
  (* 5xx: (server error) *)
  | `Internal_server_error
  | `Not_implemented
  | `Bad_gateway
  | `Service_unavailable
  | `Gateway_timeout
  | `Http_version_not_supported ]
;;

type cache_control =
    [ `No_cache
    | `Max_age of int
    | `Unspecified
    ]
;;


type cookie =
    { cookie_name : string;
      cookie_value : string;
      cookie_expires : float option;
      cookie_domain : string option;
      cookie_path : string option;
      cookie_secure : bool;
    }
;;

(**********************************************************************)
(* aux functions for files                                            *)
(**********************************************************************)

let make_temporary_file config =
  (* Returns (filename, out_channel). *)
  let rec try_creation n =
    try
      let fn =
	Filename.concat
	  config.tmp_directory
	  (config.tmp_prefix ^ "-" ^ (string_of_int n))
      in
      let fd =
	open_out_gen
	  [ Open_wronly; Open_creat; Open_excl; Open_binary ]
	  0o666
	  fn
      in
      fn, fd
    with
	Sys_error m ->
	  (* This does not look very intelligent, but it is the only chance
	   * to limit the number of trials.
	   *)
	  if n > 1000 then
	    failwith ("Cgi: Cannot create temporary file: " ^ m);
	  try_creation (n+1)
  in
  try_creation 0
;;


let read_file name =
  (* Reads contents of file and returns them as string *)
  let b = Buffer.create 1024 in
  let s = String.create 1024 in
  let f = open_in_bin name in
  try
    while true do
      let n = input f s 0 (String.length s) in
      if n = 0 then raise End_of_file;
      Buffer.add_substring b s 0 n;
    done;
    assert false
  with
      End_of_file ->
	close_in f;
	Buffer.contents b
    | err ->
	close_in f;
	raise err
;;


let isatty() =
  (* Is stdin connected to a tty? *)
  match Sys.os_type with
    | "Unix" 
    | "Cygwin" ->
	(* Ask the "tty" program. If we had the Unix module, we could check
	 * this directly.
	 *)
	Sys.command "tty -s" = 0
    | "Win32" 
    | "MacOS" ->
	(* Don't know how to do this. So assume it's a tty anyway. *)
	true
    | _ ->
	assert false
;;


(**********************************************************************)
(* argument primitives                                                *)
(**********************************************************************)

let mk_simple_arg ~name v =
  { arg_name = name;
    arg_processing = Memory;
    arg_buf_value = Buffer.create 1;
    arg_mem_value = Some v;
    arg_disk_value = Weak.create 0;
    arg_file = None;
    arg_fd = None;
    arg_mimetype = "text/plain";
    arg_filename = None;
    arg_header = [];
  }
;;

let mk_memory_arg ~name ?(mime = "text/plain") ?filename ?(header = []) v =
  { arg_name = name;
    arg_processing = Memory;
    arg_buf_value = Buffer.create 1;
    arg_mem_value = Some v;
    arg_disk_value = Weak.create 0;
    arg_file = None;
    arg_fd = None;
    arg_mimetype = mime;
    arg_filename = filename;
    arg_header = header;
  }
;;

let mk_file_arg 
  ~name ?(mime = "text/plain") ?filename ?(header = []) v_filename =
  let v_abs_filename =
    if Filename.is_relative v_filename then
      Filename.concat (Sys.getcwd()) v_filename
    else
      v_filename
  in
  { arg_name = name;
    arg_processing = File;
    arg_buf_value = Buffer.create 1;
    arg_mem_value = None;
    arg_disk_value = Weak.create 1;
    arg_file = Some v_abs_filename;
    arg_fd = None;
    arg_mimetype = mime;
    arg_filename = filename;
    arg_header = header;
  }
;;


let print_argument arg =
  Format.printf
    "<CGIARG name=%s filename=%s mimetype=%s store=%s>"
    arg.arg_name
    (match arg.arg_filename with None -> "*" | Some n -> n)
    arg.arg_mimetype
    (match arg.arg_file with None -> "Memory" | Some n -> n)
;;


(**********************************************************************)
(* default configuration                                              *)
(**********************************************************************)

let default_config =
  { maximum_content_length = max_int;
    how_to_process_arguments = (fun _ -> Memory);
    tmp_directory = "/var/tmp";
    tmp_prefix = "cgi-";
    workarounds = [ Work_around_MSIE_Content_type_bug;
		    Work_around_backslash_bug;
		  ];
    enable_testing = true;
  }
;;

(**********************************************************************)
(* URL-encoding                                                       *)
(**********************************************************************)

let encode s = Netencoding.Url.encode s;;
let decode s = Netencoding.Url.decode s;;



let url_split_re =
  Netstring_str.regexp "[&=]";;


let mk_url_encoded_parameters nv_pairs =
  String.concat "&"
    (List.map
       (fun (name,value) ->
	  let name_encoded = Netencoding.Url.encode name in
	  let value_encoded = Netencoding.Url.encode value in
	  name_encoded ^ "=" ^ value_encoded
       )
       nv_pairs
    )
;;


let mk_query_string args =
  let mem_args =
    List.filter (fun (_,arg) -> arg.arg_mem_value <> None) args in
  let nv_pairs =
    List.map
      (fun (n,arg) ->
	 match arg.arg_mem_value with
	     Some v -> (n,v) 
	   | None   -> assert false
      )
      mem_args
  in
  mk_url_encoded_parameters nv_pairs
;;
    

let dest_url_encoded_parameters parstr =

  let rec parse_after_amp tl =
    match tl with
	Str.Text name :: Str.Delim "=" :: Str.Text value :: tl' ->
	  (Netencoding.Url.decode name,
	   Netencoding.Url.decode value) :: parse_next tl'
      | Str.Text name :: Str.Delim "=" :: Str.Delim "&" :: tl' ->
	  (Netencoding.Url.decode name, "") :: parse_after_amp tl'
      | Str.Text name :: Str.Delim "=" :: [] ->
	  [Netencoding.Url.decode name, ""]
      | _ ->
	  failwith "Cgi.dest_url_encoded_parameters"
  and parse_next tl =
    match tl with
	[] -> []
      | Str.Delim "&" :: tl' ->
	  parse_after_amp tl'
      | _ ->
	  failwith "Cgi.dest_url_encoded_parameters"
  in
  let toklist = Netstring_str.full_split url_split_re parstr in
  match toklist with
      [] -> []
    | _ -> parse_after_amp toklist
;;


(**********************************************************************)
(* state basics                                                       *)
(**********************************************************************)

let create_state() =
  { args = [];
    args_set = false;
    using_temp_files = true;
    env = [];
    get_env = (fun name -> raise Not_found);
    input_ch = stdin;
    input_ch_parsed = false;
    content_type = "";
    content_length = None;
    config = default_config;
  }
;;


let create_internal_state() =
  let state = create_state() in
  { state with
    get_env = (fun name -> failwith "Cgi: Cannot access environment before parse_arguments has been called");
  }
;;


let internal_state = create_internal_state();;

let have_env_var name =
  try ignore(Sys.getenv name); true with Not_found -> false
;;

let getenv state name =
  try
    Lazy.force(List.assoc name state.env)       (* already known? *)
  with
      Not_found ->
	let v =
	  try state.get_env name
	  with Not_found -> ""                  (* not set: same as "" *)
	in
	state.env <- (name,lazy v) :: state.env;
	v
;;


let method_supports_query_string meth =
  List.mem meth [ "GET"; "HEAD"; "PUT"; "DELETE" ]
;;


let state_supports_query_string state =
  method_supports_query_string (getenv state "REQUEST_METHOD")
;;



let get_content_type state config =
  (* Get the environment variable CONTENT_TYPE; if necessary apply
   * workarounds for browser bugs.
   *)
  let content_type = getenv state "CONTENT_TYPE" in
  let user_agent = getenv state "HTTP_USER_AGENT" in
  let eff_content_type =
    if Netstring_str.string_match 
         (Netstring_str.regexp ".*MSIE") user_agent 0 <> None &&
       List.mem Work_around_MSIE_Content_type_bug config.workarounds
    then begin
      (* Microsoft Internet Explorer: When used with SSL connections,
       * this browser sometimes produces CONTENT_TYPEs like
       * "multipart/form-data; boundary=..., multipart/form-data; boundary=..."
       * Workaround: Throw away everything after ", ".
       *)
      match Netstring_str.string_match 
	      (Netstring_str.regexp "\\([^,]*boundary[^,]*\\), .*boundary")
	      content_type 0
      with
	  Some result ->
	    Netstring_str.matched_group result 1 content_type
	| None ->
	    content_type
    end
    else
      content_type
  in
  eff_content_type
;;


let lazy_query_string state =
  lazy
    (if state_supports_query_string state then
       mk_query_string state.args
     else
       ""
    )
;;


let split_name_is_value s =
  (* Recognizes a string "name=value" and returns the pair (name,value).
   * If the string has the wrong format, the function will fail.
   *)
  try
    let p = String.index s '=' in
    (String.sub s 0 p, String.sub s (p+1) (String.length s - p - 1))
  with
      Not_found ->
	failwith ("Cgi: Cannot parse: " ^ s)
;;


let init_state ?(input=stdin) ?content_length ?content_type state config =
  assert(not state.args_set);
  assert(not state.input_ch_parsed);
  state.config <- config;
  state.input_ch <- input;
  state.content_length <- content_length;
  ( match content_type with
	Some t -> 
	  state.content_type <- t
      | None   -> 
	  state.content_type <- ""
  )
;;


let have_cgi_environment () =
  have_env_var "SERVER_SOFTWARE" && have_env_var "SERVER_NAME" &&
  have_env_var "GATEWAY_INTERFACE" 
;;


let have_command_line_options config =
  config.enable_testing  && !Arg.current+1 < Array.length Sys.argv
;;


let have_terminal config =
  config.enable_testing  &&  isatty()
;;


let init_internal_state ?(input=stdin) ?content_length ?content_type config =
  assert(not internal_state.args_set);
  assert(not internal_state.input_ch_parsed);
  internal_state.config <- config;
  (* First check whether we are in a real CGI environment: *)
  if have_cgi_environment() then begin
    internal_state.get_env <- Sys.getenv;
    internal_state.input_ch <- input;
    ( match content_length with
	  Some l -> internal_state.content_length <- Some l
	| None   ->
	    let l = getenv internal_state "CONTENT_LENGTH" in
	    if l = "" then
	      internal_state.content_length <- None
	    else
	      internal_state.content_length <- Some(int_of_string l)
    );
    ( match content_type with
	  Some t -> 
	    internal_state.content_type <- t
	| None   -> 
	    internal_state.content_type <- get_content_type internal_state config
    );
  end
  else
    (* Are there command-line options? *)
    if have_command_line_options config then begin
      let usage = ref (fun () -> ()) in
      let mimetype = ref "text/plain" in
      let filename = ref None in
      let args = ref [] in
      let cgi_method = ref "GET" in
      let user = ref "" in
      let other = ref [] in
      let keywords =
	[ "-mimetype", 
	  Arg.String (fun s -> mimetype := s),
	            "type          Set the MIME type for the next argument(s) (default: text/plain)";
	  "-filename", 
	  Arg.String (fun s -> if s = "" then filename := None 
                                         else filename := Some s),
	            "path          Set the filename property for the next argument(s)";
	  "-memarg",
	  Arg.String
	    (fun s ->
	       let (name,file) = split_name_is_value s in
	       args := !args @ [name, 
				mk_memory_arg
				~name 
				~mime:!mimetype 
				?filename:!filename
				  (read_file file)]
	    ),
	          "name=file       Read the contents of the memory argument from a file";
	  "-filearg",
	  Arg.String
	    (fun s ->
	       let (name,file) = split_name_is_value s in
	       args := !args @ [name, 
				mk_file_arg
				~name 
				~mime:!mimetype 
				?filename:!filename
				  file];
	    ),
	           "name=file      Specify a file argument whose contents are in the file";
	  "-method",
	  Arg.String (fun s -> cgi_method := s),
	          "name            Simulate this method (default is GET)";
	  "-user",
	  Arg.String (fun s -> user := s),
	        "name              Set REMOTE_USER to this name";
	  "-set",
	  Arg.String (fun s -> other := !other @ [split_name_is_value s]),
	       "name=value         Set the environment variable name to value";
	  "-help",
	  Arg.Unit !usage,
	        "                  Output this help";
	]
      in
      let usage_string = "This program expects a CGI environment. You can simulate such an environment\n\
                          by name=value command-line arguments. Furthermore, the following options\n\
                          are recognized:" in
      usage := (fun () -> Arg.usage keywords usage_string);
      Arg.parse 
	  keywords
	  (fun s -> 
	     let (name,value) = split_name_is_value s in
	     args := !args @ [name, 
			      mk_memory_arg
			        ~name 
			        ~mime:!mimetype 
			        ?filename:!filename
				value];
	  )
	  usage_string;
      internal_state.get_env <- (fun _ -> raise Not_found);
      internal_state.args <- !args;
      internal_state.args_set <- true;
      internal_state.using_temp_files <- false;
      internal_state.env <-
        [ "GATEWAY_INTERFACE", lazy "CGI/1.1";
	  "SERVER_SOFTWARE",   lazy "NetstringCGI/0";
	  "SERVER_NAME",       lazy "localhost";
	  "SERVER_PROTOCOL",   lazy "HTTP/1.0";
	  "REQUEST_METHOD",    lazy !cgi_method;
	  "SCRIPT_NAME",       lazy Sys.argv.(0);
	  "QUERY_STRING",      lazy (if method_supports_query_string !cgi_method
				     then mk_query_string !args
				     else "");
	  "REMOTE_HOST",       lazy "localhost";
	  "REMOTE_ADDR",       lazy "127.0.0.1";
	  "HTTP_USER_AGENT",   lazy "NetstringCGI/0";
	] @
        (if !user <> "" then
	   [ "REMOTE_USER", lazy !user;
	     "AUTH_TYPE",   lazy "basic";
	   ]
	 else
	   []
	);
      List.iter
	(fun (n,v) ->
	   internal_state.env <-
	     (n, lazy v) :: List.remove_assoc n internal_state.env
	)
	!other;
    end
    else
      if have_terminal config then begin
	prerr_endline "This is a CGI program. You can now input arguments, every argument on a new";
	prerr_endline "line in the format name=value. The request method is fixed to GET, and cannot";
	prerr_endline "be changed in this mode. Consider using the command-line for more options.";
	let continue = ref true in
	let args = ref [] in
	(try
	   while !continue do
	     prerr_string "> ";
	     flush stderr;
	     let line = read_line () in
	     if line <> "." then
	       try
		 let n,v = split_name_is_value line in
		 args := !args @ [n, mk_memory_arg ~name:n v];
	       with
		   Failure _ ->
		     prerr_string "Error. Do you want to enter more arguments? (y/n) ";
		     flush stderr;
		     let answer = read_line () in
		     continue := (answer = "y") || (answer = "Y") ||
		                 (answer = "yes") || (answer = "YES")
	     else
	       continue := false
	   done
	 with
	     End_of_file ->
	       prerr_endline "(Got EOF)";
	);
	prerr_endline "(Continuing the program)";
	flush stderr;
	internal_state.get_env <- (fun _ -> raise Not_found);
	internal_state.args <- !args;
	internal_state.args_set <- true;
	internal_state.using_temp_files <- false;
	internal_state.env <-
          [ "GATEWAY_INTERFACE", lazy "CGI/1.1";
	    "SERVER_SOFTWARE",   lazy "NetstringCGI/0";
	    "SERVER_NAME",       lazy "localhost";
	    "SERVER_PROTOCOL",   lazy "HTTP/1.0";
	    "REQUEST_METHOD",    lazy "GET";
	    "SCRIPT_NAME",       lazy Sys.argv.(0);
	    "QUERY_STRING",      lazy (mk_query_string !args);
	    "REMOTE_HOST",       lazy "localhost";
	    "REMOTE_ADDR",       lazy "127.0.0.1";
	    "HTTP_USER_AGENT",   lazy "NetstringCGI/0";
	  ];
      end
      else begin
	(* Finally output an error message. *)
	prerr_endline "Cgi: No CGI environment found. For testing, consider using command-line options";
	failwith "Cgi: No CGI environment found.";
      end
;;


(**********************************************************************)
(* Form encoded parameters                                            *)
(**********************************************************************)


let mk_form_encoded_parameters ntv_triples =
  failwith "Cgi.mk_form_encoded_parameters: not implemented";;


let dest_parameter_header header options =
  let get_name s =
    (* s is: form-data; ... name="fieldname" ...
     * Extract "fieldname"
     *)
    try
      let tok, params = Mimestring.scan_value_with_parameters s options in
      List.assoc "name" params
    with
	Not_found ->
	  failwith "Cgi.dest_form_encoded_parameters"
      | Failure "Mimestring.scan_value_with_parameters" ->
	  failwith "Cgi.dest_form_encoded_parameters"
  in

  let get_filename s =
    (* s is: form-data; ... filename="fieldname" ...
     * Extract "fieldname"
     *)
    try
      let tok, params = Mimestring.scan_value_with_parameters s options in
      Some(List.assoc "filename" params)
    with
	Not_found ->
	  None
      | Failure "Mimestring.scan_value_with_parameters" ->
	  failwith "Cgi.dest_form_encoded_parameters"
  in

  let mime_type =
    try List.assoc "content-type" header
    with Not_found -> "text/plain" in     (* the default *)

  let content_disposition =
    try List.assoc "content-disposition" header
    with
	Not_found ->
	  failwith "Cgi.dest_form_encoded_parameters: no content-disposition"
  in

  let name = get_name content_disposition in
  let filename = get_filename content_disposition in

  name, mime_type, filename
;;


let dest_form_encoded_parameters parstr ~boundary config =
  let options =
    if List.mem Work_around_backslash_bug config.workarounds then
      [ Mimestring.No_backslash_escaping ]
    else
      []
  in
  let parts =
    Mimestring.scan_multipart_body_and_decode
      parstr 0 (String.length parstr) boundary in
  List.map
    (fun (params, value) ->

      let name, mime_type, filename = dest_parameter_header params options in
      { arg_name = name;
	arg_processing = Memory;
	arg_buf_value = Buffer.create 1;
	arg_mem_value = Some value;
	arg_disk_value = Weak.create 1;
	arg_file = None;
	arg_fd = None;
	arg_mimetype = mime_type;
	arg_filename = filename;
	arg_header = params;
      }

    )
    parts
;;


let dest_form_encoded_parameters_from_netstream s ~boundary config =
  let parts = ref [] in
  let options =
    if List.mem Work_around_backslash_bug config.workarounds then
      [ Mimestring.No_backslash_escaping ]
    else
      []
  in

  let create header =
    (* CALLBACK for scan_multipart_body_from_netstream *)
    let name, mime_type, filename = dest_parameter_header header options in
    let p0 =
      { arg_name = name;
	arg_processing = Memory;
	arg_buf_value = Buffer.create 80;
	arg_mem_value = None;
	arg_disk_value = Weak.create 1;
	arg_file = None;
	arg_fd = None;
	arg_mimetype = mime_type;
	arg_filename = filename;
	arg_header = header;
      }
    in
    let pr = config.how_to_process_arguments p0 in
    let p = { p0 with arg_processing = pr } in
    if pr = File then begin
      let fn, fd = make_temporary_file config in
      p.arg_file <- Some fn;
      p.arg_fd   <- Some fd;
      p.arg_mem_value <- None;
    end;
    p
  in

  let add p s k n =
    (* CALLBACK for scan_multipart_body_from_netstream *)
    if (p.arg_processing = Automatic) &&
       (Buffer.length (p.arg_buf_value) >= Netstream.block_size s) then begin
	 (* This is a LARGE argument *)
	 p.arg_processing <- File;
	 let fn, fd = make_temporary_file config in
	 p.arg_file <- Some fn;
	 p.arg_fd   <- Some fd;
	 p.arg_mem_value <- None;
	 output_string fd (Buffer.contents p.arg_buf_value);
	 p.arg_buf_value <- Buffer.create 1;
       end;

    match p.arg_processing with
	(Memory|Automatic) ->
	  Buffer.add_substring
	    p.arg_buf_value
	    (Netbuffer.unsafe_buffer (Netstream.window s))
	    k
	    n
      | File ->
	  let fd = match p.arg_fd with Some fd -> fd | None -> assert false in
	  output
	    fd
	    (Netbuffer.unsafe_buffer (Netstream.window s))
	    k
	    n;
  in

  let stop p =
    (* CALLBACK for scan_multipart_body_from_netstream *)
    begin match p.arg_processing with
	(Memory|Automatic) ->
	  p.arg_mem_value <- Some (Buffer.contents p.arg_buf_value);
	  p.arg_buf_value <- Buffer.create 1;
      | File ->
	  let fd = match p.arg_fd with Some fd -> fd | None -> assert false in
	  close_out fd;
	  p.arg_mem_value <- None
    end;
    parts := p :: !parts
  in

  Mimestring.scan_multipart_body_from_netstream
    s
    boundary
    create
    add
    stop;

  List.rev !parts
;;

(**********************************************************************)
(* Argument parsing                                                   *)
(**********************************************************************)

let really_parse_args state config =
  let make_simple_arg (n,v) = mk_simple_arg n v in

  match getenv state "REQUEST_METHOD" with
      ("GET"|"HEAD") ->
	List.map
	  make_simple_arg
	  (dest_url_encoded_parameters(getenv state "QUERY_STRING"))

    | "POST" ->
	let n = 
	  match state.content_length with
	      None -> failwith "Cgi.parse_arguments: No content length"
	    | Some x -> x
	in
	if n > config.maximum_content_length then
	  raise Resources_exceeded;
	begin
	  let mime_type, params =
	    Mimestring.scan_mime_type state.content_type [] in
	  match mime_type with
	      "application/x-www-form-urlencoded" ->
		let buf = String.create n in
		assert (not state.input_ch_parsed);
		really_input state.input_ch buf 0 n;
		state.input_ch_parsed <- true;
		List.map
		  make_simple_arg
		  (dest_url_encoded_parameters buf)
	    | "multipart/form-data" ->
		let boundary =
		  try
		    List.assoc "boundary" params
		  with
		      Not_found ->
			failwith "Cgi.parse_arguments"
		in
		(* -------------------------------------------------- DEBUG
		   let f = open_out "/tmp/cgiout" in
		   output_string f buf;
		   close_out f;
		 * --------------------------------------------------
		 *)
		assert (not state.input_ch_parsed);
		let r =
		  dest_form_encoded_parameters_from_netstream
		    (Netstream.create_from_channel state.input_ch (Some n) 4096)
		    boundary
		    config in
		state.input_ch_parsed <- true;
		r
	    | _ ->
		failwith ("Cgi.parse_arguments: unknown content-type " ^ mime_type)
	end
    | "PUT" ->
	failwith "Cgi.parse_arguments: PUT method not supported"
    | "DELETE" ->
	failwith "Cgi.parse_arguments: DELETE method not supported"
    | "" ->
	failwith "Cgi.parse_arguments: REQUEST_METHOD is unset or empty"
    | _ ->
	failwith "Cgi.parse_arguments: unknown method"
;;


(**********************************************************************)
(* Interface                                                          *)
(**********************************************************************)


(* In multi-threaded programs, several threads may concurrently access 
 * CGI data. Such accesses are serialized by a mutex that is created 
 * only in MT contexts.
 *
 * Every function below that accesses state must be protected.
 *)

let lock   = ref (fun () -> ());;
let unlock = ref (fun () -> ());;

let init_mt new_lock new_unlock =
  lock   := new_lock;
  unlock := new_unlock
;;

let protect f =
  !lock();
  try
    let r = f() in
    !unlock();
    r
  with
      x ->
        !unlock();
        raise x
;;

let parse_arguments ?(state = internal_state) 
                    ?input ?content_length ?content_type 
                    config =
  protect
    (fun () ->
       (* Reset for toploop? *)
       if state.args_set
	  && state == internal_state 
	  && not(have_cgi_environment()) 
	  && not(have_command_line_options config)
	  && !Sys.interactive
	  && (have_terminal config) 
       then begin
	 prerr_string "Do you want to enter new CGI arguments? (y/n) ";
	 flush stderr;
	 let answer = read_line() in
	 if answer = "y" || answer = "Y" || answer = "yes" || answer = "YES"
	 then
	   state.args_set <- false
	 else
	   ( prerr_endline "(Keeping old arguments)"; flush stderr );
       end;
       if not state.args_set then begin
	 (* Initialize state. *)
	 if state == internal_state then
	   init_internal_state ?input ?content_length ?content_type config
	 else
	   init_state ?input ?content_length ?content_type state config;
	 (* It is possible that the arguments are set now. *)
	 if not state.args_set then begin
	   let args = really_parse_args state config in
	   state.args <- List.map (fun arg -> arg.arg_name, arg) args;
	   state.args_set <- true;
	 end;
       end
    )
;;


let arguments ?(state = internal_state) () =
  protect
    (fun () ->
       if state.args_set then 
	 state.args
       else
	 failwith "Cgi.arguments";
    )
;;

let set_arguments ?(state = internal_state) ?set_query_string arglist =
  protect 
    (fun () ->
       state.args <- List.map (fun arg -> arg.arg_name,arg) arglist;
       state.args_set <- true;
       ( match set_query_string with
	     Some b ->
	       if b then
		 state.env <- ("QUERY_STRING", 
			       lazy (mk_query_string state.args)) ::
		              List.remove_assoc "QUERY_STRING" state.env;
	   | None ->
	       if state_supports_query_string state then
		 state.env <- ("QUERY_STRING", 
			       lazy (mk_query_string state.args)) ::
   		              List.remove_assoc "QUERY_STRING" state.env; 
       )
    )
;;

let update_argument ?(state = internal_state) arg =
  protect
    (fun () ->
       if not state.args_set then failwith "Cgi.update_argument";
       let name = arg.arg_name in
       state.args <- (name, arg) :: List.remove_assoc name state.args
    )
;;


let update_argument_value ?state ~name value =
  try
    let arg = List.assoc name (arguments ?state ()) in  (* or Not_found *)
    if arg.arg_file <> None then failwith "Cgi.update_argument_value";
    arg.arg_mem_value <- Some value;
  with
      Not_found ->
	update_argument ?state (mk_simple_arg name value)
;;


let delete_argument ?(state = internal_state) name =
    protect
    (fun () ->
       if not state.args_set then failwith "Cgi.delete_argument";
       state.args <- List.remove_assoc name state.args
    )
;;


let arg_value arg =
  match arg.arg_mem_value with
      None ->
	begin
	  match Weak.get arg.arg_disk_value 0 with
	      None ->
		begin
		  match arg.arg_file with
		      None ->
			failwith "Cgi.arg_value: no value present"
		    | Some filename ->
			let s = read_file filename in
			Weak.set arg.arg_disk_value 0 (Some s);
			s
		end
	    | Some v -> v
	end
    | Some s ->
	s
;;

let arg_name     arg = arg.arg_name;;
let arg_file     arg = arg.arg_file;;
let arg_mimetype arg = arg.arg_mimetype;;
let arg_filename arg = arg.arg_filename;;
let arg_header   arg = arg.arg_header;;

let cleanup ?(state = internal_state) () =
  protect
    (fun () ->
       if state.args_set && state.using_temp_files then begin
	 List.iter
	   (fun (name, arg) ->
	      match arg.arg_file with
		  None -> ()
		| Some filename ->
		    (* We do not complain if the file does not exist anymore. *)
		    if Sys.file_exists filename then
		      Sys.remove filename;
		    arg.arg_file <- None
	   )
	   state.args
       end
    )
;;

let argument ?state name = 
  List.assoc name (arguments ?state ());;
let argument_value ?state name = 
  arg_value (argument ?state name);;

module Operators = struct
  let ( !% ) = argument ?state:None
  let ( !$ ) = argument_value ?state:None
end;;


let parse_args() =
  (* Note: works always with internal_state *)
  parse_arguments default_config;
  List.map
    (fun (name, arg) -> name, arg_value arg)
    (arguments())
;;

let parse_args_with_mimetypes() =
  (* Note: works always with internal_state *)
  parse_arguments default_config;
  List.map
    (fun (name, arg) -> name, arg_mimetype arg, arg_value arg)
    (arguments())
;;

module Env = struct
  let get ?(state = internal_state) name =
    protect (fun() -> getenv state name)

  let set ?(state = internal_state) name value =
    protect 
      (fun () ->
	 state.env <- (name,lazy value) :: List.remove_assoc name state.env)

  let set_list ?(state = internal_state) nv_pairs =
    protect
      (fun () ->
	 state.env <- List.map (fun (n,v) -> (n, lazy v)) nv_pairs)

  let gateway_interface ?state () = get ?state "GATEWAY_INTERFACE"
  let server_software   ?state () = get ?state "SERVER_SOFTWARE"
  let server_name       ?state () = get ?state "SERVER_NAME"
  let server_protocol   ?state () = get ?state "SERVER_PROTOCOL"
  let request_method    ?state () = get ?state "REQUEST_METHOD"
  let path_info         ?state () = get ?state "PATH_INFO"
  let path_translated   ?state () = get ?state "PATH_TRANSLATED"
  let script_name       ?state () = get ?state "SCRIPT_NAME"
  let query_string      ?state () = get ?state "QUERY_STRING"
  let remote_host       ?state () = get ?state "REMOTE_HOST"
  let remote_addr       ?state () = get ?state "REMOTE_ADDR"
  let auth_type         ?state () = get ?state "AUTH_TYPE"
  let remote_user       ?state () = get ?state "REMOTE_USER"
  let remote_ident      ?state () = get ?state "REMOTE_IDENT"
  let http_user_agent   ?state () = get ?state "HTTP_USER_AGENT"
  let server_port       ?state () = 
    let s = get ?state "SERVER_PORT" in
    if s = "" then
      None
    else
      Some(int_of_string s)

  let major_protocol ?state () =
    let p = server_protocol ?state () in
    try
      let k = String.index p '/' in
      String.sub p 0 k
    with
	Not_found -> p

  let https ?state () =
    String.lowercase (get ?state "HTTPS") = "on"

  let protocol_is_http ?state () = 
    major_protocol ?state () = "HTTP" && not (https ?state ())

  let protocol_is_https ?state () = 
    major_protocol ?state () = "HTTP" && (https ?state ())


  let cookies ?state () =
    let cstring = get ?state "HTTP_COOKIE" in
    let parts = Netstring_str.split 
		  (Netstring_str.regexp "[ \t\r\n]*;[ \t\r\n]*")
		  cstring in
    List.map
      (fun part ->
	 let n,v = split_name_is_value part in
	 let n_dec = Netencoding.Url.decode n in
	 let v_dec = Netencoding.Url.decode v in
	 (n_dec, v_dec)
      )
      parts


  let set_variable ?(state  = internal_state)
                   ?gateway_interface ?server_software ?server_name
                   ?server_protocol ?server_port ?request_method ?path_info
                   ?path_translated ?script_name ?query_string ?remote_host
                   ?remote_addr ?auth_type ?remote_user ?remote_ident 
                   ?http_user_agent () =
    let list = ref [] in
    let names = ref [] in
    let add n cond =
      match cond with
	  None -> ()
	| Some v -> list := (n, lazy v) :: !list;   names := n :: !names
    in
    let add_port n cond =
      match cond with
	  None -> ()
	| Some None -> add n (Some "")
	| Some (Some port) -> add n (Some (string_of_int port))
    in
    add "GATEWAY_INTERFACE" gateway_interface;
    add "SERVER_SOFTWARE" server_software;
    add "SERVER_NAME" server_name;
    add "SERVER_PROTOCOL" server_protocol;
    add_port "SERVER_PORT" server_port;
    add "REQUEST_METHOD" request_method;
    add "PATH_INFO" path_info;
    add "PATH_TRANSLATED" path_translated;
    add "SCRIPT_NAME" script_name;
    add "QUERY_STRING" query_string;
    add "REMOTE_HOST" remote_host;
    add "REMOTE_ADDR" remote_addr;
    add "AUTH_TYPE" auth_type;
    add "REMOTE_USER" remote_user;
    add "REMOTE_IDENT" remote_ident;
    add "HTTP_USER_AGENT" http_user_agent;
    protect
      (fun () ->
	 state.env <- !list @ 
	              (List.filter 
			 (fun (n,v) -> not (List.mem n !names))
			 state.env)
      )

end
;;

(**********************************************************************)
(* Output                                                             *)
(**********************************************************************)

let status_line (s:status) =
  "Status: " ^ 
  match s with
      `Ok -> "200 OK"
    | `Created -> "201 Created"
    | `Accepted -> "202 Accepted"
    | `Non_authoritative -> "203 Non-Authoritative Information"
    | `No_content -> "204 No content"
    | `Reset_content -> "205 Reset Content"
    | `Partial_content -> "206 Partial Content"
    | `Multiple_choices -> "300 Multiple Choices"
    | `Moved_permanently -> "301 Moved Permanently"
    | `Found -> "302 Found"
    | `See_other -> "303 See Other"
    | `Not_modified -> "304 Not Modified"
    | `Use_proxy -> "305 Use Proxy"
    | `Temporary_redirect -> "307 Temporary Redirect"
    | `Bad_request -> "400 Bad Request"
    | `Unauthorized -> "401 Unauthorized"
    | `Payment_required -> "402 Payment Required"
    | `Forbidden -> "403 Forbidden"
    | `Not_found -> "404 Not Found"
    | `Method_not_allowed -> "405 Method Not Allowed"
    | `Not_acceptable -> "406 Not Acceptable"
    | `Proxy_auth_required -> "407 Proxy Authentication Required"
    | `Request_timeout -> "408 Request Timeout"
    | `Conflict -> "409 Conflict"
    | `Gone -> "410 Gone"
    | `Length_required -> "411 Length Required"
    | `Precondition_failed -> "412 Precondition Failed"
    | `Request_entity_too_large -> "413 Request Entity Too Large"
    | `Request_uri_too_long -> "414 Request-URI Too Long"
    | `Unsupported_media_type -> "415 Unsupported Media Type"
    | `Requested_range_not_satisfiable -> "416 Requested Range Not Satisfiable"
    | `Expectation_failed -> "417 Expectation Failed"
    | `Internal_server_error -> "500 Internal Server Error"
    | `Not_implemented -> "501 Not Implemented"
    | `Bad_gateway -> "502 Bad Gateway"
    | `Service_unavailable -> "503 Service Unavailable"
    | `Gateway_timeout -> "504 Gateway Timeout"
    | `Http_version_not_supported -> "505 HTTP Version Not Supported"
;;


let header ?(output = stdout) 
           ?status 
           ?(cache = `Unspecified)
           ?(filename = "")
           ?(language = "")
           ?(script_type = "")
           ?(style_type = "")
           ?(set_cookie = [])
           ?(fields = []) 
           s =
  let t =
    match s with
	"" -> "text/html"
      | _  -> s
  in
  output_string output ("Content-type: " ^ t ^ "\n");
  (match status with
       None -> ()
     | Some s -> output_string output (status_line s ^ "\n"));
  (match cache with
       `Unspecified -> ()
     | `No_cache ->
	 let over = Unix.time() -. 1.0 in
	 output_string output "Cache-control: no-cache\n";
	 output_string output "Pragma: no-cache\n";
	 output_string output ("Expires: " ^ Netdate.mk_mail_date over ^ "\n")
     | `Max_age n ->
	 let exp = Unix.time() +. float_of_int n in
	 output_string output ("Cache-control: max-age=" ^ string_of_int n ^
			       "\n");
	 output_string output "Cache-control: must-revalidate\n";
	 output_string output ("Expires: " ^ Netdate.mk_mail_date exp ^ "\n");
  );
  if filename <> "" then begin
    (* We need to quote quotation marks and backslashes: *)
    let qfn = Netstring_str.global_substitute
                (Netstring_str.regexp "[\"\\]")
                (fun r s -> "\\" ^ Netstring_str.matched_string r s)
                filename 
    in
    output_string output 
      ("Content-disposition: attachment; filename=\"" ^ qfn ^ "\"\n");
  end;
  if language <> "" then
    output_string output ("Content-language: " ^ language ^ "\n");
  if script_type <> "" then
    output_string output ("Content-script-type: " ^ script_type ^ "\n");
  if style_type <> "" then
    output_string output ("Content-style-type: "  ^ style_type ^ "\n");
  List.iter
    (fun c ->
       output_string output "Set-cookie: ";
       let enc_name  = Netencoding.Url.encode ~plus:false c.cookie_name in
       let enc_value = Netencoding.Url.encode ~plus:false c.cookie_value in
       output_string output (enc_name ^ "=" ^ enc_value);
       ( match c.cookie_expires with
	     None -> ()
	   | Some t -> 
	       output_string output (";EXPIRES=" ^ Netdate.mk_usenet_date t);
       );
       (match c.cookie_domain with
	    None -> ()
	  | Some d ->
	      output_string output (";DOMAIN=" ^ d);
       );
       (match c.cookie_path with
	    None -> ()
	  | Some p ->
	      output_string output (";PATH=" ^ p);
       );
       if c.cookie_secure then output_string output (";SECURE");
       output_string output "\n";
    )
    set_cookie;
  List.iter
    (fun (n,v) ->
       output_string output (n ^ ": " ^ v ^ "\n")
    )
    fields;
  output_string output "\n";
  flush output
;;


let redirect ?(output = stdout) s =
  output_string output ("Location: " ^ s ^ "\n\n");
  flush output
;;


let this_url ?(state = internal_state) 
             ?(with_host_and_port = true)
	     ?(with_script_name = true)
	     ?(with_path_info = true)
             ?(with_query_string = false)
	     ?(update_query_string = false)
	     () =
  ( if with_host_and_port then
      let proto, proto_port =
	( if Env.protocol_is_http ~state () then
	    "http://", 80
	  else
	    if Env.protocol_is_https ~state () then
	      "https://", 443
	    else
	      failwith "Cgi.this_url: unknown protocol"
	) in
      proto ^ 
      Env.server_name ~state () ^ 
      match Env.server_port ~state() with
	  None -> ""
	| Some port -> 
	    if port = proto_port then "" else ":" ^ string_of_int port
    else
      ""
  ) ^ 
  ( if with_script_name then
      Env.script_name ~state ()
    else
      ""
  ) ^ 
  ( if with_path_info then
      Env.path_info ~state ()
    else
      ""
  ) ^ 
  ( if with_query_string then
      let qs = 
	if update_query_string then
	  mk_query_string state.args 
	else
	  Env.query_string ~state()
      in
      if qs = "" then
	""
      else
	"?" ^ qs
    else
      ""
  )
;;


(* ======================================================================
 * History:
 *
 * $Log: cgi.ml,v $
 * Revision 1.9  2001/08/30 19:45:19  gerd
 * Added a lot of new features:
 *
 * - Testing: If the CGI program is started from the command-line it recognizes
 *   several command-line options. Furthermore, there is an interactive
 *   mode.
 * - It is now possible to have multiple instances of the CGI module.
 * - The CGI environment and the arguments can be read from arbitrary
 *   sources. (Not only stdin, and the process environment.)
 * - CGI arguments can be updated.
 * - Enhanced "header" function; it includes cache-control directives,
 *   and cookies
 * - There is now a "redirect" function for server redirects.
 * - "this_url" has been enhanced (supports non-standard ports, https,
 *   and the inclusion of the CGI parameters)
 * - There is now a layer representing the CGI environment variables
 *   (module Env).
 *
 * Revision 1.8  2000/06/25 22:34:43  gerd
 * 	Added labels to arguments.
 *
 * Revision 1.7  2000/06/25 21:40:36  gerd
 * 	Added printer.
 *
 * Revision 1.6  2000/06/25 21:15:48  gerd
 * 	Checked thread-safety.
 *
 * Revision 1.5  2000/05/16 22:29:36  gerd
 * 	Added support for two common file upload bugs.
 *
 * Revision 1.4  2000/04/15 16:47:27  gerd
 * 	Last minor changes before releasing 0.6.
 *
 * Revision 1.3  2000/04/15 13:09:01  gerd
 * 	Implemented uploads to temporary files.
 *
 * Revision 1.2  2000/03/02 01:15:30  gerd
 * 	Updated.
 *
 * Revision 1.1  2000/02/25 15:21:12  gerd
 * 	Initial revision.
 *
 *
 *)