-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathcgi.d
12539 lines (10374 loc) · 374 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
// add the Range header in there too. should return 206
// 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. Offers both lower- and higher- level api options among other common (optional) things like websocket and event source serving support, session management, and job scheduling.
---
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;
---
Or:
---
import arsd.cgi;
class MyApi : WebObject {
@UrlName("")
string hello(string name = null) {
if(name is null)
return "Hello, world!";
else
return "Hello, " ~ name;
}
}
mixin DispatcherMain!(
"/".serveApi!MyApi
);
---
$(NOTE
Please note that using the higher-level api will add a dependency on arsd.dom and arsd.jsvar to your application.
If you use `dmd -i` or `ldc2 -i` to build, it will just work, but with dub, you will have do `dub add arsd-official:jsvar`
and `dub add arsd-official:dom` yourself.
)
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
)
Please note: the default port for http is 8085 and for scgi is 4000. I recommend you set your own by the command line argument in a startup script instead of relying on any hard coded defaults. It is possible though to code your own with [RequestServer], however.
Build_Configurations:
cgi.d tries to be flexible to meet your needs. It is possible to configure it both at runtime (by writing your own `main` function and constructing a [RequestServer] object) or at compile time using the `version` switch to the compiler or a dub `subConfiguration`.
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 for dub builds. You can run the program then connect directly to it from your browser. Note: prior to version 11, this would be embedded_httpd_processes on Linux and embedded_httpd_threads everywhere else. It now means embedded_httpd_hybrid everywhere supported and embedded_httpd_threads everywhere else.
* `cgi` for traditional cgi binaries. These are run by an outside web server as-needed to handle requests.
* `fastcgi` for FastCGI builds. FastCGI is managed from an outside helper, there's one built into Microsoft IIS, Apache httpd, and Lighttpd, and a generic program you can use with nginx called `spawn-fcgi`. If you don't already know how to use it, I suggest you use one of the other modes.
* `scgi` for SCGI builds. SCGI is a simplified form of FastCGI, where you run the server as an application service which is proxied by your outside webserver. Please note: on nginx make sure you add `scgi_param PATH_INFO $document_uri;` to the config!
* `stdio_http` for speaking raw http over stdin and stdout. This is made for systemd services. See [RequestServer.serveSingleHttpConnectionOnStdio] for more information.
)
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_hybrid`
- A HTTP server that uses a combination of processes, threads, and fibers to better handle large numbers of idle connections. Recommended if you are going to serve websockets in a non-local application.
* - `-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.
* - `-version=stdio_http`
- The embedded HTTP server will be spoken over stdin and stdout.
* + Tweaks
+ (can be used together with others)
* - `-version=cgi_with_websocket`
- The CGI class has websocket server support. (This is on by default now.)
* - `-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.
)
For example,
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 (this causes it to call FCGX_OpenSocket, which can work on nginx too).
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.
Command_line_interface:
If using [GenericMain] or [DispatcherMain], an application using arsd.cgi will offer a command line interface out of the box.
See [RequestServer.listenSpec] for more information.
Simulating_requests:
If you are using one of the [GenericMain] or [DispatcherMain] mixins, or main with your own call to [RequestServer.trySimulatedRequest], you can simulate requests from your command-ine shell. Call the program like this:
$(CONSOLE
./yourprogram GET / name=adr
)
And it will print the result to stdout instead of running a server, regardless of build more..
CGI_Setup_tips:
On Apache, you may do `SetHandler cgi-script` in your `.htaccess` file to set a particular file to be run through the cgi program. Note that all "subdirectories" of it also run the program; if you configure `/foo` to be a cgi script, then going to `/foo/bar` will call your cgi handler function with `cgi.pathInfo == "/bar"`.
Overview_Of_Basic_Concepts:
cgi.d offers both lower-level handler apis as well as higher-level auto-dispatcher apis. For a lower-level handler function, you'll probably want to review the following functions:
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]
Websockets: [Websocket], [websocketRequested], [acceptWebsocket]. For websockets, use the `embedded_httpd_hybrid` build mode for best results, because it is optimized for handling large numbers of idle connections compared to the other build modes.
Overriding behavior for special cases streaming input data: see the virtual functions [Cgi.handleIncomingDataChunk], [Cgi.prepareForIncomingDataChunks], [Cgi.cleanUpPostDataState]
A basic program using the lower-level api might look like:
---
import arsd.cgi;
// you write a request handler which always takes a Cgi object
void handler(Cgi cgi) {
/+
when the user goes to your site, suppose you are being hosted at http://example.com/yourapp
If the user goes to http://example.com/yourapp/test?name=value
then the url will be parsed out into the following pieces:
cgi.pathInfo == "/test". This is everything after yourapp's name. (If you are doing an embedded http server, your app's name is blank, so pathInfo will be the whole path of the url.)
cgi.scriptName == "yourapp". With an embedded http server, this will be blank.
cgi.host == "example.com"
cgi.https == false
cgi.queryString == "name=value" (there's also cgi.search, which will be "?name=value", including the ?)
The query string is further parsed into the `get` and `getArray` members, so:
cgi.get == ["name": "value"], meaning you can do `cgi.get["name"] == "value"`
And
cgi.getArray == ["name": ["value"]].
Why is there both `get` and `getArray`? The standard allows names to be repeated. This can be very useful,
it is how http forms naturally pass multiple items like a set of checkboxes. So `getArray` is the complete data
if you need it. But since so often you only care about one value, the `get` member provides more convenient access.
We can use these members to process the request and build link urls. Other info from the request are in other members, we'll look at them later.
+/
switch(cgi.pathInfo) {
// the home page will be a small html form that can set a cookie.
case "/":
cgi.write(`<!DOCTYPE html>
<html>
<body>
<form method="POST" action="set-cookie">
<label>Your name: <input type="text" name="name" /></label>
<input type="submit" value="Submit" />
</form>
</body>
</html>
`, true); // the , true tells it that this is the one, complete response i want to send, allowing some optimizations.
break;
// POSTing to this will set a cookie with our submitted name
case "/set-cookie":
// HTTP has a number of request methods (also called "verbs") to tell
// what you should do with the given resource.
// The most common are GET and POST, the ones used in html forms.
// You can check which one was used with the `cgi.requestMethod` property.
if(cgi.requestMethod == Cgi.RequestMethod.POST) {
// headers like redirections need to be set before we call `write`
cgi.setResponseLocation("read-cookie");
// just like how url params go into cgi.get/getArray, form data submitted in a POST
// body go to cgi.post/postArray. Please note that a POST request can also have get
// params in addition to post params.
//
// There's also a convenience function `cgi.request("name")` which checks post first,
// then get if it isn't found there, and then returns a default value if it is in neither.
if("name" in cgi.post) {
// we can set cookies with a method too
// again, cookies need to be set before calling `cgi.write`, since they
// are a kind of header.
cgi.setCookie("name" , cgi.post["name"]);
}
// the user will probably never see this, since the response location
// is an automatic redirect, but it is still best to say something anyway
cgi.write("Redirecting you to see the cookie...", true);
} else {
// you can write out response codes and headers
// as well as response bodies
//
// But always check the cgi docs before using the generic
// `header` method - if there is a specific method for your
// header, use it before resorting to the generic one to avoid
// a header value from being sent twice.
cgi.setResponseLocation("405 Method Not Allowed");
// there is no special accept member, so you can use the generic header function
cgi.header("Accept: POST");
// but content type does have a method, so prefer to use it:
cgi.setResponseContentType("text/plain");
// all the headers are buffered, and will be sent upon the first body
// write. you can actually modify some of them before sending if need be.
cgi.write("You must use the POST http verb on this resource.", true);
}
break;
// and GETting this will read the cookie back out
case "/read-cookie":
// I did NOT pass `,true` here because this is writing a partial response.
// It is possible to stream data to the user in chunks by writing partial
// responses the calling `cgi.flush();` to send the partial response immediately.
// normally, you'd only send partial chunks if you have to - it is better to build
// a response as a whole and send it as a whole whenever possible - but here I want
// to demo that you can.
cgi.write("Hello, ");
if("name" in cgi.cookies) {
import arsd.dom; // dom.d provides a lot of helpers for html
// since the cookie is set, we need to write it out properly to
// avoid cross-site scripting attacks.
//
// Getting this stuff right automatically is a benefit of using the higher
// level apis, but this demo is to show the fundamental building blocks, so
// we're responsible to take care of it.
cgi.write(htmlEntitiesEncode(cgi.cookies["name"]));
} else {
cgi.write("friend");
}
// note that I never called cgi.setResponseContentType, since the default is text/html.
// it doesn't hurt to do it explicitly though, just remember to do it before any cgi.write
// calls.
break;
default:
// no path matched
cgi.setResponseStatus("404 Not Found");
cgi.write("Resource not found.", true);
}
}
// and this adds the boilerplate to set up a server according to the
// compile version configuration and call your handler as requests come in
mixin GenericMain!handler; // the `handler` here is the name of your function
---
Even if you plan to always use the higher-level apis, I still recommend you at least familiarize yourself with the lower level functions, since they provide the lightest weight, most flexible options to get down to business if you ever need them.
In the lower-level api, the [Cgi] object represents your HTTP transaction. It has functions to describe the request and for you to send your response. It leaves the details of how you o it up to you. The general guideline though is to avoid depending any variables outside your handler function, since there's no guarantee they will survive to another handler. You can use global vars as a lazy initialized cache, but you should always be ready in case it is empty. (One exception: if you use `-version=embedded_httpd_threads -version=cgi_no_fork`, then you can rely on it more, but you should still really write things assuming your function won't have anything survive beyond its return for max scalability and compatibility.)
A basic program using the higher-level apis might look like:
---
/+
import arsd.cgi;
struct LoginData {
string currentUser;
}
class AppClass : WebObject {
string foo() {}
}
mixin DispatcherMain!(
"/assets/.serveStaticFileDirectory("assets/", true), // serve the files in the assets subdirectory
"/".serveApi!AppClass,
"/thing/".serveRestObject,
);
+/
---
Guide_for_PHP_users:
(Please note: I wrote this section in 2008. A lot of PHP hosts still ran 4.x back then, so it was common to avoid using classes - introduced in php 5 - to maintain compatibility! If you're coming from php more recently, this may not be relevant anymore, but still might help you.)
If you are coming from old-style 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.webtemplate], and maybe some functions from my old [arsd.html] for more code for making
web applications. dom and webtemplate are used by the higher-level api here in cgi.d.
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 [arsd.http2].
Copyright:
cgi.d copyright 2008-2023, Adam D. Ruppe. Provided under the Boost Software License.
Yes, this file is old, and yes, it is still actively maintained and used.
History:
An import of `arsd.core` was added on March 21, 2023 (dub v11.0). Prior to this, the module's default configuration was completely stand-alone. You must now include the `core.d` file in your builds with `cgi.d`.
This change is primarily to integrate the event loops across the library, allowing you to more easily use cgi.d along with my other libraries like simpledisplay and http2.d. Previously, you'd have to run separate helper threads. Now, they can all automatically work together.
+/
module arsd.cgi;
// FIXME: Nullable!T can be a checkbox that enables/disables the T on the automatic form
// and a SumType!(T, R) can be a radio box to pick between T and R to disclose the extra boxes on the automatic form
/++
This micro-example uses the [dispatcher] api to act as a simple http file server, serving files found in the current directory and its children.
+/
version(Demo)
unittest {
import arsd.cgi;
mixin DispatcherMain!(
"/".serveStaticFileDirectory(null, true)
);
}
/++
Same as the previous example, but written out long-form without the use of [DispatcherMain] nor [GenericMain].
+/
version(Demo)
unittest {
import arsd.cgi;
void requestHandler(Cgi cgi) {
cgi.dispatcher!(
"/".serveStaticFileDirectory(null, true)
);
}
// mixin GenericMain!requestHandler would add this function:
void main(string[] args) {
// this is all the content of [cgiMainImpl] which you can also call
// cgi.d embeds a few add on functions like real time event forwarders
// and session servers it can run in other processes. this spawns them, if needed.
if(tryAddonServers(args))
return;
// cgi.d allows you to easily simulate http requests from the command line,
// without actually starting a server. this function will do that.
if(trySimulatedRequest!(requestHandler, Cgi)(args))
return;
RequestServer server;
// you can change the default port here if you like
// server.listeningPort = 9000;
// then call this to let the command line args override your default
server.configureFromCommandLine(args);
// here is where you could print out the listeningPort to the user if you wanted
// and serve the request(s) according to the compile configuration
server.serve!(requestHandler)();
// or you could explicitly choose a serve mode like this:
// server.serveEmbeddedHttp!requestHandler();
}
}
/++
cgi.d has built-in testing helpers too. These will provide mock requests and mock sessions that
otherwise run through the rest of the internal mechanisms to call your functions without actually
spinning up a server.
+/
version(Demo)
unittest {
import arsd.cgi;
void requestHandler(Cgi cgi) {
}
// D doesn't let me embed a unittest inside an example unittest
// so this is a function, but you can do it however in your real program
/* unittest */ void runTests() {
auto tester = new CgiTester(&requestHandler);
auto response = tester.GET("/");
assert(response.code == 200);
}
}
/++
The session system works via a built-in spawnable server.
Bugs:
Requires addon servers, which are not implemented yet on Windows.
+/
version(Posix)
version(Demo)
unittest {
import arsd.cgi;
struct SessionData {
string userId;
}
void handler(Cgi cgi) {
auto session = cgi.getSessionObject!SessionData;
if(cgi.pathInfo == "/login") {
session.userId = cgi.queryString;
cgi.setResponseLocation("view");
} else {
cgi.write(session.userId);
}
}
mixin GenericMain!handler;
}
static import std.file;
static import arsd.core;
version(Posix)
import arsd.core : makeNonBlocking;
import arsd.core : encodeUriComponent, decodeUriComponent;
// 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(FreeBSD) {
// not implemented on bsds
} else version(OpenBSD) {
// I never implemented the fancy stuff there either
} else {
version=with_breaking_cgi_features;
version=with_sendfd;
version=with_addon_servers;
}
}
}
version(Windows) {
version(minimal) {
} else {
// not too concerned about gdc here since the mingw version is fairly new as well
version=with_breaking_cgi_features;
}
}
// FIXME: can use the arsd.core function now but it is trivial anyway tbh
void cloexec(int fd) {
version(Posix) {
import core.sys.posix.fcntl;
fcntl(fd, F_SETFD, FD_CLOEXEC);
}
}
void cloexec(Socket s) {
version(Posix) {
import core.sys.posix.fcntl;
fcntl(s.handle, F_SETFD, FD_CLOEXEC);
}
}
// 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(OSX)
version = embedded_httpd_threads;
else
version=embedded_httpd_hybrid;
/*
version(with_openssl) {
pragma(lib, "crypto");
pragma(lib, "ssl");
}
*/
}
version(embedded_httpd_hybrid) {
version=embedded_httpd_threads;
version(cgi_no_fork) {} else version(Posix)
version=cgi_use_fork;
version=cgi_use_fiber;
}
version(cgi_use_fork)
enum cgi_use_fork_default = true;
else
enum cgi_use_fork_default = false;
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.
// 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.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");
}
do {
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:
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); }
void close() {
std.stdio.stdin.close;
}
}
}
/// 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 }
/+
ubyte[] perRequestMemoryPool;
void[] perRequestMemoryPoolWithPointers;
// might want to just slice the buffer itself too when we happened to have gotten a full request inside it and don't need to decode
// then the buffer also can be recycled if it is set.
// we might also be able to set memory recyclable true by default, but then the property getters set it to false. but not all the things are property getters. but realistically anything except benchmarks are gonna get something lol so meh.
/+
struct VariableCollection {
string[] opIndex(string name) {
}
}
/++
Call this to indicate that you've not retained any reference to the request-local memory (including all strings returned from the Cgi object) outside the request (you can .idup anything you need to store) and it is thus free to be freed or reused by another request.
Most handlers should be able to call this; retaining memory is the exception in any cgi program, but since I can't prove it from inside the library, it plays it safe and lets the GC manage it unless you opt into this behavior. All cgi.d functions will duplicate strings if needed (e.g. session ids from cookies) so unless you're doing something yourself, this should be ok.
History:
Added
+/
public void recycleMemory() {
}
+/
/++
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'
--session name=value (these are added to a mock session, changes to the session are printed out as dummy response headers)
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;