-
Notifications
You must be signed in to change notification settings - Fork 14
/
cgi.d
9424 lines (7856 loc) · 274 KB
/
cgi.d
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
// FIXME: if an exception is thrown, we shouldn't necessarily cache...
// FIXME: there's some annoying duplication of code in the various versioned mains
// FIXME: cgi per-request arena allocator
// i need to add a bunch of type templates for validations... mayne @NotNull or NotNull!
// FIXME: I might make a cgi proxy class which can change things; the underlying one is still immutable
// but the later one can edit and simplify the api. You'd have to use the subclass tho!
/*
void foo(int f, @("test") string s) {}
void main() {
static if(is(typeof(foo) Params == __parameters))
//pragma(msg, __traits(getAttributes, Params[0]));
pragma(msg, __traits(getAttributes, Params[1..2]));
else
pragma(msg, "fail");
}
*/
// Note: spawn-fcgi can help with fastcgi on nginx
// FIXME: to do: add openssl optionally
// make sure embedded_httpd doesn't send two answers if one writes() then dies
// future direction: websocket as a separate process that you can sendfile to for an async passoff of those long-lived connections
/*
Session manager process: it spawns a new process, passing a
command line argument, to just be a little key/value store
of some serializable struct. On Windows, it CreateProcess.
On Linux, it can just fork or maybe fork/exec. The session
key is in a cookie.
Server-side event process: spawns an async manager. You can
push stuff out to channel ids and the clients listen to it.
websocket process: spawns an async handler. They can talk to
each other or get info from a cgi request.
Tempting to put web.d 2.0 in here. It would:
* map urls and form generation to functions
* have data presentation magic
* do the skeleton stuff like 1.0
* auto-cache generated stuff in files (at least if pure?)
* introspect functions in json for consumers
https://linux.die.net/man/3/posix_spawn
*/
/++
Provides a uniform server-side API for CGI, FastCGI, SCGI, and HTTP web applications.
---
import arsd.cgi;
// Instead of writing your own main(), you should write a function
// that takes a Cgi param, and use mixin GenericMain
// for maximum compatibility with different web servers.
void hello(Cgi cgi) {
cgi.setResponseContentType("text/plain");
if("name" in cgi.get)
cgi.write("Hello, " ~ cgi.get["name"]);
else
cgi.write("Hello, world!");
}
mixin GenericMain!hello;
---
Test on console (works in any interface mode):
$(CONSOLE
$ ./cgi_hello GET / name=whatever
)
If using http version (default on `dub` builds, or on custom builds when passing `-version=embedded_httpd` to dmd):
$(CONSOLE
$ ./cgi_hello --port 8080
# now you can go to http://localhost:8080/?name=whatever
)
Compile_versions:
If you are using `dub`, use:
```sdlang
subConfiguration "arsd-official:cgi" "VALUE_HERE"
```
or to dub.json:
```json
"subConfigurations": {"arsd-official:cgi": "VALUE_HERE"}
```
to change versions. The possible options for `VALUE_HERE` are:
$(LIST
* `embedded_httpd` for the embedded httpd version (built-in web server). This is the default.
* `cgi` for traditional cgi binaries.
* `fastcgi` for FastCGI builds.
* `scgi` for SCGI builds.
)
With dmd, use:
$(TABLE_ROWS
* + Interfaces
+ (mutually exclusive)
* - `-version=plain_cgi`
- The default building the module alone without dub - a traditional, plain CGI executable will be generated.
* - `-version=embedded_httpd`
- A HTTP server will be embedded in the generated executable. This is default when building with dub.
* - `-version=fastcgi`
- A FastCGI executable will be generated.
* - `-version=scgi`
- A SCGI (SimpleCGI) executable will be generated.
* - `-version=embedded_httpd_threads`
- The embedded HTTP server will use a single process with a thread pool. (use instead of plain `embedded_httpd` if you want this specific implementation)
* - `-version=embedded_httpd_processes`
- The embedded HTTP server will use a prefork style process pool. (use instead of plain `embedded_httpd` if you want this specific implementation)
* - `-version=embedded_httpd_processes_accept_after_fork`
- It will call accept() in each child process, after forking. This is currently the only option, though I am experimenting with other ideas. You probably should NOT specify this right now.
* + Tweaks
+ (can be used together with others)
* - `-version=cgi_with_websocket`
- The CGI class has websocket server support.
* - `-version=with_openssl`
- not currently used
* - `-version=cgi_embedded_sessions`
- The session server will be embedded in the cgi.d server process
* - `-version=cgi_session_server_process`
- The session will be provided in a separate process, provided by cgi.d.
)
Compile_and_run:
For CGI, `dmd yourfile.d cgi.d` then put the executable in your cgi-bin directory.
For FastCGI: `dmd yourfile.d cgi.d -version=fastcgi` and run it. spawn-fcgi helps on nginx. You can put the file in the directory for Apache. On IIS, run it with a port on the command line.
For SCGI: `dmd yourfile.d cgi.d -version=scgi` and run the executable, providing a port number on the command line.
For an embedded HTTP server, run `dmd yourfile.d cgi.d -version=embedded_httpd` and run the generated program. It listens on port 8085 by default. You can change this on the command line with the --port option when running your program.
You can also simulate a request by passing parameters on the command line, like:
$(CONSOLE
./yourprogram GET / name=adr
)
And it will print the result to stdout.
CGI_Setup_tips:
On Apache, you may do `SetHandler cgi-script` in your `.htaccess` file.
Integration_tips:
cgi.d works well with dom.d for generating html. You may also use web.d for other utilities and automatic api wrapping.
dom.d usage:
---
import arsd.cgi;
import arsd.dom;
void hello_dom(Cgi cgi) {
auto document = new Document();
static import std.file;
// parse the file in strict mode, requiring it to be well-formed UTF-8 XHTML
// (You'll appreciate this if you've ever had to deal with a missing </div>
// or something in a php or erb template before that would randomly mess up
// the output in your browser. Just check it and throw an exception early!)
//
// You could also hard-code a template or load one at compile time with an
// import expression, but you might appreciate making it a regular file
// because that means it can be more easily edited by the frontend team and
// they can see their changes without needing to recompile the program.
//
// Note on CTFE: if you do choose to load a static file at compile time,
// you *can* parse it in CTFE using enum, which will cause it to throw at
// compile time, which is kinda cool too. Be careful in modifying that document,
// though, as it will be a static instance. You might want to clone on on demand,
// or perhaps modify it lazily as you print it out. (Try element.tree, it returns
// a range of elements which you could send through std.algorithm functions. But
// since my selector implementation doesn't work on that level yet, you'll find that
// harder to use. Of course, you could make a static list of matching elements and
// then use a simple e is e2 predicate... :) )
document.parseUtf8(std.file.read("your_template.html"), true, true);
// fill in data using DOM functions, so placing it is in the hands of HTML
// and it will be properly encoded as text too.
//
// Plain html templates can't run server side logic, but I think that's a
// good thing - it keeps them simple. You may choose to extend the html,
// but I think it is best to try to stick to standard elements and fill them
// in with requested data with IDs or class names. A further benefit of
// this is the designer can also highlight data based on sources in the CSS.
//
// However, all of dom.d is available, so you can format your data however
// you like. You can do partial templates with innerHTML too, or perhaps better,
// injecting cloned nodes from a partial document.
//
// There's a lot of possibilities.
document["#name"].innerText = cgi.request("name", "default name");
// send the document to the browser. The second argument to `cgi.write`
// indicates that this is all the data at once, enabling a few small
// optimizations.
cgi.write(document.toString(), true);
}
---
Concepts:
Input: [Cgi.get], [Cgi.post], [Cgi.request], [Cgi.files], [Cgi.cookies], [Cgi.pathInfo], [Cgi.requestMethod],
and HTTP headers ([Cgi.headers], [Cgi.userAgent], [Cgi.referrer], [Cgi.accept], [Cgi.authorization], [Cgi.lastEventId])
Output: [Cgi.write], [Cgi.header], [Cgi.setResponseStatus], [Cgi.setResponseContentType], [Cgi.gzipResponse]
Cookies: [Cgi.setCookie], [Cgi.clearCookie], [Cgi.cookie], [Cgi.cookies]
Caching: [Cgi.setResponseExpires], [Cgi.updateResponseExpires], [Cgi.setCache]
Redirections: [Cgi.setResponseLocation]
Other Information: [Cgi.remoteAddress], [Cgi.https], [Cgi.port], [Cgi.scriptName], [Cgi.requestUri], [Cgi.getCurrentCompleteUri], [Cgi.onRequestBodyDataReceived]
Overriding behavior: [Cgi.handleIncomingDataChunk], [Cgi.prepareForIncomingDataChunks], [Cgi.cleanUpPostDataState]
Installing: Apache, IIS, CGI, FastCGI, SCGI, embedded HTTPD (not recommended for production use)
Guide_for_PHP_users:
If you are coming from PHP, here's a quick guide to help you get started:
$(SIDE_BY_SIDE
$(COLUMN
```php
<?php
$foo = $_POST["foo"];
$bar = $_GET["bar"];
$baz = $_COOKIE["baz"];
$user_ip = $_SERVER["REMOTE_ADDR"];
$host = $_SERVER["HTTP_HOST"];
$path = $_SERVER["PATH_INFO"];
setcookie("baz", "some value");
echo "hello!";
?>
```
)
$(COLUMN
---
import arsd.cgi;
void app(Cgi cgi) {
string foo = cgi.post["foo"];
string bar = cgi.get["bar"];
string baz = cgi.cookies["baz"];
string user_ip = cgi.remoteAddress;
string host = cgi.host;
string path = cgi.pathInfo;
cgi.setCookie("baz", "some value");
cgi.write("hello!");
}
mixin GenericMain!app
---
)
)
$(H3 Array elements)
In PHP, you can give a form element a name like `"something[]"`, and then
`$_POST["something"]` gives an array. In D, you can use whatever name
you want, and access an array of values with the `cgi.getArray["name"]` and
`cgi.postArray["name"]` members.
$(H3 Databases)
PHP has a lot of stuff in its standard library. cgi.d doesn't include most
of these, but the rest of my arsd repository has much of it. For example,
to access a MySQL database, download `database.d` and `mysql.d` from my
github repo, and try this code (assuming, of course, your database is
set up):
---
import arsd.cgi;
import arsd.mysql;
void app(Cgi cgi) {
auto database = new MySql("localhost", "username", "password", "database_name");
foreach(row; mysql.query("SELECT count(id) FROM people"))
cgi.write(row[0] ~ " people in database");
}
mixin GenericMain!app;
---
Similar modules are available for PostgreSQL, Microsoft SQL Server, and SQLite databases,
implementing the same basic interface.
See_Also:
You may also want to see [arsd.dom], [arsd.web], and [arsd.html] for more code for making
web applications.
For working with json, try [arsd.jsvar].
[arsd.database], [arsd.mysql], [arsd.postgres], [arsd.mssql], and [arsd.sqlite] can help in
accessing databases.
If you are looking to access a web application via HTTP, try [std.net.curl], [arsd.curl], or [arsd.http2].
Copyright:
cgi.d copyright 2008-2019, Adam D. Ruppe. Provided under the Boost Software License.
Yes, this file is almost ten years old, and yes, it is still actively maintained and used.
+/
module arsd.cgi;
static import std.file;
// for a single thread, linear request thing, use:
// -version=embedded_httpd_threads -version=cgi_no_threads
version(Posix) {
version(CRuntime_Musl) {
} else version(minimal) {
} else {
version(GNU) {
// GDC doesn't support static foreach so I had to cheat on it :(
} else {
version=with_breaking_cgi_features;
version=with_sendfd;
version=with_addon_servers;
}
}
}
// the servers must know about the connections to talk to them; the interfaces are vital
version(with_addon_servers)
version=with_addon_servers_connections;
version(embedded_httpd) {
version(linux)
version=embedded_httpd_processes;
else {
version=embedded_httpd_threads;
}
/*
version(with_openssl) {
pragma(lib, "crypto");
pragma(lib, "ssl");
}
*/
}
version(embedded_httpd_processes)
version=embedded_httpd_processes_accept_after_fork; // I am getting much better average performance on this, so just keeping it. But the other way MIGHT help keep the variation down so i wanna keep the code to play with later
version(embedded_httpd_threads) {
// unless the user overrides the default..
version(cgi_session_server_process)
{}
else
version=cgi_embedded_sessions;
}
version(scgi) {
// unless the user overrides the default..
version(cgi_session_server_process)
{}
else
version=cgi_embedded_sessions;
}
// fall back if the other is not defined so we can cleanly version it below
version(cgi_embedded_sessions) {}
else version=cgi_session_server_process;
version=cgi_with_websocket;
enum long defaultMaxContentLength = 5_000_000;
/*
To do a file download offer in the browser:
cgi.setResponseContentType("text/csv");
cgi.header("Content-Disposition: attachment; filename=\"customers.csv\"");
*/
// FIXME: the location header is supposed to be an absolute url I guess.
// FIXME: would be cool to flush part of a dom document before complete
// somehow in here and dom.d.
// FIXME: 100 Continue in the nph section? Probably belongs on the
// httpd class though.
// these are public so you can mixin GenericMain.
// FIXME: use a function level import instead!
public import std.string;
public import std.stdio;
public import std.conv;
import std.uri;
import std.uni;
import std.algorithm.comparison;
import std.algorithm.searching;
import std.exception;
import std.base64;
static import std.algorithm;
import std.datetime;
import std.range;
import std.process;
import std.zlib;
T[] consume(T)(T[] range, int count) {
if(count > range.length)
count = range.length;
return range[count..$];
}
int locationOf(T)(T[] data, string item) {
const(ubyte[]) d = cast(const(ubyte[])) data;
const(ubyte[]) i = cast(const(ubyte[])) item;
// this is a vague sanity check to ensure we aren't getting insanely
// sized input that will infinite loop below. it should never happen;
// even huge file uploads ought to come in smaller individual pieces.
if(d.length > (int.max/2))
throw new Exception("excessive block of input");
for(int a = 0; a < d.length; a++) {
if(a + i.length > d.length)
return -1;
if(d[a..a+i.length] == i)
return a;
}
return -1;
}
/// If you are doing a custom cgi class, mixing this in can take care of
/// the required constructors for you
mixin template ForwardCgiConstructors() {
this(long maxContentLength = defaultMaxContentLength,
string[string] env = null,
const(ubyte)[] delegate() readdata = null,
void delegate(const(ubyte)[]) _rawDataOutput = null,
void delegate() _flush = null
) { super(maxContentLength, env, readdata, _rawDataOutput, _flush); }
this(string[] args) { super(args); }
this(
BufferedInputRange inputData,
string address, ushort _port,
int pathInfoStarts = 0,
bool _https = false,
void delegate(const(ubyte)[]) _rawDataOutput = null,
void delegate() _flush = null,
// this pointer tells if the connection is supposed to be closed after we handle this
bool* closeConnection = null)
{
super(inputData, address, _port, pathInfoStarts, _https, _rawDataOutput, _flush, closeConnection);
}
this(BufferedInputRange ir, bool* closeConnection) { super(ir, closeConnection); }
}
/// thrown when a connection is closed remotely while we waiting on data from it
class ConnectionClosedException : Exception {
this(string message, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
super(message, file, line, next);
}
}
version(Windows) {
// FIXME: ugly hack to solve stdin exception problems on Windows:
// reading stdin results in StdioException (Bad file descriptor)
// this is probably due to http://d.puremagic.com/issues/show_bug.cgi?id=3425
private struct stdin {
struct ByChunk { // Replicates std.stdio.ByChunk
private:
ubyte[] chunk_;
public:
this(size_t size)
in {
assert(size, "size must be larger than 0");
}
body {
chunk_ = new ubyte[](size);
popFront();
}
@property bool empty() const {
return !std.stdio.stdin.isOpen || std.stdio.stdin.eof; // Ugly, but seems to do the job
}
@property nothrow ubyte[] front() { return chunk_; }
void popFront() {
enforce(!empty, "Cannot call popFront on empty range");
chunk_ = stdin.rawRead(chunk_);
}
}
import core.sys.windows.windows;
static:
static this() {
// Set stdin to binary mode
version(Win64)
_setmode(std.stdio.stdin.fileno(), 0x8000);
else
setmode(std.stdio.stdin.fileno(), 0x8000);
}
T[] rawRead(T)(T[] buf) {
uint bytesRead;
auto result = ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf.ptr, cast(int) (buf.length * T.sizeof), &bytesRead, null);
if (!result) {
auto err = GetLastError();
if (err == 38/*ERROR_HANDLE_EOF*/ || err == 109/*ERROR_BROKEN_PIPE*/) // 'good' errors meaning end of input
return buf[0..0];
// Some other error, throw it
char* buffer;
scope(exit) LocalFree(buffer);
// FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
// FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
FormatMessageA(0x1100, null, err, 0, cast(char*)&buffer, 256, null);
throw new Exception(to!string(buffer));
}
enforce(!(bytesRead % T.sizeof), "I/O error");
return buf[0..bytesRead / T.sizeof];
}
auto byChunk(size_t sz) { return ByChunk(sz); }
}
}
/// The main interface with the web request
class Cgi {
public:
/// the methods a request can be
enum RequestMethod { GET, HEAD, POST, PUT, DELETE, // GET and POST are the ones that really work
// these are defined in the standard, but idk if they are useful for anything
OPTIONS, TRACE, CONNECT,
// These seem new, I have only recently seen them
PATCH, MERGE,
// this is an extension for when the method is not specified and you want to assume
CommandLine }
/+
/++
Cgi provides a per-request memory pool
+/
void[] allocateMemory(size_t nBytes) {
}
/// ditto
void[] reallocateMemory(void[] old, size_t nBytes) {
}
/// ditto
void freeMemory(void[] memory) {
}
+/
/*
import core.runtime;
auto args = Runtime.args();
we can call the app a few ways:
1) set up the environment variables and call the app (manually simulating CGI)
2) simulate a call automatically:
./app method 'uri'
for example:
./app get /path?arg arg2=something
Anything on the uri is treated as query string etc
on get method, further args are appended to the query string (encoded automatically)
on post method, further args are done as post
@name means import from file "name". if name == -, it uses stdin
(so info=@- means set info to the value of stdin)
Other arguments include:
--cookie name=value (these are all concated together)
--header 'X-Something: cool'
--referrer 'something'
--port 80
--remote-address some.ip.address.here
--https yes
--user-agent 'something'
--userpass 'user:pass'
--authorization 'Basic base64encoded_user:pass'
--accept 'content' // FIXME: better example
--last-event-id 'something'
--host 'something.com'
Non-simulation arguments:
--port xxx listening port for non-cgi things (valid for the cgi interfaces)
--listening-host the ip address the application should listen on, or if you want to use unix domain sockets, it is here you can set them: `--listening-host unix:filename` or, on Linux, `--listening-host abstract:name`.
*/
/** Initializes it with command line arguments (for easy testing) */
this(string[] args, void delegate(const(ubyte)[]) _rawDataOutput = null) {
rawDataOutput = _rawDataOutput;
// these are all set locally so the loop works
// without triggering errors in dmd 2.064
// we go ahead and set them at the end of it to the this version
int port;
string referrer;
string remoteAddress;
string userAgent;
string authorization;
string origin;
string accept;
string lastEventId;
bool https;
string host;
RequestMethod requestMethod;
string requestUri;
string pathInfo;
string queryString;
bool lookingForMethod;
bool lookingForUri;
string nextArgIs;
string _cookie;
string _queryString;
string[][string] _post;
string[string] _headers;
string[] breakUp(string s) {
string k, v;
auto idx = s.indexOf("=");
if(idx == -1) {
k = s;
} else {
k = s[0 .. idx];
v = s[idx + 1 .. $];
}
return [k, v];
}
lookingForMethod = true;
scriptName = args[0];
scriptFileName = args[0];
environmentVariables = cast(const) environment.toAA;
foreach(arg; args[1 .. $]) {
if(arg.startsWith("--")) {
nextArgIs = arg[2 .. $];
} else if(nextArgIs.length) {
if (nextArgIs == "cookie") {
auto info = breakUp(arg);
if(_cookie.length)
_cookie ~= "; ";
_cookie ~= std.uri.encodeComponent(info[0]) ~ "=" ~ std.uri.encodeComponent(info[1]);
}
else if (nextArgIs == "port") {
port = to!int(arg);
}
else if (nextArgIs == "referrer") {
referrer = arg;
}
else if (nextArgIs == "remote-address") {
remoteAddress = arg;
}
else if (nextArgIs == "user-agent") {
userAgent = arg;
}
else if (nextArgIs == "authorization") {
authorization = arg;
}
else if (nextArgIs == "userpass") {
authorization = "Basic " ~ Base64.encode(cast(immutable(ubyte)[]) (arg)).idup;
}
else if (nextArgIs == "origin") {
origin = arg;
}
else if (nextArgIs == "accept") {
accept = arg;
}
else if (nextArgIs == "last-event-id") {
lastEventId = arg;
}
else if (nextArgIs == "https") {
if(arg == "yes")
https = true;
}
else if (nextArgIs == "header") {
string thing, other;
auto idx = arg.indexOf(":");
if(idx == -1)
throw new Exception("need a colon in a http header");
thing = arg[0 .. idx];
other = arg[idx + 1.. $];
_headers[thing.strip.toLower()] = other.strip;
}
else if (nextArgIs == "host") {
host = arg;
}
// else
// skip, we don't know it but that's ok, it might be used elsewhere so no error
nextArgIs = null;
} else if(lookingForMethod) {
lookingForMethod = false;
lookingForUri = true;
if(arg.asLowerCase().equal("commandline"))
requestMethod = RequestMethod.CommandLine;
else
requestMethod = to!RequestMethod(arg.toUpper());
} else if(lookingForUri) {
lookingForUri = false;
requestUri = arg;
auto idx = arg.indexOf("?");
if(idx == -1)
pathInfo = arg;
else {
pathInfo = arg[0 .. idx];
_queryString = arg[idx + 1 .. $];
}
} else {
// it is an argument of some sort
if(requestMethod == Cgi.RequestMethod.POST || requestMethod == Cgi.RequestMethod.PATCH || requestMethod == Cgi.RequestMethod.PUT) {
auto parts = breakUp(arg);
_post[parts[0]] ~= parts[1];
allPostNamesInOrder ~= parts[0];
allPostValuesInOrder ~= parts[1];
} else {
if(_queryString.length)
_queryString ~= "&";
auto parts = breakUp(arg);
_queryString ~= std.uri.encodeComponent(parts[0]) ~ "=" ~ std.uri.encodeComponent(parts[1]);
}
}
}
acceptsGzip = false;
keepAliveRequested = false;
requestHeaders = cast(immutable) _headers;
cookie = _cookie;
cookiesArray = getCookieArray();
cookies = keepLastOf(cookiesArray);
queryString = _queryString;
getArray = cast(immutable) decodeVariables(queryString, "&", &allGetNamesInOrder, &allGetValuesInOrder);
get = keepLastOf(getArray);
postArray = cast(immutable) _post;
post = keepLastOf(_post);
// FIXME
filesArray = null;
files = null;
isCalledWithCommandLineArguments = true;
this.port = port;
this.referrer = referrer;
this.remoteAddress = remoteAddress;
this.userAgent = userAgent;
this.authorization = authorization;
this.origin = origin;
this.accept = accept;
this.lastEventId = lastEventId;
this.https = https;
this.host = host;
this.requestMethod = requestMethod;
this.requestUri = requestUri;
this.pathInfo = pathInfo;
this.queryString = queryString;
this.postJson = null;
}
private {
string[] allPostNamesInOrder;
string[] allPostValuesInOrder;
string[] allGetNamesInOrder;
string[] allGetValuesInOrder;
}
CgiConnectionHandle getOutputFileHandle() {
return _outputFileHandle;
}
CgiConnectionHandle _outputFileHandle = INVALID_CGI_CONNECTION_HANDLE;
/** Initializes it using a CGI or CGI-like interface */
this(long maxContentLength = defaultMaxContentLength,
// use this to override the environment variable listing
in string[string] env = null,
// and this should return a chunk of data. return empty when done
const(ubyte)[] delegate() readdata = null,
// finally, use this to do custom output if needed
void delegate(const(ubyte)[]) _rawDataOutput = null,
// to flush teh custom output
void delegate() _flush = null
)
{
// these are all set locally so the loop works
// without triggering errors in dmd 2.064
// we go ahead and set them at the end of it to the this version
int port;
string referrer;
string remoteAddress;
string userAgent;
string authorization;
string origin;
string accept;
string lastEventId;
bool https;
string host;
RequestMethod requestMethod;
string requestUri;
string pathInfo;
string queryString;
isCalledWithCommandLineArguments = false;
rawDataOutput = _rawDataOutput;
flushDelegate = _flush;
auto getenv = delegate string(string var) {
if(env is null)
return std.process.environment.get(var);
auto e = var in env;
if(e is null)
return null;
return *e;
};
environmentVariables = env is null ?
cast(const) environment.toAA :
env;
// fetching all the request headers
string[string] requestHeadersHere;
foreach(k, v; env is null ? cast(const) environment.toAA() : env) {
if(k.startsWith("HTTP_")) {
requestHeadersHere[replace(k["HTTP_".length .. $].toLower(), "_", "-")] = v;
}
}
this.requestHeaders = assumeUnique(requestHeadersHere);
requestUri = getenv("REQUEST_URI");
cookie = getenv("HTTP_COOKIE");
cookiesArray = getCookieArray();
cookies = keepLastOf(cookiesArray);
referrer = getenv("HTTP_REFERER");
userAgent = getenv("HTTP_USER_AGENT");
remoteAddress = getenv("REMOTE_ADDR");
host = getenv("HTTP_HOST");
pathInfo = getenv("PATH_INFO");
queryString = getenv("QUERY_STRING");
scriptName = getenv("SCRIPT_NAME");
{
import core.runtime;
auto sfn = getenv("SCRIPT_FILENAME");
scriptFileName = sfn.length ? sfn : Runtime.args[0];
}
bool iis = false;
// Because IIS doesn't pass requestUri, we simulate it here if it's empty.
if(requestUri.length == 0) {
// IIS sometimes includes the script name as part of the path info - we don't want that
if(pathInfo.length >= scriptName.length && (pathInfo[0 .. scriptName.length] == scriptName))
pathInfo = pathInfo[scriptName.length .. $];
requestUri = scriptName ~ pathInfo ~ (queryString.length ? ("?" ~ queryString) : "");
iis = true; // FIXME HACK - used in byChunk below - see bugzilla 6339
// FIXME: this works for apache and iis... but what about others?
}
auto ugh = decodeVariables(queryString, "&", &allGetNamesInOrder, &allGetValuesInOrder);
getArray = assumeUnique(ugh);
get = keepLastOf(getArray);
// NOTE: on shitpache, you need to specifically forward this
authorization = getenv("HTTP_AUTHORIZATION");
// this is a hack because Apache is a shitload of fuck and
// refuses to send the real header to us. Compatible
// programs should send both the standard and X- versions
// NOTE: if you have access to .htaccess or httpd.conf, you can make this
// unnecessary with mod_rewrite, so it is commented
//if(authorization.length == 0) // if the std is there, use it
// authorization = getenv("HTTP_X_AUTHORIZATION");
// the REDIRECT_HTTPS check is here because with an Apache hack, the port can become wrong
if(getenv("SERVER_PORT").length && getenv("REDIRECT_HTTPS") != "on")
port = to!int(getenv("SERVER_PORT"));
else
port = 0; // this was probably called from the command line
auto ae = getenv("HTTP_ACCEPT_ENCODING");
if(ae.length && ae.indexOf("gzip") != -1)
acceptsGzip = true;
accept = getenv("HTTP_ACCEPT");
lastEventId = getenv("HTTP_LAST_EVENT_ID");
auto ka = getenv("HTTP_CONNECTION");
if(ka.length && ka.asLowerCase().canFind("keep-alive"))
keepAliveRequested = true;
auto or = getenv("HTTP_ORIGIN");
origin = or;
auto rm = getenv("REQUEST_METHOD");
if(rm.length)
requestMethod = to!RequestMethod(getenv("REQUEST_METHOD"));
else
requestMethod = RequestMethod.CommandLine;
// FIXME: hack on REDIRECT_HTTPS; this is there because the work app uses mod_rewrite which loses the https flag! So I set it with [E=HTTPS=%HTTPS] or whatever but then it gets translated to here so i want it to still work. This is arguably wrong but meh.
https = (getenv("HTTPS") == "on" || getenv("REDIRECT_HTTPS") == "on");
// FIXME: DOCUMENT_ROOT?
// FIXME: what about PUT?
if(requestMethod == RequestMethod.POST || requestMethod == Cgi.RequestMethod.PATCH || requestMethod == Cgi.RequestMethod.PUT) {
version(preserveData) // a hack to make forwarding simpler
immutable(ubyte)[] data;
size_t amountReceived = 0;
auto contentType = getenv("CONTENT_TYPE");
// FIXME: is this ever not going to be set? I guess it depends
// on if the server de-chunks and buffers... seems like it has potential
// to be slow if they did that. The spec says it is always there though.
// And it has worked reliably for me all year in the live environment,
// but some servers might be different.
auto contentLength = to!size_t(getenv("CONTENT_LENGTH"));
immutable originalContentLength = contentLength;
if(contentLength) {