View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2007-2020, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(http_dispatch,
   38          [ http_dispatch/1,            % +Request
   39            http_handler/3,             % +Path, +Predicate, +Options
   40            http_delete_handler/1,      % +Path
   41            http_request_expansion/2,   % :Goal, +Rank
   42            http_reply_file/3,          % +File, +Options, +Request
   43            http_redirect/3,            % +How, +Path, +Request
   44            http_404/2,                 % +Options, +Request
   45            http_switch_protocol/2,     % :Goal, +Options
   46            http_current_handler/2,     % ?Path, ?Pred
   47            http_current_handler/3,     % ?Path, ?Pred, -Options
   48            http_location_by_id/2,      % +ID, -Location
   49            http_link_to_id/3,          % +ID, +Parameters, -HREF
   50            http_reload_with_parameters/3, % +Request, +Parameters, -HREF
   51            http_safe_file/2            % +Spec, +Options
   52          ]).   53:- use_module(library(lists),
   54              [ select/3, append/3, append/2, same_length/2, member/2,
   55                last/2, delete/3
   56              ]).   57:- autoload(library(apply),
   58	    [partition/4,maplist/3,maplist/2,include/3,exclude/3]).   59:- autoload(library(broadcast),[listen/2]).   60:- autoload(library(error),
   61	    [ must_be/2,
   62	      domain_error/2,
   63	      type_error/2,
   64	      instantiation_error/1,
   65	      existence_error/2,
   66	      permission_error/3
   67	    ]).   68:- autoload(library(filesex),[directory_file_path/3]).   69:- autoload(library(option),[option/3,option/2,merge_options/3]).   70:- autoload(library(pairs),[pairs_values/2]).   71:- autoload(library(time),[call_with_time_limit/2]).   72:- autoload(library(uri),
   73	    [ uri_encoded/3,
   74	      uri_data/3,
   75	      uri_components/2,
   76	      uri_query_components/2
   77	    ]).   78:- autoload(library(http/http_header),[http_timestamp/2]).   79:- autoload(library(http/http_path),[http_absolute_location/3]).   80:- autoload(library(http/mimetype),
   81	    [file_content_type/2,file_content_type/3]).   82:- autoload(library(http/thread_httpd),[http_spawn/2]).   83:- use_module(library(settings),[setting/4,setting/2]).   84
   85:- predicate_options(http_404/2, 1, [index(any)]).   86:- predicate_options(http_reply_file/3, 2,
   87                     [ cache(boolean),
   88                       mime_type(any),
   89                       static_gzip(boolean),
   90                       cached_gzip(boolean),
   91                       pass_to(http_safe_file/2, 2),
   92                       headers(list)
   93                     ]).   94:- predicate_options(http_safe_file/2, 2, [unsafe(boolean)]).   95:- predicate_options(http_switch_protocol/2, 2, []).

Dispatch requests in the HTTP server

Most code doesn't need to use this directly; instead use library(http/http_server), which combines this library with the typical HTTP libraries that most servers need.

This module can be placed between http_wrapper.pl and the application code to associate HTTP locations to predicates that serve the pages. In addition, it associates parameters with locations that deal with timeout handling and user authentication. The typical setup is:

server(Port, Options) :-
        http_server(http_dispatch,
                    [ port(Port)
                    | Options
                    ]).

:- http_handler('/index.html', write_index, []).

write_index(Request) :-
        ...

*/

  122:- setting(http:time_limit, nonneg, 300,
  123           'Time limit handling a single query (0=infinite)').
 http_handler(+Path, :Closure, +Options) is det
Register Closure as a handler for HTTP requests. Path is either an absolute path such as '/home.html' or a term Alias(Relative). Where Alias is associated with a concrete path using http:location/3 and resolved using http_absolute_location/3. Relative can be a single atom or a term `Segment1/Segment2/...`, where each element is either an atom or a variable. If a segment is a variable it matches any segment and the binding may be passed to the closure. If the last segment is a variable it may match multiple segments. This allows registering REST paths, for example:
:- http_handler(root(user/User), user(Method, User),
                [ method(Method),
                  methods([get,post,put])
                ]).

user(get, User, Request) :-
    ...
user(post, User, Request) :-
    ...

If an HTTP request arrives at the server that matches Path, Closure is called as below, where Request is the parsed HTTP request.

call(Closure, Request)

Options is a list containing the following options:

authentication(+Type)
Demand authentication. Authentication methods are pluggable. The library http_authenticate.pl provides a plugin for user/password based Basic HTTP authentication.
chunked
Use Transfer-encoding: chunked if the client allows for it.
condition(:Goal)
If present, the handler is ignored if Goal does not succeed.
content_type(+Term)
Specifies the content-type of the reply. This value is currently not used by this library. It enhances the reflexive capabilities of this library through http_current_handler/3.
id(+Atom)
Identifier of the handler. The default identifier is the predicate name. Used by http_location_by_id/2 and http_link_to_id/3.
hide_children(+Bool)
If true on a prefix-handler (see prefix), possible children are masked. This can be used to (temporary) overrule part of the tree.
method(+Method)
Declare that the handler processes Method. This is equivalent to methods([Method]). Using method(*) allows for all methods.
methods(+ListOfMethods)
Declare that the handler processes all of the given methods. If this option appears multiple times, the methods are combined.
prefix
Call Pred on any location that is a specialisation of Path. If multiple handlers match, the one with the longest path is used. Options defined with a prefix handler are the default options for paths that start with this prefix. Note that the handler acts as a fallback handler for the tree below it:
:- http_handler(/, http_404([index('index.html')]),
                [spawn(my_pool),prefix]).
priority(+Integer)
If two handlers handle the same path, the one with the highest priority is used. If equal, the last registered is used. Please be aware that the order of clauses in multifile predicates can change due to reloading files. The default priority is 0 (zero).
spawn(+SpawnOptions)
Run the handler in a separate thread. If SpawnOptions is an atom, it is interpreted as a thread pool name (see create_thread_pool/3). Otherwise the options are passed to http_spawn/2 and from there to thread_create/3. These options are typically used to set the stack limits.
time_limit(+Spec)
One of infinite, default or a positive number (seconds). If default, the value from the setting http:time_limit is taken. The default of this setting is 300 (5 minutes). See setting/2.

Note that http_handler/3 is normally invoked as a directive and processed using term-expansion. Using term-expansion ensures proper update through make/0 when the specification is modified.

Errors
- existence_error(http_location, Location)
- permission_error(http_method, Method, Location)
See also
- http_reply_file/3 and http_redirect/3 are generic handlers to serve files and achieve redirects.
  230:- dynamic handler/4.                   % Path, Action, IsPrefix, Options
  231:- multifile handler/4.  232:- dynamic generation/1.  233
  234:- meta_predicate
  235    http_handler(+, :, +),
  236    http_current_handler(?, :),
  237    http_current_handler(?, :, ?),
  238    http_request_expansion(3, +),
  239    http_switch_protocol(2, +).  240
  241http_handler(Path, Pred, Options) :-
  242    compile_handler(Path, Pred, Options, Clause),
  243    next_generation,
  244    assert(Clause).
  245
  246:- multifile
  247    system:term_expansion/2.  248
  249system:term_expansion((:- http_handler(Path, Pred, Options)), Clause) :-
  250    \+ current_prolog_flag(xref, true),
  251    prolog_load_context(module, M),
  252    compile_handler(Path, M:Pred, Options, Clause),
  253    next_generation.
 http_delete_handler(+Spec) is det
Delete handler for Spec. Typically, this should only be used for handlers that are registered dynamically. Spec is one of:
id(Id)
Delete a handler with the given id. The default id is the handler-predicate-name.
path(Path)
Delete handler that serves the given path.
  268http_delete_handler(id(Id)) :-
  269    !,
  270    clause(handler(_Path, _:Pred, _, Options), true, Ref),
  271    functor(Pred, DefID, _),
  272    option(id(Id0), Options, DefID),
  273    Id == Id0,
  274    erase(Ref),
  275    next_generation.
  276http_delete_handler(path(Path)) :-
  277    !,
  278    retractall(handler(Path, _Pred, _, _Options)),
  279    next_generation.
  280http_delete_handler(Path) :-
  281    http_delete_handler(path(Path)).
 next_generation is det
 current_generation(-G) is det
Increment the generation count.
  289next_generation :-
  290    retractall(id_location_cache(_,_,_,_)),
  291    with_mutex(http_dispatch, next_generation_unlocked).
  292
  293next_generation_unlocked :-
  294    retract(generation(G0)),
  295    !,
  296    G is G0 + 1,
  297    assert(generation(G)).
  298next_generation_unlocked :-
  299    assert(generation(1)).
  300
  301current_generation(G) :-
  302    with_mutex(http_dispatch, generation(G)),
  303    !.
  304current_generation(0).
 compile_handler(+Path, :Pred, +Options, -Clause) is det
Compile a handler specification.
  311compile_handler(Path, Pred, Options0,
  312                http_dispatch:handler(Path1, Pred, IsPrefix, Options)) :-
  313    check_path(Path, Path1, PathOptions),
  314    check_id(Options0),
  315    (   memberchk(segment_pattern(_), PathOptions)
  316    ->  IsPrefix = true,
  317        Options1 = Options0
  318    ;   select(prefix, Options0, Options1)
  319    ->  IsPrefix = true
  320    ;   IsPrefix = false,
  321        Options1 = Options0
  322    ),
  323    partition(ground, Options1, Options2, QueryOptions),
  324    Pred = M:_,
  325    maplist(qualify_option(M), Options2, Options3),
  326    combine_methods(Options3, Options4),
  327    (   QueryOptions == []
  328    ->  append(PathOptions, Options4, Options)
  329    ;   append(PathOptions, ['$extract'(QueryOptions)|Options4], Options)
  330    ).
  331
  332qualify_option(M, condition(Pred), condition(M:Pred)) :-
  333    Pred \= _:_, !.
  334qualify_option(_, Option, Option).
 combine_methods(+OptionsIn, -Options) is det
Combine method(M) and methods(MList) options into a single methods(MList) option.
  341combine_methods(Options0, Options) :-
  342    collect_methods(Options0, Options1, Methods),
  343    (   Methods == []
  344    ->  Options = Options0
  345    ;   append(Methods, Flat),
  346        sort(Flat, Unique),
  347        (   memberchk('*', Unique)
  348        ->  Final = '*'
  349        ;   Final = Unique
  350        ),
  351        Options = [methods(Final)|Options1]
  352    ).
  353
  354collect_methods([], [], []).
  355collect_methods([method(M)|T0], T, [[M]|TM]) :-
  356    !,
  357    (   M == '*'
  358    ->  true
  359    ;   must_be_method(M)
  360    ),
  361    collect_methods(T0, T, TM).
  362collect_methods([methods(M)|T0], T, [M|TM]) :-
  363    !,
  364    must_be(list, M),
  365    maplist(must_be_method, M),
  366    collect_methods(T0, T, TM).
  367collect_methods([H|T0], [H|T], TM) :-
  368    !,
  369    collect_methods(T0, T, TM).
  370
  371must_be_method(M) :-
  372    must_be(atom, M),
  373    (   method(M)
  374    ->  true
  375    ;   domain_error(http_method, M)
  376    ).
  377
  378method(get).
  379method(put).
  380method(head).
  381method(post).
  382method(delete).
  383method(patch).
  384method(options).
  385method(trace).
 check_path(+PathSpecIn, -PathSpecOut, -Options) is det
Validate the given path specification. We want one of

Similar to absolute_file_name/3, Relative can be a term Component/Component/.... Relative may be a / separated list of path segments, some of which may be variables. A variable patches any segment and its binding can be passed to the handler. If such a pattern is found Options is unified with [segment_pattern(SegmentList)].

Errors
- domain_error, type_error
See also
- http_absolute_location/3
  405check_path(Path, Path, []) :-
  406    atom(Path),
  407    !,
  408    (   sub_atom(Path, 0, _, _, /)
  409    ->  true
  410    ;   domain_error(absolute_http_location, Path)
  411    ).
  412check_path(Alias, AliasOut, Options) :-
  413    compound(Alias),
  414    Alias =.. [Name, Relative],
  415    !,
  416    local_path(Relative, Local, Options),
  417    (   sub_atom(Local, 0, _, _, /)
  418    ->  domain_error(relative_location, Relative)
  419    ;   AliasOut =.. [Name, Local]
  420    ).
  421check_path(PathSpec, _, _) :-
  422    type_error(path_or_alias, PathSpec).
  423
  424local_path(Atom, Atom, []) :-
  425    atom(Atom),
  426    !.
  427local_path(Path, Atom, Options) :-
  428    phrase(path_to_list(Path), Components),
  429    !,
  430    (   maplist(atom, Components)
  431    ->  atomic_list_concat(Components, '/', Atom),
  432        Options = []
  433    ;   append(Pre, [Var|Rest], Components),
  434        var(Var)
  435    ->  append(Pre, [''], PreSep),
  436        atomic_list_concat(PreSep, '/', Atom),
  437        Options = [segment_pattern([Var|Rest])]
  438    ).
  439local_path(Path, _, _) :-
  440    ground(Path),
  441    !,
  442    type_error(relative_location, Path).
  443local_path(Path, _, _) :-
  444    instantiation_error(Path).
  445
  446path_to_list(Var) -->
  447    { var(Var) },
  448    !,
  449    [Var].
  450path_to_list(A/B) -->
  451    !,
  452    path_to_list(A),
  453    path_to_list(B).
  454path_to_list(Atom) -->
  455    { atom(Atom) },
  456    !,
  457    [Atom].
  458path_to_list(Value) -->
  459    { must_be(atom, Value) }.
  460
  461check_id(Options) :-
  462    memberchk(id(Id), Options),
  463    !,
  464    must_be(atom, Id).
  465check_id(_).
 http_dispatch(Request) is det
Dispatch a Request using http_handler/3 registrations. It performs the following steps:
  1. Find a matching handler based on the path member of Request. If multiple handlers match due to the prefix option or variables in path segments (see http_handler/3), the longest specification is used. If multiple specifications of equal length match the one with the highest priority is used.
  2. Check that the handler matches the method member of the Request or throw permission_error(http_method, Method, Location)
  3. Expand the request using expansion hooks registered by http_request_expansion/3. This may add fields to the request, such the authenticated user, parsed parameters, etc. The hooks may also throw exceptions, notably using http_redirect/3 or by throwing http_reply(Term, ExtraHeader, Context) exceptions.
  4. Extract possible fields from the Request using e.g. method(Method) as one of the options.
  5. Call the registered closure, optionally spawning the request to a new thread or enforcing a time limit.
  491http_dispatch(Request) :-
  492    memberchk(path(Path), Request),
  493    find_handler(Path, Closure, Options),
  494    supports_method(Request, Options),
  495    expand_request(Request, Request1, Options),
  496    extract_from_request(Request1, Options),
  497    action(Closure, Request1, Options).
  498
  499extract_from_request(Request, Options) :-
  500    memberchk('$extract'(Fields), Options),
  501    !,
  502    extract_fields(Fields, Request).
  503extract_from_request(_, _).
  504
  505extract_fields([], _).
  506extract_fields([H|T], Request) :-
  507    memberchk(H, Request),
  508    extract_fields(T, Request).
 http_request_expansion(:Goal, +Rank:number)
Register Goal for expanding the HTTP request handler. Goal is called as below. If Goal fail the request is passed to the next expansion unmodified.
call(Goal, Request0, Request, Options)

If multiple goals are registered they expand the request in a pipeline starting with the expansion hook with the lowest rank.

Besides rewriting the request, for example by validating the user identity based on HTTP authentication or cookies and adding this to the request, the hook may raise HTTP exceptions to indicate a bad request, permission error, etc. See http_status_reply/4.

Initially, auth_expansion/3 is registered with rank 100 to deal with the older http:authenticate/3 hook.

  530http_request_expansion(Goal, Rank) :-
  531    throw(error(context_error(nodirective, http_request_expansion(Goal, Rank)), _)).
  532
  533:- multifile
  534    request_expansion/2.  535
  536system:term_expansion((:- http_request_expansion(Goal, Rank)),
  537                      http_dispatch:request_expansion(M:Callable, Rank)) :-
  538    must_be(number, Rank),
  539    prolog_load_context(module, M0),
  540    strip_module(M0:Goal, M, Callable),
  541    must_be(callable, Callable).
  542
  543request_expanders(Closures) :-
  544    findall(Rank-Closure, request_expansion(Closure, Rank), Pairs),
  545    keysort(Pairs, Sorted),
  546    pairs_values(Sorted, Closures).
 expand_request(+Request0, -Request, +Options)
Expand an HTTP request. Options is a list of combined options provided with the handler registration (see http_handler/3).
  553expand_request(Request0, Request, Options) :-
  554    request_expanders(Closures),
  555    expand_request(Closures, Request0, Request, Options).
  556
  557expand_request([], Request, Request, _).
  558expand_request([H|T], Request0, Request, Options) :-
  559    expand_request1(H, Request0, Request1, Options),
  560    expand_request(T, Request1, Request, Options).
  561
  562expand_request1(Closure, Request0, Request, Options) :-
  563    call(Closure, Request0, Request, Options),
  564    !.
  565expand_request1(_, Request, Request, _).
 http_current_handler(+Location, :Closure) is semidet
http_current_handler(-Location, :Closure) is nondet
True if Location is handled by Closure.
  573http_current_handler(Path, Closure) :-
  574    atom(Path),
  575    !,
  576    path_tree(Tree),
  577    find_handler(Tree, Path, Closure, _).
  578http_current_handler(Path, M:C) :-
  579    handler(Spec, M:C, _, _),
  580    http_absolute_location(Spec, Path, []).
 http_current_handler(+Location, :Closure, -Options) is semidet
http_current_handler(?Location, :Closure, ?Options) is nondet
Resolve the current handler and options to execute it.
  587http_current_handler(Path, Closure, Options) :-
  588    atom(Path),
  589    !,
  590    path_tree(Tree),
  591    find_handler(Tree, Path, Closure, Options).
  592http_current_handler(Path, M:C, Options) :-
  593    handler(Spec, M:C, _, _),
  594    http_absolute_location(Spec, Path, []),
  595    path_tree(Tree),
  596    find_handler(Tree, Path, _, Options).
 http_location_by_id(+ID, -Location) is det
True when Location represents the HTTP path to which the handler with identifier ID is bound. Handler identifiers are deduced from the http_handler/3 declaration as follows:
Explicit id
If a term id(ID) appears in the option list of the handler, ID it is used and takes preference over using the predicate.
Using the handler predicate
ID matches a handler if the predicate name matches ID. The ID may have a module qualification, e.g., Module:Pred

If the handler is declared with a pattern, e.g., root(user/User), the location to access a particular user may be accessed using e.g., user('Bob'). The number of arguments to the compound term must match the number of variables in the path pattern.

A plain atom ID can be used to find a handler with a pattern. The returned location is the path up to the first variable, e.g., /user/ in the example above.

User code is adviced to use http_link_to_id/3 which can also add query parameters to the URL. This predicate is a helper for http_link_to_id/3.

Errors
- existence_error(http_handler_id, Id).
See also
- http_link_to_id/3 and the library(http/html_write) construct location_by_id(ID) or its abbreviation #(ID)
  629:- dynamic
  630    id_location_cache/4.                        % Id, Argv, Location, Segments
  631
  632http_location_by_id(ID, _) :-
  633    \+ ground(ID),
  634    !,
  635    instantiation_error(ID).
  636http_location_by_id(M:ID, Location) :-
  637    compound(ID),
  638    !,
  639    compound_name_arguments(ID, Name, Argv),
  640    http_location_by_id(M:Name, Argv, Location).
  641http_location_by_id(M:ID, Location) :-
  642    atom(ID),
  643    must_be(atom, M),
  644    !,
  645    http_location_by_id(M:ID, -, Location).
  646http_location_by_id(ID, Location) :-
  647    compound(ID),
  648    !,
  649    compound_name_arguments(ID, Name, Argv),
  650    http_location_by_id(Name, Argv, Location).
  651http_location_by_id(ID, Location) :-
  652    atom(ID),
  653    !,
  654    http_location_by_id(ID, -, Location).
  655http_location_by_id(ID, _) :-
  656    type_error(location_id, ID).
  657
  658http_location_by_id(ID, Argv, Location) :-
  659    id_location_cache(ID, Argv, Segments, Path),
  660    !,
  661    add_segments(Path, Segments, Location).
  662http_location_by_id(ID, Argv, Location) :-
  663    findall(t(Priority, ArgvP, Segments, Prefix),
  664            location_by_id(ID, Argv, ArgvP, Segments, Prefix, Priority),
  665            List),
  666    sort(1, >=, List, Sorted),
  667    (   Sorted = [t(_,ArgvP,Segments,Path)]
  668    ->  assert(id_location_cache(ID,ArgvP,Segments,Path)),
  669        Argv = ArgvP
  670    ;   List == []
  671    ->  existence_error(http_handler_id, ID)
  672    ;   List = [t(P0,ArgvP,Segments,Path),t(P1,_,_,_)|_]
  673    ->  (   P0 =:= P1
  674        ->  print_message(warning,
  675                          http_dispatch(ambiguous_id(ID, Sorted, Path)))
  676        ;   true
  677        ),
  678        assert(id_location_cache(ID,Argv,Segments,Path)),
  679        Argv = ArgvP
  680    ),
  681    add_segments(Path, Segments, Location).
  682
  683add_segments(Path0, [], Path) :-
  684    !,
  685    Path = Path0.
  686add_segments(Path0, Segments, Path) :-
  687    maplist(uri_encoded(path), Segments, Encoded),
  688    atomic_list_concat(Encoded, '/', Rest),
  689    atom_concat(Path0, Rest, Path).
  690
  691location_by_id(ID, -, _, [], Location, Priority) :-
  692    !,
  693    location_by_id_raw(ID, L0, _Segments, Priority),
  694    to_path(L0, Location).
  695location_by_id(ID, Argv, ArgvP, Segments, Location, Priority) :-
  696    location_by_id_raw(ID, L0, Segments, Priority),
  697    include(var, Segments, ArgvP),
  698    same_length(Argv, ArgvP),
  699    to_path(L0, Location).
  700
  701to_path(prefix(Path0), Path) :-         % old style prefix notation
  702    !,
  703    add_prefix(Path0, Path).
  704to_path(Path0, Path) :-
  705    atomic(Path0),                      % old style notation
  706    !,
  707    add_prefix(Path0, Path).
  708to_path(Spec, Path) :-                  % new style notation
  709    http_absolute_location(Spec, Path, []).
  710
  711add_prefix(P0, P) :-
  712    (   catch(setting(http:prefix, Prefix), _, fail),
  713        Prefix \== ''
  714    ->  atom_concat(Prefix, P0, P)
  715    ;   P = P0
  716    ).
  717
  718location_by_id_raw(ID, Location, Pattern, Priority) :-
  719    handler(Location, _, _, Options),
  720    option(id(ID), Options),
  721    option(priority(P0), Options, 0),
  722    option(segment_pattern(Pattern), Options, []),
  723    Priority is P0+1000.            % id(ID) takes preference over predicate
  724location_by_id_raw(ID, Location, Pattern, Priority) :-
  725    handler(Location, M:C, _, Options),
  726    option(priority(Priority), Options, 0),
  727    functor(C, PN, _),
  728    (   ID = M:PN
  729    ->  true
  730    ;   ID = PN
  731    ),
  732    option(segment_pattern(Pattern), Options, []).
 http_link_to_id(+HandleID, +Parameters, -HREF)
HREF is a link on the local server to a handler with given ID, passing the given Parameters. This predicate is typically used to formulate a HREF that resolves to a handler implementing a particular predicate. The code below provides a typical example. The predicate user_details/1 returns a page with details about a user from a given id. This predicate is registered as a handler. The DCG user_link//1 renders a link to a user, displaying the name and calling user_details/1 when clicked. Note that the location (root(user_details)) is irrelevant in this equation and HTTP locations can thus be moved freely without breaking this code fragment.
:- http_handler(root(user_details), user_details, []).

user_details(Request) :-
    http_parameters(Request,
                    [ user_id(ID)
                    ]),
    ...

user_link(ID) -->
    { user_name(ID, Name),
      http_link_to_id(user_details, [id(ID)], HREF)
    },
    html(a([class(user), href(HREF)], Name)).
Arguments:
HandleID- is either an atom, possibly module qualified predicate or a compound term if the hander is defined using a pattern. See http_handler/3 and http_location_by_id/2.
Parameters- is one of
  • path_postfix(File) to pass a single value as the last segment of the HTTP location (path). This way of passing a parameter is commonly used in REST APIs.

    New code should use a path pattern in the handler declaration and a term `HandleID(Arg, ...)`

  • A list of search parameters for a GET request.
See also
- http_location_by_id/2 and http_handler/3 for defining and specifying handler IDs.
  782http_link_to_id(HandleID, path_postfix(File), HREF) :-
  783    !,
  784    http_location_by_id(HandleID, HandlerLocation),
  785    uri_encoded(path, File, EncFile),
  786    directory_file_path(HandlerLocation, EncFile, Location),
  787    uri_data(path, Components, Location),
  788    uri_components(HREF, Components).
  789http_link_to_id(HandleID, Parameters, HREF) :-
  790    must_be(list, Parameters),
  791    http_location_by_id(HandleID, Location),
  792    (   Parameters == []
  793    ->  HREF = Location
  794    ;   uri_data(path, Components, Location),
  795        uri_query_components(String, Parameters),
  796        uri_data(search, Components, String),
  797        uri_components(HREF, Components)
  798    ).
 http_reload_with_parameters(+Request, +Parameters, -HREF) is det
Create a request on the current handler with replaced search parameters.
  805http_reload_with_parameters(Request, NewParams, HREF) :-
  806    memberchk(path(Path), Request),
  807    (   memberchk(search(Params), Request)
  808    ->  true
  809    ;   Params = []
  810    ),
  811    merge_options(NewParams, Params, AllParams),
  812    uri_query_components(Search, AllParams),
  813    uri_data(path, Data, Path),
  814    uri_data(search, Data, Search),
  815    uri_components(HREF, Data).
  816
  817
  818%       hook into html_write:attribute_value//1.
  819
  820:- multifile
  821    html_write:expand_attribute_value//1.  822
  823html_write:expand_attribute_value(location_by_id(ID)) -->
  824    { http_location_by_id(ID, Location) },
  825    html_write:html_quoted_attribute(Location).
  826html_write:expand_attribute_value(#(ID)) -->
  827    { http_location_by_id(ID, Location) },
  828    html_write:html_quoted_attribute(Location).
 authentication(+Options, +Request, -Fields) is det
Verify authentication information. If authentication is requested through Options, demand it. The actual verification is done by the multifile predicate http:authenticate/3. The library http_authenticate.pl provides an implementation thereof.
Errors
- permission_error(access, http_location, Location)
deprecated
- This hook predates the extensible request expansion provided by http_request_expansion/2. New hooks should use http_request_expansion/2 instead of http:authenticate/3.
  843:- multifile
  844    http:authenticate/3.  845
  846authentication([], _, []).
  847authentication([authentication(Type)|Options], Request, Fields) :-
  848    !,
  849    (   http:authenticate(Type, Request, XFields)
  850    ->  append(XFields, More, Fields),
  851        authentication(Options, Request, More)
  852    ;   memberchk(path(Path), Request),
  853        permission_error(access, http_location, Path)
  854    ).
  855authentication([_|Options], Request, Fields) :-
  856    authentication(Options, Request, Fields).
  857
  858:- http_request_expansion(auth_expansion, 100).
 auth_expansion(+Request0, -Request, +Options) is semidet
Connect the HTTP authentication infrastructure by means of http_request_expansion/2.
See also
- http:authenticate/3, http_digest.pl and http_authenticate.pl
  867auth_expansion(Request0, Request, Options) :-
  868    authentication(Options, Request0, Extra),
  869    append(Extra, Request0, Request).
 find_handler(+Path, -Action, -Options) is det
Find the handler to call from Path. Rules:

If there is a handler for /dir/ and the requested path is /dir, find_handler/3 throws a http_reply exception, causing the wrapper to generate a 301 (Moved Permanently) reply.

Errors
- existence_error(http_location, Location) @throw http_reply(moved(Dir))
To be done
- Introduce automatic redirection to indexes here?
  887find_handler(Path, Action, Options) :-
  888    path_tree(Tree),
  889    (   find_handler(Tree, Path, Action, Options),
  890        eval_condition(Options)
  891    ->  true
  892    ;   \+ sub_atom(Path, _, _, 0, /),
  893        atom_concat(Path, /, Dir),
  894        find_handler(Tree, Dir, Action, Options)
  895    ->  throw(http_reply(moved(Dir)))
  896    ;   throw(error(existence_error(http_location, Path), _))
  897    ).
  898
  899
  900find_handler([node(prefix(Prefix), PAction, POptions, Children)|_],
  901             Path, Action, Options) :-
  902    sub_atom(Path, 0, _, After, Prefix),
  903    !,
  904    (   option(hide_children(false), POptions, false),
  905        find_handler(Children, Path, Action, Options)
  906    ->  true
  907    ;   member(segment_pattern(Pattern, PatAction, PatOptions), POptions),
  908        copy_term(t(Pattern,PatAction,PatOptions), t(Pattern2,Action,Options)),
  909        match_segments(After, Path, Pattern2)
  910    ->  true
  911    ;   PAction \== nop
  912    ->  Action = PAction,
  913        path_info(After, Path, POptions, Options)
  914    ).
  915find_handler([node(Path, Action, Options, _)|_], Path, Action, Options) :- !.
  916find_handler([_|Tree], Path, Action, Options) :-
  917    find_handler(Tree, Path, Action, Options).
  918
  919path_info(0, _, Options,
  920          [prefix(true)|Options]) :- !.
  921path_info(After, Path, Options,
  922          [path_info(PathInfo),prefix(true)|Options]) :-
  923    sub_atom(Path, _, After, 0, PathInfo).
  924
  925match_segments(After, Path, [Var]) :-
  926    !,
  927    sub_atom(Path, _, After, 0, Var).
  928match_segments(After, Path, Pattern) :-
  929    sub_atom(Path, _, After, 0, PathInfo),
  930    split_string(PathInfo, "/", "", Segments),
  931    match_segment_pattern(Pattern, Segments).
  932
  933match_segment_pattern([], []).
  934match_segment_pattern([Var], Segments) :-
  935    !,
  936    atomic_list_concat(Segments, '/', Var).
  937match_segment_pattern([H0|T0], [H|T]) :-
  938    atom_string(H0, H),
  939    match_segment_pattern(T0, T).
  940
  941
  942eval_condition(Options) :-
  943    (   memberchk(condition(Cond), Options)
  944    ->  catch(Cond, E, (print_message(warning, E), fail))
  945    ;   true
  946    ).
 supports_method(+Request, +Options) is det
Verify that the asked http method is supported by the handler. If not, raise an error that will be mapped to a 405 page by the http wrapper.
Errors
- permission_error(http_method, Method, Location).
  957supports_method(Request, Options) :-
  958    (   option(methods(Methods), Options)
  959    ->  (   Methods == '*'
  960        ->  true
  961        ;   memberchk(method(Method), Request),
  962            memberchk(Method, Methods)
  963        )
  964    ;   true
  965    ),
  966    !.
  967supports_method(Request, _Options) :-
  968    memberchk(path(Location), Request),
  969    memberchk(method(Method), Request),
  970    permission_error(http_method, Method, Location).
 action(+Action, +Request, +Options) is det
Execute the action found. Here we take care of the options time_limit, chunked and spawn.
Errors
- goal_failed(Goal)
  980action(Action, Request, Options) :-
  981    memberchk(chunked, Options),
  982    !,
  983    format('Transfer-encoding: chunked~n'),
  984    spawn_action(Action, Request, Options).
  985action(Action, Request, Options) :-
  986    spawn_action(Action, Request, Options).
  987
  988spawn_action(Action, Request, Options) :-
  989    option(spawn(Spawn), Options),
  990    !,
  991    spawn_options(Spawn, SpawnOption),
  992    http_spawn(time_limit_action(Action, Request, Options), SpawnOption).
  993spawn_action(Action, Request, Options) :-
  994    time_limit_action(Action, Request, Options).
  995
  996spawn_options([], []) :- !.
  997spawn_options(Pool, Options) :-
  998    atom(Pool),
  999    !,
 1000    Options = [pool(Pool)].
 1001spawn_options(List, List).
 1002
 1003time_limit_action(Action, Request, Options) :-
 1004    (   option(time_limit(TimeLimit), Options),
 1005        TimeLimit \== default
 1006    ->  true
 1007    ;   setting(http:time_limit, TimeLimit)
 1008    ),
 1009    number(TimeLimit),
 1010    TimeLimit > 0,
 1011    !,
 1012    call_with_time_limit(TimeLimit, call_action(Action, Request, Options)).
 1013time_limit_action(Action, Request, Options) :-
 1014    call_action(Action, Request, Options).
 call_action(+Action, +Request, +Options)
To be done
- reply_file is normal call?
 1021call_action(reply_file(File, FileOptions), Request, _Options) :-
 1022    !,
 1023    http_reply_file(File, FileOptions, Request).
 1024call_action(Pred, Request, Options) :-
 1025    memberchk(path_info(PathInfo), Options),
 1026    !,
 1027    call_action(Pred, [path_info(PathInfo)|Request]).
 1028call_action(Pred, Request, _Options) :-
 1029    call_action(Pred, Request).
 1030
 1031call_action(Pred, Request) :-
 1032    (   call(Pred, Request)
 1033    ->  true
 1034    ;   extend(Pred, [Request], Goal),
 1035        throw(error(goal_failed(Goal), _))
 1036    ).
 1037
 1038extend(Var, _, Var) :-
 1039    var(Var),
 1040    !.
 1041extend(M:G0, Extra, M:G) :-
 1042    extend(G0, Extra, G).
 1043extend(G0, Extra, G) :-
 1044    G0 =.. List,
 1045    append(List, Extra, List2),
 1046    G =.. List2.
 http_reply_file(+FileSpec, +Options, +Request) is det
Options is a list of
cache(+Boolean)
If true (default), handle If-modified-since and send modification time.
mime_type(+Type)
Overrule mime-type guessing from the filename as provided by file_mime_type/2.
static_gzip(+Boolean)
If true (default false) and, in addition to the plain file, there is a .gz file that is not older than the plain file and the client acceps gzip encoding, send the compressed file with Transfer-encoding: gzip.
cached_gzip(+Boolean)
If true (default false) the system maintains cached gzipped files in a directory accessible using the file search path http_gzip_cache and serves these similar to the static_gzip(true) option. If the gzip file does not exist or is older than the input the file is recreated.
unsafe(+Boolean)
If false (default), validate that FileSpec does not contain references to parent directories. E.g., specifications such as www('../../etc/passwd') are not allowed.
headers(+List)
Provides additional reply-header fields, encoded as a list of Field(Value).

If caching is not disabled, it processes the request headers If-modified-since and Range.

throws
- http_reply(not_modified)
- http_reply(file(MimeType, Path))
 1090http_reply_file(File, Options, Request) :-
 1091    http_safe_file(File, Options),
 1092    absolute_file_name(File, Path,
 1093                       [ access(read)
 1094                       ]),
 1095    (   option(cache(true), Options, true)
 1096    ->  (   memberchk(if_modified_since(Since), Request),
 1097            time_file(Path, Time),
 1098            catch(http_timestamp(Time, Since), _, fail)
 1099        ->  throw(http_reply(not_modified))
 1100        ;   true
 1101        ),
 1102        (   memberchk(range(Range), Request)
 1103        ->  Reply = file(Type, Path, Range)
 1104        ;   option(static_gzip(true), Options),
 1105            accepts_encoding(Request, gzip),
 1106            file_name_extension(Path, gz, PathGZ),
 1107            access_file(PathGZ, read),
 1108            time_file(PathGZ, TimeGZ),
 1109            time_file(Path, Time),
 1110            TimeGZ >= Time
 1111        ->  Reply = gzip_file(Type, PathGZ)
 1112        ;   option(cached_gzip(true), Options),
 1113            accepts_encoding(Request, gzip),
 1114            gzip_cached(Path, PathGZ)
 1115        ->  Reply = gzip_file(Type, PathGZ)
 1116        ;   Reply = file(Type, Path)
 1117        )
 1118    ;   Reply = tmp_file(Type, Path)
 1119    ),
 1120    (   option(mime_type(MediaType), Options)
 1121    ->  file_content_type(Path, MediaType, Type)
 1122    ;   file_content_type(Path, Type)
 1123    ->  true
 1124    ;   Type = text/plain           % fallback type
 1125    ),
 1126    option(headers(Headers), Options, []),
 1127    throw(http_reply(Reply, Headers)).
 1128
 1129accepts_encoding(Request, Enc) :-
 1130    memberchk(accept_encoding(Accept), Request),
 1131    split_string(Accept, ",", " ", Parts),
 1132    member(Part, Parts),
 1133    split_string(Part, ";", " ", [EncS|_]),
 1134    atom_string(Enc, EncS).
 1135
 1136gzip_cached(Path, PathGZ) :-
 1137    with_mutex(http_reply_file, gzip_cached_sync(Path, PathGZ)).
 1138
 1139gzip_cached_sync(Path, PathGZ) :-
 1140    time_file(Path, Time),
 1141    variant_sha1(Path, SHA1),
 1142    (   absolute_file_name(http_gzip_cache(SHA1),
 1143                           PathGZ,
 1144                           [ access(read),
 1145                             file_errors(fail)
 1146                           ]),
 1147        time_file(PathGZ, TimeGZ),
 1148        TimeGZ >= Time
 1149    ->  true
 1150    ;   absolute_file_name(http_gzip_cache(SHA1),
 1151                           PathGZ,
 1152                           [ access(write),
 1153                             file_errors(fail)
 1154                           ])
 1155    ->  setup_call_cleanup(
 1156            gzopen(PathGZ, write, Out, [type(binary)]),
 1157            setup_call_cleanup(
 1158                open(Path, read, In, [type(binary)]),
 1159                copy_stream_data(In, Out),
 1160                close(In)),
 1161            close(Out))
 1162    ).
 http_safe_file(+FileSpec, +Options) is det
True if FileSpec is considered safe. If it is an atom, it cannot be absolute and cannot have references to parent directories. If it is of the form alias(Sub), than Sub cannot have references to parent directories.
Errors
- instantiation_error
- permission_error(read, file, FileSpec)
 1174http_safe_file(File, _) :-
 1175    var(File),
 1176    !,
 1177    instantiation_error(File).
 1178http_safe_file(_, Options) :-
 1179    option(unsafe(true), Options, false),
 1180    !.
 1181http_safe_file(File, _) :-
 1182    http_safe_file(File).
 1183
 1184http_safe_file(File) :-
 1185    compound(File),
 1186    functor(File, _, 1),
 1187    !,
 1188    arg(1, File, Name),
 1189    safe_name(Name, File).
 1190http_safe_file(Name) :-
 1191    (   is_absolute_file_name(Name)
 1192    ->  permission_error(read, file, Name)
 1193    ;   true
 1194    ),
 1195    safe_name(Name, Name).
 1196
 1197safe_name(Name, _) :-
 1198    must_be(atom, Name),
 1199    prolog_to_os_filename(FileName, Name),
 1200    \+ unsafe_name(FileName),
 1201    !.
 1202safe_name(_, Spec) :-
 1203    permission_error(read, file, Spec).
 1204
 1205unsafe_name(Name) :- Name == '..'.
 1206unsafe_name(Name) :- sub_atom(Name, 0, _, _, '../').
 1207unsafe_name(Name) :- sub_atom(Name, _, _, _, '/../').
 1208unsafe_name(Name) :- sub_atom(Name, _, _, 0, '/..').
 http_redirect(+How, +To, +Request) is det
Redirect to a new location. The argument order, using the Request as last argument, allows for calling this directly from the handler declaration:
:- http_handler(root(.),
                http_redirect(moved, myapp('index.html')),
                []).
Arguments:
How- is one of moved, moved_temporary or see_other
To- is an atom, a aliased path as defined by http_absolute_location/3. or a term location_by_id(Id) or its abbreviations #(Id) or #(Id)+Parameters. If To is not absolute, it is resolved relative to the current location.
 1229http_redirect(How, To, Request) :-
 1230    must_be(oneof([moved, moved_temporary, see_other]), How),
 1231    must_be(ground, To),
 1232    (   id_location(To, URL)
 1233    ->  true
 1234    ;   memberchk(path(Base), Request),
 1235        http_absolute_location(To, URL, [relative_to(Base)])
 1236    ),
 1237    Term =.. [How,URL],
 1238    throw(http_reply(Term)).
 1239
 1240id_location(location_by_id(Id), URL) :-
 1241    http_location_by_id(Id, URL).
 1242id_location(#(Id), URL) :-
 1243    http_location_by_id(Id, URL).
 1244id_location(#(Id)+Parameters, URL) :-
 1245    http_link_to_id(Id, Parameters, URL).
 http_404(+Options, +Request) is det
Reply using an "HTTP 404 not found" page. This handler is intended as fallback handler for prefix handlers. Options processed are:
index(Location)
If there is no path-info, redirect the request to Location using http_redirect/3.
Errors
- http_reply(not_found(Path))
 1260http_404(Options, Request) :-
 1261    option(index(Index), Options),
 1262    \+ ( option(path_info(PathInfo), Request),
 1263         PathInfo \== ''
 1264       ),
 1265    !,
 1266    http_redirect(moved, Index, Request).
 1267http_404(_Options, Request) :-
 1268    option(path(Path), Request),
 1269    !,
 1270    throw(http_reply(not_found(Path))).
 1271http_404(_Options, Request) :-
 1272    domain_error(http_request, Request).
 http_switch_protocol(:Goal, +Options)
Send an "HTTP 101 Switching Protocols" reply. After sending the reply, the HTTP library calls call(Goal, InStream, OutStream), where InStream and OutStream are the raw streams to the HTTP client. This allows the communication to continue using an an alternative protocol.

If Goal fails or throws an exception, the streams are closed by the server. Otherwise Goal is responsible for closing the streams. Note that Goal runs in the HTTP handler thread. Typically, the handler should be registered using the spawn option if http_handler/3 or Goal must call thread_create/3 to allow the HTTP worker to return to the worker pool.

The streams use binary (octet) encoding and have their I/O timeout set to the server timeout (default 60 seconds). The predicate set_stream/2 can be used to change the encoding, change or cancel the timeout.

This predicate interacts with the server library by throwing an exception.

The following options are supported:

header(+Headers)
Backward compatible. Use headers(+Headers).
headers(+Headers)
Additional headers send with the reply. Each header takes the form Name(Value).
 1306%       @throws http_reply(switch_protocol(Goal, Options))
 1307
 1308http_switch_protocol(Goal, Options) :-
 1309    throw(http_reply(switching_protocols(Goal, Options))).
 1310
 1311
 1312                 /*******************************
 1313                 *        PATH COMPILATION      *
 1314                 *******************************/
 path_tree(-Tree) is det
Compile paths into a tree. The treee is multi-rooted and represented as a list of nodes, where each node has the form:
node(PathOrPrefix, Action, Options, Children)

The tree is a potentially complicated structure. It is cached in a global variable. Note that this cache is per-thread, so each worker thread holds a copy of the tree. If handler facts are changed the generation is incremented using next_generation/0 and each worker thread will re-compute the tree on the next ocasion.

 1330path_tree(Tree) :-
 1331    current_generation(G),
 1332    nb_current(http_dispatch_tree, G-Tree),
 1333    !. % Avoid existence error
 1334path_tree(Tree) :-
 1335    path_tree_nocache(Tree),
 1336    current_generation(G),
 1337    nb_setval(http_dispatch_tree, G-Tree).
 1338
 1339path_tree_nocache(Tree) :-
 1340    findall(Prefix, prefix_handler(Prefix, _, _, _), Prefixes0),
 1341    sort(Prefixes0, Prefixes),
 1342    prefix_tree(Prefixes, [], PTree),
 1343    prefix_options(PTree, [], OPTree),
 1344    add_paths_tree(OPTree, Tree).
 1345
 1346prefix_handler(Prefix, Action, Options, Priority-PLen) :-
 1347    handler(Spec, Action, true, Options),
 1348    (   memberchk(priority(Priority), Options)
 1349    ->  true
 1350    ;   Priority = 0
 1351    ),
 1352    (   memberchk(segment_pattern(Pattern), Options)
 1353    ->  length(Pattern, PLen)
 1354    ;   PLen = 0
 1355    ),
 1356    Error = error(existence_error(http_alias,_),_),
 1357    catch(http_absolute_location(Spec, Prefix, []), Error,
 1358          (   print_message(warning, Error),
 1359              fail
 1360          )).
 prefix_tree(PrefixList, +Tree0, -Tree)
Arguments:
Tree- list(Prefix-list(Children))
 1366prefix_tree([], Tree, Tree).
 1367prefix_tree([H|T], Tree0, Tree) :-
 1368    insert_prefix(H, Tree0, Tree1),
 1369    prefix_tree(T, Tree1, Tree).
 1370
 1371insert_prefix(Prefix, Tree0, Tree) :-
 1372    select(P-T, Tree0, Tree1),
 1373    sub_atom(Prefix, 0, _, _, P),
 1374    !,
 1375    insert_prefix(Prefix, T, T1),
 1376    Tree = [P-T1|Tree1].
 1377insert_prefix(Prefix, Tree, [Prefix-[]|Tree]).
 prefix_options(+PrefixTree, +DefOptions, -OptionTree)
Generate the option-tree for all prefix declarations.
To be done
- What to do if there are more?
 1386prefix_options([], _, []).
 1387prefix_options([Prefix-C|T0], DefOptions,
 1388               [node(prefix(Prefix), Action, PrefixOptions, Children)|T]) :-
 1389    findall(h(A,O,P), prefix_handler(Prefix,A,O,P), Handlers),
 1390    sort(3, >=, Handlers, Handlers1),
 1391    Handlers1 = [h(_,_,P0)|_],
 1392    same_priority_handlers(Handlers1, P0, Same),
 1393    option_patterns(Same, SegmentPatterns, Action),
 1394    last(Same, h(_, Options0, _-_)),
 1395    merge_options(Options0, DefOptions, Options),
 1396    append(SegmentPatterns, Options, PrefixOptions),
 1397    exclude(no_inherit, Options, InheritOpts),
 1398    prefix_options(C, InheritOpts, Children),
 1399    prefix_options(T0, DefOptions, T).
 1400
 1401no_inherit(id(_)).
 1402no_inherit('$extract'(_)).
 1403
 1404same_priority_handlers([H|T0], P, [H|T]) :-
 1405    H = h(_,_,P0-_),
 1406    P = P0-_,
 1407    !,
 1408    same_priority_handlers(T0, P, T).
 1409same_priority_handlers(_, _, []).
 1410
 1411option_patterns([], [], nop).
 1412option_patterns([h(A,_,_-0)|_], [], A) :-
 1413    !.
 1414option_patterns([h(A,O,_)|T0], [segment_pattern(P,A,O)|T], AF) :-
 1415    memberchk(segment_pattern(P), O),
 1416    option_patterns(T0, T, AF).
 add_paths_tree(+OPTree, -Tree) is det
Add the plain paths.
 1423add_paths_tree(OPTree, Tree) :-
 1424    findall(path(Path, Action, Options),
 1425            plain_path(Path, Action, Options),
 1426            Triples),
 1427    add_paths_tree(Triples, OPTree, Tree).
 1428
 1429add_paths_tree([], Tree, Tree).
 1430add_paths_tree([path(Path, Action, Options)|T], Tree0, Tree) :-
 1431    add_path_tree(Path, Action, Options, [], Tree0, Tree1),
 1432    add_paths_tree(T, Tree1, Tree).
 plain_path(-Path, -Action, -Options) is nondet
True if {Path,Action,Options} is registered and Path is a plain (i.e. not prefix) location.
 1440plain_path(Path, Action, Options) :-
 1441    handler(Spec, Action, false, Options),
 1442    catch(http_absolute_location(Spec, Path, []), E,
 1443          (print_message(error, E), fail)).
 add_path_tree(+Path, +Action, +Options, +Tree0, -Tree) is det
Add a path to a tree. If a handler for the same path is already defined, the one with the highest priority or the latest takes precedence.
 1452add_path_tree(Path, Action, Options0, DefOptions, [],
 1453              [node(Path, Action, Options, [])]) :-
 1454    !,
 1455    merge_options(Options0, DefOptions, Options).
 1456add_path_tree(Path, Action, Options, _,
 1457              [node(prefix(Prefix), PA, DefOptions, Children0)|RestTree],
 1458              [node(prefix(Prefix), PA, DefOptions, Children)|RestTree]) :-
 1459    sub_atom(Path, 0, _, _, Prefix),
 1460    !,
 1461    delete(DefOptions, id(_), InheritOpts),
 1462    add_path_tree(Path, Action, Options, InheritOpts, Children0, Children).
 1463add_path_tree(Path, Action, Options1, DefOptions, [H0|T], [H|T]) :-
 1464    H0 = node(Path, _, Options2, _),
 1465    option(priority(P1), Options1, 0),
 1466    option(priority(P2), Options2, 0),
 1467    P1 >= P2,
 1468    !,
 1469    merge_options(Options1, DefOptions, Options),
 1470    H = node(Path, Action, Options, []).
 1471add_path_tree(Path, Action, Options, DefOptions, [H|T0], [H|T]) :-
 1472    add_path_tree(Path, Action, Options, DefOptions, T0, T).
 1473
 1474
 1475                 /*******************************
 1476                 *            MESSAGES          *
 1477                 *******************************/
 1478
 1479:- multifile
 1480    prolog:message/3. 1481
 1482prolog:message(http_dispatch(ambiguous_id(ID, _List, Selected))) -->
 1483    [ 'HTTP dispatch: ambiguous handler ID ~q (selected ~q)'-[ID, Selected]
 1484    ].
 1485
 1486
 1487                 /*******************************
 1488                 *            XREF              *
 1489                 *******************************/
 1490
 1491:- multifile
 1492    prolog:meta_goal/2. 1493:- dynamic
 1494    prolog:meta_goal/2. 1495
 1496prolog:meta_goal(http_handler(_, G, _), [G+1]).
 1497prolog:meta_goal(http_current_handler(_, G), [G+1]).
 1498
 1499
 1500                 /*******************************
 1501                 *             EDIT             *
 1502                 *******************************/
 1503
 1504% Allow edit(Location) to edit the implementation for an HTTP location.
 1505
 1506:- multifile
 1507    prolog_edit:locate/3. 1508
 1509prolog_edit:locate(Path, Spec, Location) :-
 1510    atom(Path),
 1511    sub_atom(Path, 0, _, _, /),
 1512    Pred = _M:_H,
 1513    catch(http_current_handler(Path, Pred), _, fail),
 1514    closure_name_arity(Pred, 1, PI),
 1515    prolog_edit:locate(PI, Spec, Location).
 1516
 1517closure_name_arity(M:Term, Extra, M:Name/Arity) :-
 1518    !,
 1519    callable(Term),
 1520    functor(Term, Name, Arity0),
 1521    Arity is Arity0 + Extra.
 1522closure_name_arity(Term, Extra, Name/Arity) :-
 1523    callable(Term),
 1524    functor(Term, Name, Arity0),
 1525    Arity is Arity0 + Extra.
 1526
 1527
 1528                 /*******************************
 1529                 *        CACHE CLEANUP         *
 1530                 *******************************/
 1531
 1532:- listen(settings(changed(http:prefix, _, _)),
 1533          next_generation). 1534
 1535:- multifile
 1536    user:message_hook/3. 1537:- dynamic
 1538    user:message_hook/3. 1539
 1540user:message_hook(make(done(Reload)), _Level, _Lines) :-
 1541    Reload \== [],
 1542    next_generation,
 1543    fail