forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgi.d
More file actions
4029 lines (3336 loc) · 121 KB
/
cgi.d
File metadata and controls
4029 lines (3336 loc) · 121 KB
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
// 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
/++
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;
---
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:
```
$_GET["var"] == cgi.get["var"]
$_POST["var"] == cgi.post["var"]
$_COOKIE["var"] == cgi.cookies["var"]
```
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.
```
echo("hello"); == cgi.write("hello");
$_SERVER["REMOTE_ADDR"] == cgi.remoteAddress
$_SERVER["HTTP_HOST"] == cgi.host
```
See_Also:
You may also want to see dom.d, web.d, and html.d for more code for making
web applications. database.d, mysql.d, postgres.d, and sqlite.d can help in
accessing databases.
If you are looking to access a web application via HTTP, try curl.d.
Copyright:
cgi.d copyright 2008-2016, Adam D. Ruppe. Provided under the Boost Software License.
Yes, this file is almost eight years old, and yes, it is still actively maintained and used.
+/
module arsd.cgi;
static import std.file;
version(embedded_httpd) {
version(linux)
version=embedded_httpd_processes;
else
version=embedded_httpd_threads;
/*
version(with_openssl) {
pragma(lib, "crypto");
pragma(lib, "ssl");
}
*/
}
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.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;
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); }
}
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 }
/*
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 (only implemented for fastcgi right now)
*/
/** Initializes it with command line arguments (for easy testing) */
this(string[] args) {
// 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) {
switch(nextArgIs) {
case "cookie":
auto info = breakUp(arg);
if(_cookie.length)
_cookie ~= "; ";
_cookie ~= std.uri.encodeComponent(info[0]) ~ "=" ~ std.uri.encodeComponent(info[1]);
break;
case "port":
port = to!int(arg);
break;
case "referrer":
referrer = arg;
break;
case "remote-address":
remoteAddress = arg;
break;
case "user-agent":
userAgent = arg;
break;
case "authorization":
authorization = arg;
break;
case "userpass":
authorization = "Basic " ~ Base64.encode(cast(immutable(ubyte)[]) (arg)).idup;
break;
case "origin":
origin = arg;
break;
case "accept":
accept = arg;
break;
case "last-event-id":
lastEventId = arg;
break;
case "https":
if(arg == "yes")
https = true;
break;
case "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;
break;
case "host":
host = arg;
break;
default:
// 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.toLower() == "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) {
auto parts = breakUp(arg);
_post[parts[0]] ~= 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);
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;
}
/** 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?
}
get = getGetVariables(queryString);
auto ugh = decodeVariables(queryString);
getArray = assumeUnique(ugh);
// 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.toLower().indexOf("keep-alive") != -1)
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) {
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) {
if(maxContentLength > 0 && contentLength > maxContentLength) {
setResponseStatus("413 Request entity too large");
write("You tried to upload a file that is too large.");
close();
throw new Exception("POST too large");
}
prepareForIncomingDataChunks(contentType, contentLength);
int processChunk(in ubyte[] chunk) {
if(chunk.length > contentLength) {
handleIncomingDataChunk(chunk[0..contentLength]);
amountReceived += contentLength;
contentLength = 0;
return 1;
} else {
handleIncomingDataChunk(chunk);
contentLength -= chunk.length;
amountReceived += chunk.length;
}
if(contentLength == 0)
return 1;
onRequestBodyDataReceived(amountReceived, originalContentLength);
return 0;
}
if(readdata is null) {
foreach(ubyte[] chunk; stdin.byChunk(iis ? contentLength : 4096))
if(processChunk(chunk))
break;
} else {
// we have a custom data source..
auto chunk = readdata();
while(chunk.length) {
if(processChunk(chunk))
break;
chunk = readdata();
}
}
onRequestBodyDataReceived(amountReceived, originalContentLength);
postArray = assumeUnique(pps._post);
filesArray = assumeUnique(pps._files);
files = keepLastOf(filesArray);
post = keepLastOf(postArray);
cleanUpPostDataState();
}
version(preserveData)
originalPostData = data;
}
// fixme: remote_user script name
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;
}
/// Cleans up any temporary files. Do not use the object
/// after calling this.
///
/// NOTE: it is called automatically by GenericMain
// FIXME: this should be called if the constructor fails too, if it has created some garbage...
void dispose() {
foreach(file; files) {
if(!file.contentInMemory)
if(std.file.exists(file.contentFilename))
std.file.remove(file.contentFilename);
}
}
private {
struct PostParserState {
string contentType;
string boundary;
string localBoundary; // the ones used at the end or something lol
bool isMultipart;
ulong expectedLength;
ulong contentConsumed;
immutable(ubyte)[] buffer;
// multipart parsing state
int whatDoWeWant;
bool weHaveAPart;
string[] thisOnesHeaders;
immutable(ubyte)[] thisOnesData;
UploadedFile piece;
bool isFile = false;
size_t memoryCommitted;
// do NOT keep mutable references to these anywhere!
// I assume they are unique in the constructor once we're all done getting data.
string[][string] _post;
UploadedFile[][string] _files;
}
PostParserState pps;
}
/// This represents a file the user uploaded via a POST request.
static struct UploadedFile {
/// If you want to create one of these structs for yourself from some data,
/// use this function.
static UploadedFile fromData(immutable(void)[] data, string name = null) {
Cgi.UploadedFile f;
f.filename = name;
f.content = cast(immutable(ubyte)[]) data;
f.contentInMemory = true;
return f;
}
string name; /// The name of the form element.
string filename; /// The filename the user set.
string contentType; /// The MIME type the user's browser reported. (Not reliable.)
/**
For small files, cgi.d will buffer the uploaded file in memory, and make it
directly accessible to you through the content member. I find this very convenient
and somewhat efficient, since it can avoid hitting the disk entirely. (I
often want to inspect and modify the file anyway!)
I find the file is very large, it is undesirable to eat that much memory just
for a file buffer. In those cases, if you pass a large enough value for maxContentLength
to the constructor so they are accepted, cgi.d will write the content to a temporary
file that you can re-read later.
You can override this behavior by subclassing Cgi and overriding the protected
handlePostChunk method. Note that the object is not initialized when you
write that method - the http headers are available, but the cgi.post method
is not. You may parse the file as it streams in using this method.
Anyway, if the file is small enough to be in memory, contentInMemory will be
set to true, and the content is available in the content member.
If not, contentInMemory will be set to false, and the content saved in a file,
whose name will be available in the contentFilename member.
Tip: if you know you are always dealing with small files, and want the convenience
of ignoring this member, construct Cgi with a small maxContentLength. Then, if
a large file comes in, it simply throws an exception (and HTTP error response)
instead of trying to handle it.
The default value of maxContentLength in the constructor is for small files.
*/
bool contentInMemory = true; // the default ought to always be true
immutable(ubyte)[] content; /// The actual content of the file, if contentInMemory == true
string contentFilename; /// the file where we dumped the content, if contentInMemory == false. Note that if you want to keep it, you MUST move the file, since otherwise it is considered garbage when cgi is disposed.
void writeToFile(string filenameToSaveTo) {
import std.file;
if(contentInMemory)
std.file.write(filenameToSaveTo, content);
else
std.file.rename(contentFilename, filenameToSaveTo);
}
}
// given a content type and length, decide what we're going to do with the data..
protected void prepareForIncomingDataChunks(string contentType, ulong contentLength) {
pps.expectedLength = contentLength;
auto terminator = contentType.indexOf(";");
if(terminator == -1)
terminator = contentType.length;
pps.contentType = contentType[0 .. terminator];
auto b = contentType[terminator .. $];
if(b.length) {
auto idx = b.indexOf("boundary=");
if(idx != -1) {
pps.boundary = b[idx + "boundary=".length .. $];
pps.localBoundary = "\r\n--" ~ pps.boundary;
}
}
// while a content type SHOULD be sent according to the RFC, it is
// not required. We're told we SHOULD guess by looking at the content
// but it seems to me that this only happens when it is urlencoded.
if(pps.contentType == "application/x-www-form-urlencoded" || pps.contentType == "") {
pps.isMultipart = false;
} else if(pps.contentType == "multipart/form-data") {
pps.isMultipart = true;
enforce(pps.boundary.length, "no boundary");
} else {
// FIXME: should set a http error code too
throw new Exception("unknown request content type: " ~ pps.contentType);
}
}
// handles streaming POST data. If you handle some other content type, you should
// override this. If the data isn't the content type you want, you ought to call
// super.handleIncomingDataChunk so regular forms and files still work.
// FIXME: I do some copying in here that I'm pretty sure is unnecessary, and the
// file stuff I'm sure is inefficient. But, my guess is the real bottleneck is network
// input anyway, so I'm not going to get too worked up about it right now.
protected void handleIncomingDataChunk(const(ubyte)[] chunk) {
if(chunk.length == 0)
return;
assert(chunk.length <= 32 * 1024 * 1024); // we use chunk size as a memory constraint thing, so
// if we're passed big chunks, it might throw unnecessarily.
// just pass it smaller chunks at a time.
if(pps.isMultipart) {
// multipart/form-data
void pieceHasNewContent() {
// we just grew the piece's buffer. Do we have to switch to file backing?
if(pps.piece.contentInMemory) {
if(pps.piece.content.length <= 10 * 1024 * 1024)
// meh, I'm ok with it.
return;
else {
// this is too big.
if(!pps.isFile)
throw new Exception("Request entity too large"); // a variable this big is kinda ridiculous, just reject it.
else {
// a file this large is probably acceptable though... let's use a backing file.
pps.piece.contentInMemory = false;
// FIXME: say... how do we intend to delete these things? cgi.dispose perhaps.
int count = 0;
pps.piece.contentFilename = getTempDirectory() ~ "arsd_cgi_uploaded_file_" ~ to!string(getUtcTime()) ~ "-" ~ to!string(count);
// odds are this loop will never be entered, but we want it just in case.
while(std.file.exists(pps.piece.contentFilename)) {
count++;
pps.piece.contentFilename = getTempDirectory() ~ "arsd_cgi_uploaded_file_" ~ to!string(getUtcTime()) ~ "-" ~ to!string(count);
}
// I hope this creates the file pretty quickly, or the loop might be useless...
// FIXME: maybe I should write some kind of custom transaction here.
std.file.write(pps.piece.contentFilename, pps.piece.content);
pps.piece.content = null;
}
}
} else {
// it's already in a file, so just append it to what we have
if(pps.piece.content.length) {
// FIXME: this is surely very inefficient... we'll be calling this by 4kb chunk...
std.file.append(pps.piece.contentFilename, pps.piece.content);
pps.piece.content = null;
}
}
}
void commitPart() {
if(!pps.weHaveAPart)
return;
pieceHasNewContent(); // be sure the new content is handled every time
if(pps.isFile) {