View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker, Matt Lilley
    4    E-mail:        J.Wielemaker@cs.vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2006-2019, 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_session,
   38          [ http_set_session_options/1, % +Options
   39            http_set_session/1,         % +Option
   40            http_set_session/2,         % +SessionId, +Option
   41            http_session_option/1,      % ?Option
   42
   43            http_session_id/1,          % -SessionId
   44            http_in_session/1,          % -SessionId
   45            http_current_session/2,     % ?SessionId, ?Data
   46            http_close_session/1,       % +SessionId
   47            http_open_session/2,        % -SessionId, +Options
   48
   49            http_session_cookie/1,      % -Cookie
   50
   51            http_session_asserta/1,     % +Data
   52            http_session_assert/1,      % +Data
   53            http_session_retract/1,     % ?Data
   54            http_session_retractall/1,  % +Data
   55            http_session_data/1,        % ?Data
   56
   57            http_session_asserta/2,     % +Data, +SessionId
   58            http_session_assert/2,      % +Data, +SessionId
   59            http_session_retract/2,     % ?Data, +SessionId
   60            http_session_retractall/2,  % +Data, +SessionId
   61            http_session_data/2         % ?Data, +SessionId
   62          ]).   63:- use_module(http_wrapper).   64:- use_module(http_stream).   65:- use_module(library(error)).   66:- use_module(library(debug)).   67:- use_module(library(socket)).   68:- use_module(library(broadcast)).   69:- use_module(library(lists)).   70:- use_module(library(time)).   71
   72:- predicate_options(http_open_session/2, 2, [renew(boolean)]).

HTTP Session management

This library defines session management based on HTTP cookies. Session management is enabled simply by loading this module. Details can be modified using http_set_session_options/1. By default, this module creates a session whenever a request is processes that is inside the hierarchy defined for session handling (see path option in http_set_session_options/1). Automatic creation of a session can be stopped using the option create(noauto). The predicate http_open_session/2 must be used to create a session if noauto is enabled. Sessions can be closed using http_close_session/1.

If a session is active, http_in_session/1 returns the current session and http_session_assert/1 and friends maintain data about the session. If the session is reclaimed, all associated data is reclaimed too.

Begin and end of sessions can be monitored using library(broadcast). The broadcasted messages are:

http_session(begin(SessionID, Peer))
Broadcasted if a session is started
http_session(end(SessionId, Peer))
Broadcasted if a session is ended. See http_close_session/1.

For example, the following calls end_session(SessionId) whenever a session terminates. Please note that sessions ends are not scheduled to happen at the actual timeout moment of the session. Instead, creating a new session scans the active list for timed-out sessions. This may change in future versions of this library.

:- listen(http_session(end(SessionId, Peer)),
          end_session(SessionId)).

*/

  110:- dynamic
  111    session_setting/1,              % Name(Value)
  112    current_session/2,              % SessionId, Peer
  113    last_used/2,                    % SessionId, Time
  114    session_data/2.                 % SessionId, Data
  115
  116session_setting(timeout(600)).          % timeout in seconds
  117session_setting(cookie('swipl_session')).
  118session_setting(path(/)).
  119session_setting(enabled(true)).
  120session_setting(create(auto)).
  121session_setting(proxy_enabled(false)).
  122session_setting(gc(passive)).
  123session_setting(samesite(lax)).
  124
  125session_option(timeout, integer).
  126session_option(cookie, atom).
  127session_option(path, atom).
  128session_option(create, oneof([auto,noauto])).
  129session_option(route, atom).
  130session_option(enabled, boolean).
  131session_option(proxy_enabled, boolean).
  132session_option(gc, oneof([active,passive])).
  133session_option(samesite, oneof([none,lax,strict])).
 http_set_session_options(+Options) is det
Set options for the session library. Provided options are:
timeout(+Seconds)
Session timeout in seconds. Default is 600 (10 min). A timeout of 0 (zero) disables timeout.
cookie(+Cookiekname)
Name to use for the cookie to identify the session. Default swipl_session.
path(+Path)
Path to which the cookie is associated. Default is /. Cookies are only sent if the HTTP request path is a refinement of Path.
route(+Route)
Set the route name. Default is the unqualified hostname. To cancel adding a route, use the empty atom. See route/1.
enabled(+Boolean)
Enable/disable session management. Sesion management is enabled by default after loading this file.
create(+Atom)
Defines when a session is created. This is one of auto (default), which creates a session if there is a request whose path matches the defined session path or noauto, in which cases sessions are only created by calling http_open_session/2 explicitely.
proxy_enabled(+Boolean)
Enable/disable proxy session management. Proxy session management associates the originating IP address of the client to the session rather than the proxy IP address. Default is false.
gc(+When)
When is one of active, which starts a thread that performs session cleanup at close to the moment of the timeout or passive, which runs session GC when a new session is created.
samesite(+Restriction)
One of none, lax (default), or strict - The SameSite attribute prevents the CSRF vulnerability. strict has best security, but prevents links from external sites from operating properly. lax stops most CSRF attacks against REST endpoints but rarely interferes with legitimage operations. none removes the samesite attribute entirely. Caution: The value none exposes the entire site to CSRF attacks.
  190http_set_session_options([]).
  191http_set_session_options([H|T]) :-
  192    http_set_session_option(H),
  193    http_set_session_options(T).
  194
  195http_set_session_option(Option) :-
  196    functor(Option, Name, Arity),
  197    arg(1, Option, Value),
  198    (   session_option(Name, Type)
  199    ->  must_be(Type, Value)
  200    ;   domain_error(http_session_option, Option)
  201    ),
  202    functor(Free, Name, Arity),
  203    (   clause(session_setting(Free), _, Ref)
  204    ->  (   Free \== Value
  205        ->  asserta(session_setting(Option)),
  206            erase(Ref),
  207            updated_session_setting(Name, Free, Value)
  208        ;   true
  209        )
  210    ;   asserta(session_setting(Option))
  211    ).
 http_session_option(?Option) is nondet
True if Option is a current option of the session system.
  217http_session_option(Option) :-
  218    session_setting(Option).
 session_setting(+SessionID, ?Setting) is semidet
Find setting for SessionID. It is possible to overrule some session settings using http_session_set(Setting).
  225session_setting(SessionId, Setting) :-
  226    nonvar(Setting),
  227    functor(Setting, Name, 1),
  228    local_option(Name, Value, Term),
  229    session_data(SessionId, '$setting'(Term)),
  230    !,
  231    arg(1, Setting, Value).
  232session_setting(_, Setting) :-
  233    session_setting(Setting).
  234
  235updated_session_setting(gc, _, passive) :-
  236    stop_session_gc_thread, !.
  237updated_session_setting(_, _, _).               % broadcast?
 http_set_session(Setting) is det
 http_set_session(SessionId, Setting) is det
Overrule a setting for the current or specified session. Currently, the only setting that can be overruled is timeout.
Errors
- permission_error(set, http_session, Setting) if setting a setting that is not supported on per-session basis.
  249http_set_session(Setting) :-
  250    http_session_id(SessionId),
  251    http_set_session(SessionId, Setting).
  252
  253http_set_session(SessionId, Setting) :-
  254    functor(Setting, Name, Arity),
  255    (   local_option(Name, _, _)
  256    ->  true
  257    ;   permission_error(set, http_session, Setting)
  258    ),
  259    arg(1, Setting, Value),
  260    (   session_option(Name, Type)
  261    ->  must_be(Type, Value)
  262    ;   domain_error(http_session_option, Setting)
  263    ),
  264    functor(Free, Name, Arity),
  265    retractall(session_data(SessionId, '$setting'(Free))),
  266    assert(session_data(SessionId, '$setting'(Setting))).
  267
  268local_option(timeout, X, timeout(X)).
 http_session_id(-SessionId) is det
True if SessionId is an identifier for the current session.
Arguments:
SessionId- is an atom.
Errors
- existence_error(http_session, _)
See also
- http_in_session/1 for a version that fails if there is no session.
  279http_session_id(SessionID) :-
  280    (   http_in_session(ID)
  281    ->  SessionID = ID
  282    ;   throw(error(existence_error(http_session, _), _))
  283    ).
 http_in_session(-SessionId) is semidet
True if SessionId is an identifier for the current session. The current session is extracted from session(ID) from the current HTTP request (see http_current_request/1). The value is cached in a backtrackable global variable http_session_id. Using a backtrackable global variable is safe because continuous worker threads use a failure driven loop and spawned threads start without any global variables. This variable can be set from the commandline to fake running a goal from the commandline in the context of a session.
See also
- http_session_id/1
  299http_in_session(SessionID) :-
  300    nb_current(http_session_id, ID),
  301    ID \== [],
  302    !,
  303    debug(http_session, 'Session id from global variable: ~q', [ID]),
  304    ID \== no_session,
  305    SessionID = ID.
  306http_in_session(SessionID) :-
  307    http_current_request(Request),
  308    http_in_session(Request, SessionID).
  309
  310http_in_session(Request, SessionID) :-
  311    memberchk(session(ID), Request),
  312    !,
  313    debug(http_session, 'Session id from request: ~q', [ID]),
  314    b_setval(http_session_id, ID),
  315    SessionID = ID.
  316http_in_session(Request, SessionID) :-
  317    memberchk(cookie(Cookies), Request),
  318    session_setting(cookie(Cookie)),
  319    member(Cookie=SessionID0, Cookies),
  320    debug(http_session, 'Session id from cookie: ~q', [SessionID0]),
  321    peer(Request, Peer),
  322    valid_session_id(SessionID0, Peer),
  323    !,
  324    b_setval(http_session_id, SessionID0),
  325    SessionID = SessionID0.
 http_session(+RequestIn, -RequestOut, -SessionID) is semidet
Maintain the notion of a session using a client-side cookie. This must be called first when handling a request that wishes to do session management, after which the possibly modified request must be used for further processing.

This predicate creates a session if the setting create is auto. If create is noauto, the application must call http_open_session/1 to create a session.

  339http_session(Request, Request, SessionID) :-
  340    memberchk(session(SessionID0), Request),
  341    !,
  342    SessionID = SessionID0.
  343http_session(Request0, Request, SessionID) :-
  344    memberchk(cookie(Cookies), Request0),
  345    session_setting(cookie(Cookie)),
  346    member(Cookie=SessionID0, Cookies),
  347    peer(Request0, Peer),
  348    valid_session_id(SessionID0, Peer),
  349    !,
  350    SessionID = SessionID0,
  351    Request = [session(SessionID)|Request0],
  352    b_setval(http_session_id, SessionID).
  353http_session(Request0, Request, SessionID) :-
  354    session_setting(create(auto)),
  355    session_setting(path(Path)),
  356    memberchk(path(ReqPath), Request0),
  357    sub_atom(ReqPath, 0, _, _, Path),
  358    !,
  359    create_session(Request0, Request, SessionID).
  360
  361create_session(Request0, Request, SessionID) :-
  362    http_gc_sessions,
  363    http_session_cookie(SessionID),
  364    session_setting(cookie(Cookie)),
  365    session_setting(path(Path)),
  366    session_setting(samesite(SameSite)),
  367    debug(http_session, 'Created session ~q at path=~q', [SessionID, Path]),
  368    (   SameSite == none
  369    ->  format('Set-Cookie: ~w=~w; Path=~w; Version=1\r\n',
  370               [Cookie, SessionID, Path])
  371    ;   format('Set-Cookie: ~w=~w; Path=~w; Version=1; SameSite=~w\r\n',
  372               [Cookie, SessionID, Path, SameSite])
  373    ),
  374    Request = [session(SessionID)|Request0],
  375    peer(Request0, Peer),
  376    open_session(SessionID, Peer).
 http_open_session(-SessionID, +Options) is det
Establish a new session. This is normally used if the create option is set to noauto. Options:
renew(+Boolean)
If true (default false) and the current request is part of a session, generate a new session-id. By default, this predicate returns the current session as obtained with http_in_session/1.
Errors
- permission_error(open, http_session, CGI) if this call is used after closing the CGI header.
See also
- http_set_session_options/1 to control the create option.
- http_close_session/1 for closing the session.
  395http_open_session(SessionID, Options) :-
  396    http_in_session(SessionID0),
  397    \+ option(renew(true), Options, false),
  398    !,
  399    SessionID = SessionID0.
  400http_open_session(SessionID, _Options) :-
  401    (   in_header_state
  402    ->  true
  403    ;   current_output(CGI),
  404        permission_error(open, http_session, CGI)
  405    ),
  406    (   http_in_session(ActiveSession)
  407    ->  http_close_session(ActiveSession, false)
  408    ;   true
  409    ),
  410    http_current_request(Request),
  411    create_session(Request, _, SessionID).
  412
  413
  414:- multifile
  415    http:request_expansion/2.  416
  417http:request_expansion(Request0, Request) :-
  418    session_setting(enabled(true)),
  419    http_session(Request0, Request, _SessionID).
 peer(+Request, -Peer) is det
Find peer for current request. If unknown we leave it unbound. Alternatively we should treat this as an error.
  426peer(Request, Peer) :-
  427    (   session_setting(proxy_enabled(true)),
  428        http_peer(Request, Peer)
  429    ->  true
  430    ;   memberchk(peer(Peer), Request)
  431    ->  true
  432    ;   true
  433    ).
 open_session(+SessionID, +Peer)
Open a new session. Uses broadcast/1 with the term http_session(begin(SessionID, Peer)).
  440open_session(SessionID, Peer) :-
  441    get_time(Now),
  442    assert(current_session(SessionID, Peer)),
  443    assert(last_used(SessionID, Now)),
  444    b_setval(http_session_id, SessionID),
  445    broadcast(http_session(begin(SessionID, Peer))).
 valid_session_id(+SessionID, +Peer) is semidet
Check if this sessionID is known. If so, check the idle time and update the last_used for this session.
  453valid_session_id(SessionID, Peer) :-
  454    current_session(SessionID, SessionPeer),
  455    get_time(Now),
  456    (   session_setting(SessionID, timeout(Timeout)),
  457        Timeout > 0
  458    ->  get_last_used(SessionID, Last),
  459        Idle is Now - Last,
  460        (   Idle =< Timeout
  461        ->  true
  462        ;   http_close_session(SessionID),
  463            fail
  464        )
  465    ;   Peer \== SessionPeer
  466    ->  http_close_session(SessionID),
  467        fail
  468    ;   true
  469    ),
  470    set_last_used(SessionID, Now, Timeout).
  471
  472get_last_used(SessionID, Last) :-
  473    atom(SessionID),
  474    !,
  475    once(last_used(SessionID, Last)).
  476get_last_used(SessionID, Last) :-
  477    last_used(SessionID, Last).
 set_last_used(+SessionID, +Now, +TimeOut)
Set the last-used notion for SessionID from the current time stamp. The time is rounded down to 10 second intervals to avoid many updates and simplify the scheduling of session GC.
  485set_last_used(SessionID, Now, TimeOut) :-
  486    LastUsed is floor(Now/10)*10,
  487    (   clause(last_used(SessionID, CurrentLast), _, Ref)
  488    ->  (   CurrentLast == LastUsed
  489        ->  true
  490        ;   asserta(last_used(SessionID, LastUsed)),
  491            erase(Ref),
  492            schedule_gc(LastUsed, TimeOut)
  493        )
  494    ;   asserta(last_used(SessionID, LastUsed)),
  495        schedule_gc(LastUsed, TimeOut)
  496    ).
  497
  498
  499                 /*******************************
  500                 *         SESSION DATA         *
  501                 *******************************/
 http_session_asserta(+Data) is det
 http_session_assert(+Data) is det
 http_session_retract(?Data) is nondet
 http_session_retractall(?Data) is det
Versions of assert/1, retract/1 and retractall/1 that associate data with the current HTTP session.
  511http_session_asserta(Data) :-
  512    http_session_id(SessionId),
  513    asserta(session_data(SessionId, Data)).
  514
  515http_session_assert(Data) :-
  516    http_session_id(SessionId),
  517    assert(session_data(SessionId, Data)).
  518
  519http_session_retract(Data) :-
  520    http_session_id(SessionId),
  521    retract(session_data(SessionId, Data)).
  522
  523http_session_retractall(Data) :-
  524    http_session_id(SessionId),
  525    retractall(session_data(SessionId, Data)).
 http_session_data(?Data) is nondet
True if Data is associated using http_session_assert/1 to the current HTTP session.
Errors
- existence_error(http_session,_)
  534http_session_data(Data) :-
  535    http_session_id(SessionId),
  536    session_data(SessionId, Data).
 http_session_asserta(+Data, +SessionID) is det
 http_session_assert(+Data, +SessionID) is det
 http_session_retract(?Data, +SessionID) is nondet
 http_session_retractall(@Data, +SessionID) is det
 http_session_data(?Data, +SessionID) is det
Versions of assert/1, retract/1 and retractall/1 that associate data with an explicit HTTP session.
See also
- http_current_session/2.
  549http_session_asserta(Data, SessionId) :-
  550    must_be(atom, SessionId),
  551    asserta(session_data(SessionId, Data)).
  552
  553http_session_assert(Data, SessionId) :-
  554    must_be(atom, SessionId),
  555    assert(session_data(SessionId, Data)).
  556
  557http_session_retract(Data, SessionId) :-
  558    must_be(atom, SessionId),
  559    retract(session_data(SessionId, Data)).
  560
  561http_session_retractall(Data, SessionId) :-
  562    must_be(atom, SessionId),
  563    retractall(session_data(SessionId, Data)).
  564
  565http_session_data(Data, SessionId) :-
  566    must_be(atom, SessionId),
  567    session_data(SessionId, Data).
  568
  569
  570
  571                 /*******************************
  572                 *           ENUMERATE          *
  573                 *******************************/
 http_current_session(?SessionID, ?Data) is nondet
Enumerate the current sessions and associated data. There are two Pseudo data elements:
idle(Seconds)
Session has been idle for Seconds.
peer(Peer)
Peer of the connection.
  586http_current_session(SessionID, Data) :-
  587    get_time(Now),
  588    get_last_used(SessionID, Last), % binds SessionID
  589    Idle is Now - Last,
  590    (   session_setting(SessionID, timeout(Timeout)),
  591        Timeout > 0
  592    ->  Idle =< Timeout
  593    ;   true
  594    ),
  595    (   Data = idle(Idle)
  596    ;   Data = peer(Peer),
  597        current_session(SessionID, Peer)
  598    ;   session_data(SessionID, Data)
  599    ).
  600
  601
  602                 /*******************************
  603                 *          GC SESSIONS         *
  604                 *******************************/
 http_close_session(+SessionID) is det
Closes an HTTP session. This predicate can be called from any thread to terminate a session. It uses the broadcast/1 service with the message below.
http_session(end(SessionId, Peer))

The broadcast is done before the session data is destroyed and the listen-handlers are executed in context of the session that is being closed. Here is an example that destroys a Prolog thread that is associated to a thread:

:- listen(http_session(end(SessionId, _Peer)),
          kill_session_thread(SessionID)).

kill_session_thread(SessionID) :-
        http_session_data(thread(ThreadID)),
        thread_signal(ThreadID, throw(session_closed)).

Succeed without any effect if SessionID does not refer to an active session.

If http_close_session/1 is called from a handler operating in the current session and the CGI stream is still in state header, this predicate emits a Set-Cookie to expire the cookie.

Errors
- type_error(atom, SessionID)
See also
- listen/2 for acting upon closed sessions
  639http_close_session(SessionId) :-
  640    http_close_session(SessionId, true).
  641
  642http_close_session(SessionId, Expire) :-
  643    must_be(atom, SessionId),
  644    (   current_session(SessionId, Peer),
  645        (   b_setval(http_session_id, SessionId),
  646            broadcast(http_session(end(SessionId, Peer))),
  647            fail
  648        ;   true
  649        ),
  650        (   Expire == true
  651        ->  expire_session_cookie
  652        ;   true
  653        ),
  654        retractall(current_session(SessionId, _)),
  655        retractall(last_used(SessionId, _)),
  656        retractall(session_data(SessionId, _)),
  657        fail
  658    ;   true
  659    ).
 expire_session_cookie(+SessionId) is det
Emit a request to delete a session cookie. This is only done if http_close_session/1 is still in `header mode'.
  667expire_session_cookie :-
  668    in_header_state,
  669    session_setting(cookie(Cookie)),
  670    session_setting(path(Path)),
  671    !,
  672    format('Set-Cookie: ~w=; \c
  673                expires=Tue, 01-Jan-1970 00:00:00 GMT; \c
  674                path=~w\r\n',
  675           [Cookie, Path]).
  676expire_session_cookie.
  677
  678in_header_state :-
  679    current_output(CGI),
  680    is_cgi_stream(CGI),
  681    cgi_property(CGI, state(header)),
  682    !.
 http_gc_sessions is det
 http_gc_sessions(+TimeOut) is det
Delete dead sessions. Currently runs session GC if a new session is opened and the last session GC was more than a TimeOut ago.
  691:- dynamic
  692    last_gc/1.  693
  694http_gc_sessions :-
  695    start_session_gc_thread,
  696    http_gc_sessions(60).
  697http_gc_sessions(TimeOut) :-
  698    (   with_mutex(http_session_gc, need_sesion_gc(TimeOut))
  699    ->  do_http_gc_sessions
  700    ;   true
  701    ).
  702
  703need_sesion_gc(TimeOut) :-
  704    get_time(Now),
  705    (   last_gc(LastGC),
  706        Now-LastGC < TimeOut
  707    ->  true
  708    ;   retractall(last_gc(_)),
  709        asserta(last_gc(Now)),
  710        do_http_gc_sessions
  711    ).
  712
  713do_http_gc_sessions :-
  714    debug(http_session(gc), 'Running HTTP session GC', []),
  715    get_time(Now),
  716    (   last_used(SessionID, Last),
  717        session_setting(SessionID, timeout(Timeout)),
  718        Timeout > 0,
  719        Idle is Now - Last,
  720        Idle > Timeout,
  721        http_close_session(SessionID, false),
  722        fail
  723    ;   true
  724    ).
 start_session_gc_thread is det
 stop_session_gc_thread is det
Create/stop a thread that listens for timeout-at timing and wakes up to run http_gc_sessions/1 shortly after a session is scheduled to timeout.
  733:- dynamic
  734    session_gc_queue/1.  735
  736start_session_gc_thread :-
  737    session_gc_queue(_),
  738    !.
  739start_session_gc_thread :-
  740    session_setting(gc(active)),
  741    !,
  742    catch(thread_create(session_gc_loop, _,
  743                        [ alias('__http_session_gc'),
  744                          at_exit(retractall(session_gc_queue(_)))
  745                        ]),
  746          error(permission_error(create, thread, _),_),
  747          true).
  748start_session_gc_thread.
  749
  750stop_session_gc_thread :-
  751    retract(session_gc_queue(Id)),
  752    !,
  753    thread_send_message(Id, done),
  754    thread_join(Id, _).
  755stop_session_gc_thread.
  756
  757session_gc_loop :-
  758    thread_self(GcQueue),
  759    asserta(session_gc_queue(GcQueue)),
  760    repeat,
  761    thread_get_message(Message),
  762    (   Message == done
  763    ->  !
  764    ;   schedule(Message),
  765        fail
  766    ).
  767
  768schedule(at(Time)) :-
  769    current_alarm(At, _, _, _),
  770    Time == At,
  771    !.
  772schedule(at(Time)) :-
  773    debug(http_session(gc), 'Schedule GC at ~p', [Time]),
  774    alarm_at(Time, http_gc_sessions(10), _,
  775             [ remove(true)
  776             ]).
  777
  778schedule_gc(LastUsed, TimeOut) :-
  779    nonvar(TimeOut),                            % var(TimeOut) means none
  780    session_gc_queue(Queue),
  781    !,
  782    At is LastUsed+TimeOut+5,                   % give some slack
  783    thread_send_message(Queue, at(At)).
  784schedule_gc(_, _).
  785
  786
  787                 /*******************************
  788                 *             UTIL             *
  789                 *******************************/
 http_session_cookie(-Cookie) is det
Generate a random cookie that can be used by a browser to identify the current session. The cookie has the format XXXX-XXXX-XXXX-XXXX[.<route>], where XXXX are random hexadecimal numbers and [.<route>] is the optionally added routing information.
  799http_session_cookie(Cookie) :-
  800    route(Route),
  801    !,
  802    random_4(R1,R2,R3,R4),
  803    format(atom(Cookie),
  804            '~`0t~16r~4|-~`0t~16r~9|-~`0t~16r~14|-~`0t~16r~19|.~w',
  805            [R1,R2,R3,R4,Route]).
  806http_session_cookie(Cookie) :-
  807    random_4(R1,R2,R3,R4),
  808    format(atom(Cookie),
  809            '~`0t~16r~4|-~`0t~16r~9|-~`0t~16r~14|-~`0t~16r~19|',
  810            [R1,R2,R3,R4]).
  811
  812:- thread_local
  813    route_cache/1.
 route(-RouteID) is semidet
Fetch the route identifier. This value is added as .<route> to the session cookie and used by -for example- the apache load balanching module. The default route is the local name of the host. Alternatives may be provided using http_set_session_options/1.
  823route(Route) :-
  824    route_cache(Route),
  825    !,
  826    Route \== ''.
  827route(Route) :-
  828    route_no_cache(Route),
  829    assert(route_cache(Route)),
  830    Route \== ''.
  831
  832route_no_cache(Route) :-
  833    session_setting(route(Route)),
  834    !.
  835route_no_cache(Route) :-
  836    gethostname(Host),
  837    (   sub_atom(Host, Before, _, _, '.')
  838    ->  sub_atom(Host, 0, Before, _, Route)
  839    ;   Route = Host
  840    ).
  841
  842:- if(\+current_prolog_flag(windows, true)).
 urandom(-Handle) is semidet
Handle is a stream-handle for /dev/urandom. Originally, this simply tried to open /dev/urandom, failing if this device does not exist. It turns out that trying to open /dev/urandom can block indefinitely on some Windows installations, so we no longer try this on Windows.
  851:- dynamic
  852    urandom_handle/1.  853
  854urandom(Handle) :-
  855    urandom_handle(Handle),
  856    !,
  857    Handle \== [].
  858urandom(Handle) :-
  859    catch(open('/dev/urandom', read, In, [type(binary)]), _, fail),
  860    !,
  861    assert(urandom_handle(In)),
  862    Handle = In.
  863urandom(_) :-
  864    assert(urandom_handle([])),
  865    fail.
  866
  867get_pair(In, Value) :-
  868    get_byte(In, B1),
  869    get_byte(In, B2),
  870    Value is B1<<8+B2.
  871:- endif.
 random_4(-R1, -R2, -R3, -R4) is det
Generate 4 2-byte random numbers. Uses /dev/urandom when available to make prediction of the session IDs hard.
  878:- if(current_predicate(urandom/1)).  879random_4(R1,R2,R3,R4) :-
  880    urandom(In),
  881    !,
  882    get_pair(In, R1),
  883    get_pair(In, R2),
  884    get_pair(In, R3),
  885    get_pair(In, R4).
  886:- endif.  887random_4(R1,R2,R3,R4) :-
  888    R1 is random(65536),
  889    R2 is random(65536),
  890    R3 is random(65536),
  891    R4 is random(65536)