forked from SWI-Prolog/packages-http
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_header.pl
2787 lines (2513 loc) · 84.8 KB
/
http_header.pl
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
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2002-2020, University of Amsterdam
VU University Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(http_header,
[ http_read_request/2, % +Stream, -Request
http_read_reply_header/2, % +Stream, -Reply
http_reply/2, % +What, +Stream
http_reply/3, % +What, +Stream, +HdrExtra
http_reply/4, % +What, +Stream, +HdrExtra, -Code
http_reply/5, % +What, +Stream, +HdrExtra, +Context,
% -Code
http_reply/6, % +What, +Stream, +HdrExtra, +Context,
% +Request, -Code
http_reply_header/3, % +Stream, +What, +HdrExtra
http_status_reply/4, % +Status, +Out, +HdrExtra, -Code
http_status_reply/5, % +Status, +Out, +HdrExtra,
% +Context, -Code
http_timestamp/2, % +Time, -HTTP string
http_post_data/3, % +Stream, +Data, +HdrExtra
http_read_header/2, % +Fd, -Header
http_parse_header/2, % +Codes, -Header
http_parse_header_value/3, % +Header, +HeaderValue, -MediaTypes
http_join_headers/3, % +Default, +InHdr, -OutHdr
http_update_encoding/3, % +HeaderIn, -Encoding, -HeaderOut
http_update_connection/4, % +HeaderIn, +Request, -Connection, -HeaderOut
http_update_transfer/4 % +HeaderIn, +Request, -Transfer, -HeaderOut
]).
:- autoload(html_write,
[ print_html/2, print_html/1, page/4, html/3,
html_print_length/2
]).
:- if(exists_source(http_exception)).
:- autoload(http_exception,[map_exception_to_http_status/4]).
:- endif.
:- autoload(mimepack,[mime_pack/3]).
:- autoload(mimetype,[file_mime_type/2]).
:- autoload(library(apply),[maplist/2]).
:- autoload(library(base64),[base64/2]).
:- use_module(library(debug),[debug/3,debugging/1]).
:- autoload(library(error),[syntax_error/1,domain_error/2]).
:- autoload(library(lists),[append/3,member/2,select/3,delete/3]).
:- autoload(library(memfile),
[ new_memory_file/1, open_memory_file/3,
free_memory_file/1, open_memory_file/4,
size_memory_file/3
]).
:- autoload(library(option),[option/3,option/2]).
:- autoload(library(pairs),[pairs_values/2]).
:- autoload(library(readutil),
[read_line_to_codes/2,read_line_to_codes/3]).
:- autoload(library(sgml_write),[xml_write/3]).
:- autoload(library(socket),[gethostname/1]).
:- autoload(library(uri),
[ uri_components/2, uri_data/3, uri_encoded/3, uri_query_components/2
]).
:- autoload(library(url),[parse_url_search/2]).
:- autoload(library(dcg/basics),
[ integer/3, atom/3, whites/2, blanks_to_nl/2, string/3,
number/3, blanks/2, float/3, nonblanks/3, eos/2
]).
:- use_module(library(settings),[setting/4,setting/2]).
:- multifile
http:status_page/3, % +Status, +Context, -HTML
http:status_reply/3, % +Status, -Reply, +Options
http:serialize_reply/2, % +Reply, -Body
http:post_data_hook/3, % +Data, +Out, +HdrExtra
http:mime_type_encoding/2. % +MimeType, -Encoding
% see http_update_transfer/4.
:- setting(http:chunked_transfer, oneof([never,on_request,if_possible]),
on_request, 'When to use Transfer-Encoding: Chunked').
/** <module> Handling HTTP headers
The library library(http/http_header) provides primitives for parsing
and composing HTTP headers. Its functionality is normally hidden by the
other parts of the HTTP server and client libraries.
*/
:- discontiguous
term_expansion/2.
/*******************************
* READ REQUEST *
*******************************/
%! http_read_request(+FdIn:stream, -Request) is det.
%
% Read an HTTP request-header from FdIn and return the broken-down
% request fields as +Name(+Value) pairs in a list. Request is
% unified to =end_of_file= if FdIn is at the end of input.
http_read_request(In, Request) :-
catch(read_line_to_codes(In, Codes), E, true),
( var(E)
-> ( Codes == end_of_file
-> debug(http(header), 'end-of-file', []),
Request = end_of_file
; debug(http(header), 'First line: ~s', [Codes]),
Request = [input(In)|Request1],
phrase(request(In, Request1), Codes),
( Request1 = [unknown(Text)|_]
-> string_codes(S, Text),
syntax_error(http_request(S))
; true
)
)
; ( debugging(http(request))
-> message_to_string(E, Msg),
debug(http(request), "Exception reading 1st line: ~s", [Msg])
; true
),
Request = end_of_file
).
%! http_read_reply_header(+FdIn, -Reply)
%
% Read the HTTP reply header. Throws an exception if the current
% input does not contain a valid reply header.
http_read_reply_header(In, [input(In)|Reply]) :-
read_line_to_codes(In, Codes),
( Codes == end_of_file
-> debug(http(header), 'end-of-file', []),
throw(error(syntax(http_reply_header, end_of_file), _))
; debug(http(header), 'First line: ~s~n', [Codes]),
( phrase(reply(In, Reply), Codes)
-> true
; atom_codes(Header, Codes),
syntax_error(http_reply_header(Header))
)
).
/*******************************
* FORMULATE REPLY *
*******************************/
%! http_reply(+Data, +Out:stream) is det.
%! http_reply(+Data, +Out:stream, +HdrExtra) is det.
%! http_reply(+Data, +Out:stream, +HdrExtra, -Code) is det.
%! http_reply(+Data, +Out:stream, +HdrExtra, +Context, -Code) is det.
%! http_reply(+Data, +Out:stream, +HdrExtra, +Context, +Request, -Code) is det.
%
% Compose a complete HTTP reply from the term Data using
% additional headers from HdrExtra to the output stream Out.
% ExtraHeader is a list of Field(Value). Data is one of:
%
% * html(HTML)
% HTML tokens as produced by html//1 from html_write.pl
%
% * file(+MimeType, +FileName)
% Reply content of FileName using MimeType
%
% * file(+MimeType, +FileName, +Range)
% Reply partial content of FileName with given MimeType
%
% * tmp_file(+MimeType, +FileName)
% Same as =file=, but do not include modification time
%
% * bytes(+MimeType, +Bytes)
% Send a sequence of Bytes with the indicated MimeType.
% Bytes is either a string of character codes 0..255 or
% list of integers in the range 0..255. Out-of-bound codes
% result in a representation error exception.
%
% * stream(+In, +Len)
% Reply content of stream.
%
% * cgi_stream(+In, +Len)
% Reply content of stream, which should start with an
% HTTP header, followed by a blank line. This is the
% typical output from a CGI script.
%
% * Status
% HTTP status report as defined by http_status_reply/4.
%
% @param HdrExtra provides additional reply-header fields, encoded
% as Name(Value). It can also contain a field
% content_length(-Len) to _retrieve_ the
% value of the Content-length header that is replied.
% @param Code is the numeric HTTP status code sent
%
% @tbd Complete documentation
http_reply(What, Out) :-
http_reply(What, Out, [connection(close)], _).
http_reply(Data, Out, HdrExtra) :-
http_reply(Data, Out, HdrExtra, _Code).
http_reply(Data, Out, HdrExtra, Code) :-
http_reply(Data, Out, HdrExtra, [], Code).
http_reply(Data, Out, HdrExtra, Context, Code) :-
http_reply(Data, Out, HdrExtra, Context, [method(get)], Code).
http_reply(Data, Out, HdrExtra, _Context, Request, Code) :-
byte_count(Out, C0),
memberchk(method(Method), Request),
catch(http_reply_data(Data, Out, HdrExtra, Method, Code), E, true),
!,
( var(E)
-> true
; ( E = error(io_error(write,_), _)
; E = error(socket_error(_,_), _)
)
-> byte_count(Out, C1),
Sent is C1 - C0,
throw(error(http_write_short(Data, Sent), _))
; E = error(timeout_error(write, _), _)
-> throw(E)
; map_exception_to_http_status(E, Status, NewHdr, NewContext)
-> http_status_reply(Status, Out, NewHdr, NewContext, Request, Code)
; throw(E)
).
http_reply(Status, Out, HdrExtra, Context, Request, Code) :-
http_status_reply(Status, Out, HdrExtra, Context, Request, Code).
:- if(\+current_predicate(map_exception_to_http_status/4)).
map_exception_to_http_status(_E, _Status, _NewHdr, _NewContext) :-
fail.
:- endif.
:- meta_predicate
if_no_head(0, +).
%! http_reply_data(+Data, +Out, +HdrExtra, +Method, -Code) is semidet.
%
% Fails if Data is not a defined reply-data format, but a status
% term. See http_reply/3 and http_status_reply/6.
%
% @error Various I/O errors.
http_reply_data(Data, Out, HdrExtra, Method, Code) :-
http_reply_data_(Data, Out, HdrExtra, Method, Code),
flush_output(Out).
http_reply_data_(html(HTML), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(html(HTML), HdrExtra, Code), Header),
send_reply_header(Out, Header),
if_no_head(print_html(Out, HTML), Method).
http_reply_data_(file(Type, File), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(file(Type, File), HdrExtra, Code), Header),
reply_file(Out, File, Header, Method).
http_reply_data_(gzip_file(Type, File), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(gzip_file(Type, File), HdrExtra, Code), Header),
reply_file(Out, File, Header, Method).
http_reply_data_(file(Type, File, Range), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(file(Type, File, Range), HdrExtra, Code), Header),
reply_file_range(Out, File, Header, Range, Method).
http_reply_data_(tmp_file(Type, File), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(tmp_file(Type, File), HdrExtra, Code), Header),
reply_file(Out, File, Header, Method).
http_reply_data_(bytes(Type, Bytes), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(bytes(Type, Bytes), HdrExtra, Code), Header),
send_reply_header(Out, Header),
if_no_head(format(Out, '~s', [Bytes]), Method).
http_reply_data_(stream(In, Len), Out, HdrExtra, Method, Code) :-
!,
phrase(reply_header(cgi_data(Len), HdrExtra, Code), Header),
copy_stream(Out, In, Header, Method, 0, end).
http_reply_data_(cgi_stream(In, Len), Out, HdrExtra, Method, Code) :-
!,
http_read_header(In, CgiHeader),
seek(In, 0, current, Pos),
Size is Len - Pos,
http_join_headers(HdrExtra, CgiHeader, Hdr2),
phrase(reply_header(cgi_data(Size), Hdr2, Code), Header),
copy_stream(Out, In, Header, Method, 0, end).
if_no_head(_, head) :-
!.
if_no_head(Goal, _) :-
call(Goal).
reply_file(Out, _File, Header, head) :-
!,
send_reply_header(Out, Header).
reply_file(Out, File, Header, _) :-
setup_call_cleanup(
open(File, read, In, [type(binary)]),
copy_stream(Out, In, Header, 0, end),
close(In)).
reply_file_range(Out, _File, Header, _Range, head) :-
!,
send_reply_header(Out, Header).
reply_file_range(Out, File, Header, bytes(From, To), _) :-
setup_call_cleanup(
open(File, read, In, [type(binary)]),
copy_stream(Out, In, Header, From, To),
close(In)).
copy_stream(Out, _, Header, head, _, _) :-
!,
send_reply_header(Out, Header).
copy_stream(Out, In, Header, _, From, To) :-
copy_stream(Out, In, Header, From, To).
copy_stream(Out, In, Header, From, To) :-
( From == 0
-> true
; seek(In, From, bof, _)
),
peek_byte(In, _),
send_reply_header(Out, Header),
( To == end
-> copy_stream_data(In, Out)
; Len is To - From,
copy_stream_data(In, Out, Len)
).
%! http_status_reply(+Status, +Out, +HdrExtra, -Code) is det.
%! http_status_reply(+Status, +Out, +HdrExtra, +Context, -Code) is det.
%! http_status_reply(+Status, +Out, +HdrExtra, +Context, +Request, -Code) is det.
%
% Emit HTML non-200 status reports. Such requests are always sent
% as UTF-8 documents.
%
% Status can be one of the following:
% - authorise(Method)
% Challenge authorization. Method is one of
% - basic(Realm)
% - digest(Digest)
% - authorise(basic,Realm)
% Same as authorise(basic(Realm)). Deprecated.
% - bad_request(ErrorTerm)
% - busy
% - created(Location)
% - forbidden(Url)
% - moved(To)
% - moved_temporary(To)
% - no_content
% - not_acceptable(WhyHtml)
% - not_found(Path)
% - method_not_allowed(Method, Path)
% - not_modified
% - resource_error(ErrorTerm)
% - see_other(To)
% - switching_protocols(Goal,Options)
% - server_error(ErrorTerm)
% - unavailable(WhyHtml)
http_status_reply(Status, Out, Options) :-
_{header:HdrExtra, context:Context, code:Code, method:Method} :< Options,
http_status_reply(Status, Out, HdrExtra, Context, [method(Method)], Code).
http_status_reply(Status, Out, HdrExtra, Code) :-
http_status_reply(Status, Out, HdrExtra, [], Code).
http_status_reply(Status, Out, HdrExtra, Context, Code) :-
http_status_reply(Status, Out, HdrExtra, Context, [method(get)], Code).
http_status_reply(Status, Out, HdrExtra, Context, Request, Code) :-
option(method(Method), Request, get),
parsed_accept(Request, Accept),
status_reply_flush(Status, Out,
_{ context: Context,
method: Method,
code: Code,
accept: Accept,
header: HdrExtra
}).
parsed_accept(Request, Accept) :-
memberchk(accept(Accept0), Request),
http_parse_header_value(accept, Accept0, Accept1),
!,
Accept = Accept1.
parsed_accept(_, [ media(text/html, [], 0.1, []),
media(_, [], 0.01, [])
]).
status_reply_flush(Status, Out, Options) :-
status_reply(Status, Out, Options),
!,
flush_output(Out).
%! status_reply(+Status, +Out, +Options:dict)
%
% Formulate a non-200 reply and send it to the stream Out. Options
% is a dict containing:
%
% - header
% - context
% - method
% - code
% - accept
% Replies without content
status_reply(no_content, Out, Options) :-
!,
phrase(reply_header(status(no_content), Options), Header),
send_reply_header(Out, Header).
status_reply(switching_protocols(_Goal,SwitchOptions), Out, Options) :-
!,
( option(headers(Extra1), SwitchOptions)
-> true
; option(header(Extra1), SwitchOptions, [])
),
http_join_headers(Options.header, Extra1, HdrExtra),
phrase(reply_header(status(switching_protocols),
Options.put(header,HdrExtra)), Header),
send_reply_header(Out, Header).
status_reply(authorise(basic, ''), Out, Options) :-
!,
status_reply(authorise(basic), Out, Options).
status_reply(authorise(basic, Realm), Out, Options) :-
!,
status_reply(authorise(basic(Realm)), Out, Options).
status_reply(not_modified, Out, Options) :-
!,
phrase(reply_header(status(not_modified), Options), Header),
send_reply_header(Out, Header).
% aliases (compatibility)
status_reply(busy, Out, Options) :-
status_reply(service_unavailable(busy), Out, Options).
status_reply(unavailable(Why), Out, Options) :-
status_reply(service_unavailable(Why), Out, Options).
status_reply(resource_error(Why), Out, Options) :-
status_reply(service_unavailable(Why), Out, Options).
% replies with content
status_reply(Status, Out, Options) :-
status_has_content(Status),
status_page_hook(Status, Reply, Options),
serialize_body(Reply, Body),
Status =.. List,
append(List, [Body], ExList),
ExStatus =.. ExList,
phrase(reply_header(ExStatus, Options), Header),
send_reply_header(Out, Header),
reply_status_body(Out, Body, Options).
%! status_has_content(+StatusTerm, -HTTPCode)
%
% True when StatusTerm is a status that usually comes with an
% expanatory content message.
status_has_content(created(_Location)).
status_has_content(moved(_To)).
status_has_content(moved_temporary(_To)).
status_has_content(gone(_URL)).
status_has_content(see_other(_To)).
status_has_content(bad_request(_ErrorTerm)).
status_has_content(authorise(_Method)).
status_has_content(forbidden(_URL)).
status_has_content(not_found(_URL)).
status_has_content(method_not_allowed(_Method, _URL)).
status_has_content(not_acceptable(_Why)).
status_has_content(server_error(_ErrorTerm)).
status_has_content(service_unavailable(_Why)).
%! serialize_body(+Reply, -Body) is det.
%
% Serialize the reply as returned by status_page_hook/3 into a term:
%
% - body(Type, Encoding, Content)
% In this term, Type is the media type, Encoding is the
% required wire encoding and Content a string representing the
% content.
serialize_body(Reply, Body) :-
http:serialize_reply(Reply, Body),
!.
serialize_body(html_tokens(Tokens), body(text/html, utf8, Content)) :-
!,
with_output_to(string(Content), print_html(Tokens)).
serialize_body(Reply, Reply) :-
Reply = body(_,_,_),
!.
serialize_body(Reply, _) :-
domain_error(http_reply_body, Reply).
reply_status_body(_, _, Options) :-
Options.method == head,
!.
reply_status_body(Out, body(_Type, Encoding, Content), _Options) :-
( Encoding == octet
-> format(Out, '~s', [Content])
; setup_call_cleanup(
set_stream(Out, encoding(Encoding)),
format(Out, '~s', [Content]),
set_stream(Out, encoding(octet)))
).
%! http:serialize_reply(+Reply, -Body) is semidet.
%
% Multifile hook to serialize the result of http:status_reply/3
% into a term
%
% - body(Type, Encoding, Content)
% In this term, Type is the media type, Encoding is the
% required wire encoding and Content a string representing the
% content.
%! status_page_hook(+Term, -Reply, +Options) is det.
%
% Calls the following two hooks to generate an HTML page from a
% status reply.
%
% - http:status_reply(+Term, -Reply, +Options)
% Provide non-HTML description of the (non-200) reply.
% The term Reply is handed to serialize_body/2, calling
% the hook http:serialize_reply/2.
% - http:status_page(+Term, +Context, -HTML)
% - http:status_page(+Code, +Context, -HTML)
%
% @arg Term is the status term, e.g., not_found(URL)
% @see http:status_page/3
status_page_hook(Term, Reply, Options) :-
Context = Options.context,
functor(Term, Name, _),
status_number_fact(Name, Code),
( Options.code = Code,
http:status_reply(Term, Reply, Options)
; http:status_page(Term, Context, HTML),
Reply = html_tokens(HTML)
; http:status_page(Code, Context, HTML), % deprecated
Reply = html_tokens(HTML)
),
!.
status_page_hook(created(Location), html_tokens(HTML), _Options) :-
phrase(page([ title('201 Created')
],
[ h1('Created'),
p(['The document was created ',
a(href(Location), ' Here')
]),
\address
]),
HTML).
status_page_hook(moved(To), html_tokens(HTML), _Options) :-
phrase(page([ title('301 Moved Permanently')
],
[ h1('Moved Permanently'),
p(['The document has moved ',
a(href(To), ' Here')
]),
\address
]),
HTML).
status_page_hook(moved_temporary(To), html_tokens(HTML), _Options) :-
phrase(page([ title('302 Moved Temporary')
],
[ h1('Moved Temporary'),
p(['The document is currently ',
a(href(To), ' Here')
]),
\address
]),
HTML).
status_page_hook(gone(URL), html_tokens(HTML), _Options) :-
phrase(page([ title('410 Resource Gone')
],
[ h1('Resource Gone'),
p(['The document has been removed ',
a(href(URL), ' from here')
]),
\address
]),
HTML).
status_page_hook(see_other(To), html_tokens(HTML), _Options) :-
phrase(page([ title('303 See Other')
],
[ h1('See Other'),
p(['See other document ',
a(href(To), ' Here')
]),
\address
]),
HTML).
status_page_hook(bad_request(ErrorTerm), html_tokens(HTML), _Options) :-
'$messages':translate_message(ErrorTerm, Lines, []),
phrase(page([ title('400 Bad Request')
],
[ h1('Bad Request'),
p(\html_message_lines(Lines)),
\address
]),
HTML).
status_page_hook(authorise(_Method), html_tokens(HTML), _Options):-
phrase(page([ title('401 Authorization Required')
],
[ h1('Authorization Required'),
p(['This server could not verify that you ',
'are authorized to access the document ',
'requested. Either you supplied the wrong ',
'credentials (e.g., bad password), or your ',
'browser doesn\'t understand how to supply ',
'the credentials required.'
]),
\address
]),
HTML).
status_page_hook(forbidden(URL), html_tokens(HTML), _Options) :-
phrase(page([ title('403 Forbidden')
],
[ h1('Forbidden'),
p(['You don\'t have permission to access ', URL,
' on this server'
]),
\address
]),
HTML).
status_page_hook(not_found(URL), html_tokens(HTML), _Options) :-
phrase(page([ title('404 Not Found')
],
[ h1('Not Found'),
p(['The requested URL ', tt(URL),
' was not found on this server'
]),
\address
]),
HTML).
status_page_hook(method_not_allowed(Method,URL), html_tokens(HTML), _Options) :-
upcase_atom(Method, UMethod),
phrase(page([ title('405 Method not allowed')
],
[ h1('Method not allowed'),
p(['The requested URL ', tt(URL),
' does not support method ', tt(UMethod), '.'
]),
\address
]),
HTML).
status_page_hook(not_acceptable(WhyHTML), html_tokens(HTML), _Options) :-
phrase(page([ title('406 Not Acceptable')
],
[ h1('Not Acceptable'),
WhyHTML,
\address
]),
HTML).
status_page_hook(server_error(ErrorTerm), html_tokens(HTML), _Options) :-
'$messages':translate_message(ErrorTerm, Lines, []),
phrase(page([ title('500 Internal server error')
],
[ h1('Internal server error'),
p(\html_message_lines(Lines)),
\address
]),
HTML).
status_page_hook(service_unavailable(Why), html_tokens(HTML), _Options) :-
phrase(page([ title('503 Service Unavailable')
],
[ h1('Service Unavailable'),
\unavailable(Why),
\address
]),
HTML).
unavailable(busy) -->
html(p(['The server is temporarily out of resources, ',
'please try again later'])).
unavailable(error(Formal,Context)) -->
{ '$messages':translate_message(error(Formal,Context), Lines, []) },
html_message_lines(Lines).
unavailable(HTML) -->
html(HTML).
html_message_lines([]) -->
[].
html_message_lines([nl|T]) -->
!,
html([br([])]),
html_message_lines(T).
html_message_lines([flush]) -->
[].
html_message_lines([ansi(_Style,Fmt,Args)|T]) -->
!,
{ format(string(S), Fmt, Args)
},
html([S]),
html_message_lines(T).
html_message_lines([url(Pos)|T]) -->
!,
msg_url(Pos),
html_message_lines(T).
html_message_lines([url(URL, Label)|T]) -->
!,
html(a(href(URL), Label)),
html_message_lines(T).
html_message_lines([Fmt-Args|T]) -->
!,
{ format(string(S), Fmt, Args)
},
html([S]),
html_message_lines(T).
html_message_lines([Fmt|T]) -->
!,
{ format(string(S), Fmt, [])
},
html([S]),
html_message_lines(T).
msg_url(File:Line:Pos) -->
!,
html([File, :, Line, :, Pos]).
msg_url(File:Line) -->
!,
html([File, :, Line]).
msg_url(File) -->
html([File]).
%! http_join_headers(+Default, +Header, -Out)
%
% Append headers from Default to Header if they are not
% already part of it.
http_join_headers([], H, H).
http_join_headers([H|T], Hdr0, Hdr) :-
functor(H, N, A),
functor(H2, N, A),
member(H2, Hdr0),
!,
http_join_headers(T, Hdr0, Hdr).
http_join_headers([H|T], Hdr0, [H|Hdr]) :-
http_join_headers(T, Hdr0, Hdr).
%! http_update_encoding(+HeaderIn, -Encoding, -HeaderOut)
%
% Allow for rewrite of the header, adjusting the encoding. We
% distinguish three options. If the user announces `text', we
% always use UTF-8 encoding. If the user announces charset=utf-8
% we use UTF-8 and otherwise we use octet (raw) encoding.
% Alternatively we could dynamically choose for ASCII, ISO-Latin-1
% or UTF-8.
http_update_encoding(Header0, utf8, [content_type(Type)|Header]) :-
select(content_type(Type0), Header0, Header),
sub_atom(Type0, 0, _, _, 'text/'),
!,
( sub_atom(Type0, S, _, _, ';')
-> sub_atom(Type0, 0, S, _, B)
; B = Type0
),
atom_concat(B, '; charset=UTF-8', Type).
http_update_encoding(Header, Encoding, Header) :-
memberchk(content_type(Type), Header),
( sub_atom_icasechk(Type, _, 'utf-8')
-> Encoding = utf8
; http:mime_type_encoding(Type, Encoding)
-> true
; mime_type_encoding(Type, Encoding)
).
http_update_encoding(Header, octet, Header).
%! mime_type_encoding(+MimeType, -Encoding) is semidet.
%
% Encoding is the (default) character encoding for MimeType. Hooked by
% http:mime_type_encoding/2.
mime_type_encoding('application/json', utf8).
mime_type_encoding('application/jsonrequest', utf8).
mime_type_encoding('application/x-prolog', utf8).
mime_type_encoding('application/n-quads', utf8).
mime_type_encoding('application/n-triples', utf8).
mime_type_encoding('application/sparql-query', utf8).
mime_type_encoding('application/trig', utf8).
mime_type_encoding('application/sparql-results+json', utf8).
mime_type_encoding('application/sparql-results+xml', utf8).
%! http:mime_type_encoding(+MimeType, -Encoding) is semidet.
%
% Encoding is the (default) character encoding for MimeType. This is
% used for setting the encoding for HTTP replies after the user calls
% format('Content-type: <MIME type>~n'). This hook is called before
% mime_type_encoding/2. This default defines `utf8` for JSON and
% Turtle derived =|application/|= MIME types.
%! http_update_connection(+CGIHeader, +Request, -Connection, -Header)
%
% Merge keep-alive information from Request and CGIHeader into
% Header.
http_update_connection(CgiHeader, Request, Connect,
[connection(Connect)|Rest]) :-
select(connection(CgiConn), CgiHeader, Rest),
!,
connection(Request, ReqConnection),
join_connection(ReqConnection, CgiConn, Connect).
http_update_connection(CgiHeader, Request, Connect,
[connection(Connect)|CgiHeader]) :-
connection(Request, Connect).
join_connection(Keep1, Keep2, Connection) :-
( downcase_atom(Keep1, 'keep-alive'),
downcase_atom(Keep2, 'keep-alive')
-> Connection = 'Keep-Alive'
; Connection = close
).
%! connection(+Header, -Connection)
%
% Extract the desired connection from a header.
connection(Header, Close) :-
( memberchk(connection(Connection), Header)
-> Close = Connection
; memberchk(http_version(1-X), Header),
X >= 1
-> Close = 'Keep-Alive'
; Close = close
).
%! http_update_transfer(+Request, +CGIHeader, -Transfer, -Header)
%
% Decide on the transfer encoding from the Request and the CGI
% header. The behaviour depends on the setting
% http:chunked_transfer. If =never=, even explitic requests are
% ignored. If =on_request=, chunked encoding is used if requested
% through the CGI header and allowed by the client. If
% =if_possible=, chunked encoding is used whenever the client
% allows for it, which is interpreted as the client supporting
% HTTP 1.1 or higher.
%
% Chunked encoding is more space efficient and allows the client
% to start processing partial results. The drawback is that errors
% lead to incomplete pages instead of a nicely formatted complete
% page.
http_update_transfer(Request, CgiHeader, Transfer, Header) :-
setting(http:chunked_transfer, When),
http_update_transfer(When, Request, CgiHeader, Transfer, Header).
http_update_transfer(never, _, CgiHeader, none, Header) :-
!,
delete(CgiHeader, transfer_encoding(_), Header).
http_update_transfer(_, _, CgiHeader, none, Header) :-
memberchk(location(_), CgiHeader),
!,
delete(CgiHeader, transfer_encoding(_), Header).
http_update_transfer(_, Request, CgiHeader, Transfer, Header) :-
select(transfer_encoding(CgiTransfer), CgiHeader, Rest),
!,
transfer(Request, ReqConnection),
join_transfer(ReqConnection, CgiTransfer, Transfer),
( Transfer == none
-> Header = Rest
; Header = [transfer_encoding(Transfer)|Rest]
).
http_update_transfer(if_possible, Request, CgiHeader, Transfer, Header) :-
transfer(Request, Transfer),
Transfer \== none,
!,
Header = [transfer_encoding(Transfer)|CgiHeader].
http_update_transfer(_, _, CgiHeader, none, CgiHeader).
join_transfer(chunked, chunked, chunked) :- !.
join_transfer(_, _, none).
%! transfer(+Header, -Connection)
%
% Extract the desired connection from a header.
transfer(Header, Transfer) :-
( memberchk(transfer_encoding(Transfer0), Header)
-> Transfer = Transfer0
; memberchk(http_version(1-X), Header),
X >= 1
-> Transfer = chunked
; Transfer = none
).
%! content_length_in_encoding(+Encoding, +In, -Bytes)
%
% Determine hom many bytes are required to represent the data from
% stream In using the given encoding. Fails if the data cannot be
% represented with the given encoding.
content_length_in_encoding(Enc, Stream, Bytes) :-
stream_property(Stream, position(Here)),
setup_call_cleanup(
open_null_stream(Out),
( set_stream(Out, encoding(Enc)),
catch(copy_stream_data(Stream, Out), _, fail),
flush_output(Out),
byte_count(Out, Bytes)
),
( close(Out, [force(true)]),
set_stream_position(Stream, Here)
)).
/*******************************
* POST SUPPORT *
*******************************/
%! http_post_data(+Data, +Out:stream, +HdrExtra) is det.
%
% Send data on behalf on an HTTP POST request. This predicate is
% normally called by http_post/4 from http_client.pl to send the
% POST data to the server. Data is one of:
%
% * html(+Tokens)
% Result of html//1 from html_write.pl
%
% * json(+Term)
% Posting a JSON query and processing the JSON reply (or any other
% reply understood by http_read_data/3) is simple as
% =|http_post(URL, json(Term), Reply, [])|=, where Term is a JSON
% term as described in json.pl and reply is of the same format if
% the server replies with JSON, when using module =|:-
% use_module(library(http/http_json))|=. Note that the module is
% used in both http server and http client, see
% library(http/http_json).
%
% * xml(+Term)
% Post the result of xml_write/3 using the Mime-type
% =|text/xml|=
%
% * xml(+Type, +Term)
% Post the result of xml_write/3 using the given Mime-type
% and an empty option list to xml_write/3.
%
% * xml(+Type, +Term, +Options)
% Post the result of xml_write/3 using the given Mime-type
% and option list for xml_write/3.
%
% * file(+File)
% Send contents of a file. Mime-type is determined by
% file_mime_type/2.
%
% * file(+Type, +File)
% Send file with content of indicated mime-type.
%
% * memory_file(+Type, +Handle)
% Similar to file(+Type, +File), but using a memory file
% instead of a real file. See new_memory_file/1.
%
% * codes(+Codes)
% As codes(text/plain, Codes).
%
% * codes(+Type, +Codes)
% Send Codes using the indicated MIME-type.
%
% * bytes(+Type, +Bytes)
% Send Bytes using the indicated MIME-type. Bytes is either a
% string of character codes 0..255 or list of integers in the
% range 0..255. Out-of-bound codes result in a representation
% error exception.
%
% * atom(+Atom)
% As atom(text/plain, Atom).
%