View source with formatted 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)  2008-2025, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module(http_log,
   39          [ http_log_stream/1,          % -Stream
   40            http_log/2,                 % +Format, +Args
   41            http_log_close/1,           % +Reason
   42            post_data_encoded/2,        % ?Bytes, ?Encoded
   43            http_logrotate/1,           % +Options
   44            http_schedule_logrotate/2   % +When, +Options
   45          ]).   46:- use_module(library(http/http_header)).   47:- use_module(library(settings)).   48:- use_module(library(option)).   49:- use_module(library(error)).   50:- use_module(library(debug)).   51:- use_module(library(broadcast)).   52:- autoload(library(apply), [maplist/3]).   53:- autoload(library(uri),
   54            [ uri_components/2, uri_data/3, uri_data/4,
   55              uri_query_components/2
   56            ]).   57
   58:- setting(http:logfile, callable, 'httpd.log',
   59           'File in which to log HTTP requests').   60:- setting(http:log_post_data, integer, 0,
   61           'Log POST data up to N bytes long').   62:- setting(http:on_log_error, any, retry,
   63           'Action if logging fails').   64
   65/** <module> HTTP Logging module
   66
   67Simple module for logging HTTP requests to a file. Logging is enabled by
   68loading this file and ensure the setting   http:logfile is not the empty
   69atom. The default  file  for  writing   the  log  is  =|httpd.log|=. See
   70library(settings) for details.
   71
   72The  level of  logging  can be modified  using  the  multifile predicate
   73http_log:nolog/1 to hide HTTP  request  fields   from  the  logfile  and
   74http_log:password_field/1   to   hide   passwords   from   HTTP   search
   75specifications (e.g. =|/topsecret?password=secret|=).
   76*/
   77
   78:- multifile
   79    nolog/1,
   80    password_field/1,
   81    nolog_post_content_type/1.   82
   83% If the log settings change,  simply  close   the  log  and  it will be
   84% reopened with the new settings.
   85
   86:- listen(settings(changed(http:logfile, _, New)),
   87          http_log_close(changed(New))).   88:- listen(http(Message),
   89          http_message(Message)).   90:- listen(logrotate,
   91          http_log_close(logrotate)).   92
   93http_message(Message) :-
   94    log_message(Message),
   95    http_log_stream(Stream),
   96    E = error(_,_),
   97    catch(http_message(Message, Stream), E,
   98          log_error(E)).
   99
  100log_message(request_start(_Id, _Request)).
  101log_message(request_finished(_Id, _Code, _Status, _CPU, _Bytes)).
  102
  103http_message(request_start(Id, Request), Stream) :-
  104    log_started(Request, Id, Stream).
  105http_message(request_finished(Id, Code, Status, CPU, Bytes), Stream) :-
  106    log_completed(Code, Status, Bytes, Id, CPU, Stream).
  107
  108%!  log_error(+Error)
  109%
  110%   There was an error writing the  log   file.  The  message is printed
  111%   using print_message/2 and  execution  continues   according  to  the
  112%   setting `http:on_log_error`, which is one of:
  113%
  114%     - retry
  115%       Close the log file. The system will try to reopen it on the
  116%       next log event, recovering from the error. Note that the
  117%       most common case for this is probably running out of disc space.
  118%     - exit
  119%     - exit(Code)
  120%       Stop the server using halt(Code). The `exit` variant is
  121%       equivalent to exit(1).
  122%
  123%   The best choice depends on  your   priorities.  Using  `retry` gives
  124%   priority to keep the server running.  Using `exit` guarantees proper
  125%   log files and  thus  the  ability   to  examine  these  for security
  126%   reasons. An attacker may try to flood the disc, causing a successful
  127%   DoS attack if `exit` is used  and   the  ability to interact without
  128%   being logged if `retry` is used.
  129
  130log_error(E) :-
  131    print_message(warning, E),
  132    log_error_continue.
  133
  134log_error_continue :-
  135    setting(http:on_log_error, Action),
  136    log_error_continue(Action).
  137
  138log_error_continue(retry) :-
  139    http_log_close(error).
  140log_error_continue(exit) :-
  141    log_error_continue(exit(1)).
  142log_error_continue(exit(Code)) :-
  143    halt(Code).
  144
  145
  146
  147                 /*******************************
  148                 *         LOG ACTIVITY         *
  149                 *******************************/
  150
  151:- dynamic
  152    log_stream/2,                   % Stream, TimeTried
  153    halt_registered/0.  154
  155%!  http_log_stream(-Stream) is semidet.
  156%
  157%   True when Stream is a stream to the  opened HTTP log file. Opens the
  158%   log file in `append` mode if the file  is not yet open. The log file
  159%   is determined from the setting ``http:logfile``.  If this setting is
  160%   set to the empty atom (''), this predicate fails.
  161%
  162%   If  a  file  error  is   encountered,    this   is   reported  using
  163%   print_message/2, after which this predicate  silently fails. Opening
  164%   is retried every minute when a new message arrives.
  165%
  166%   Before opening the log  file,   the  message  http_log_open(Term) is
  167%   broadcasted.  This  message  allows  for   creating  the  directory,
  168%   renaming, deleting or truncating an existing log file.
  169
  170http_log_stream(Stream) :-
  171    log_stream(Stream, _Opened),
  172    !,
  173    Stream \== [].
  174http_log_stream([]) :-
  175    setting(http:logfile, ''),
  176    !,
  177    get_time(Now),
  178    assert(log_stream([], Now)),
  179    fail.
  180http_log_stream(Stream) :-
  181    setting(http:logfile, Term),
  182    broadcast(http_log_open(Term)),
  183    catch(absolute_file_name(Term, File,
  184                             [ access(append)
  185                             ]),
  186          E, open_error(E)),
  187    with_mutex(http_log, open_log(File, Stream0)),
  188    Stream = Stream0.
  189
  190open_log(_File, Stream) :-
  191    log_stream(Stream, Opened),
  192    (   Stream == []
  193    ->  (   get_time(Now),
  194            Now - Opened > 60
  195        ->  retractall(log_stream(_,_)),
  196            fail
  197        ;   !, fail
  198        )
  199    ;   true
  200    ), !.
  201open_log(File, Stream) :-
  202    catch(open(File, append, Stream,
  203               [ close_on_abort(false),
  204                 encoding(utf8),
  205                 buffer(line)
  206               ]), E, open_error(E)),
  207    get_time(Time),
  208    register_close_log,
  209    Error = error(_,_),
  210    catch(format(Stream,
  211                 'server(started, ~0f).~n',
  212                 [ Time ]),
  213          Error,
  214          open_error(Stream, Error)),
  215    assert(log_stream(Stream, Time)).
  216
  217open_error(Stream, E) :-
  218    close(Stream, [force(true)]),
  219    open_error(E).
  220
  221open_error(E) :-
  222    print_message(error, E),
  223    log_open_error_continue.
  224
  225log_open_error_continue :-
  226    setting(http:on_log_error, Action),
  227    log_open_error_continue(Action).
  228
  229log_open_error_continue(retry) :-
  230    !,
  231    get_time(Now),
  232    assert(log_stream([], Now)),
  233    fail.
  234log_open_error_continue(Action) :-
  235    log_error_continue(Action).
  236
  237register_close_log :-
  238    halt_registered,
  239    !.
  240register_close_log :-
  241    at_halt(close_log(stopped)),
  242    asserta(halt_registered).
  243
  244%!  http_log_close(+Reason) is det.
  245%
  246%   If there is a currently open HTTP logfile, close it after adding
  247%   a term server(Reason, Time).  to  the   logfile.  This  call  is
  248%   intended for cooperation with the Unix logrotate facility
  249%   using the following schema:
  250%
  251%       * Move logfile (the HTTP server keeps writing to the moved
  252%       file)
  253%       * Inform the server using an HTTP request that calls
  254%       http_log_close/1
  255%       * Compress the moved logfile
  256%
  257%   @author Suggested by Jacco van Ossenbruggen
  258
  259http_log_close(Reason) :-
  260    with_mutex(http_log, close_log(Reason)).
  261
  262close_log(Reason) :-
  263    retract(log_stream(Stream, _Opened)),
  264    !,
  265    (   is_stream(Stream)
  266    ->  get_time(Time),
  267        catch(( format(Stream, 'server(~q, ~0f).~n', [ Reason, Time ]),
  268                close(Stream)
  269              ), E, print_message(warning, E))
  270    ;   true
  271    ).
  272close_log(_).
  273
  274%!  http_log(+Format, +Args) is det.
  275%
  276%   Write message from Format and Args   to log-stream. See format/2
  277%   for details. Succeed without side  effects   if  logging  is not
  278%   enabled.
  279
  280http_log(Format, Args) :-
  281    (   http_log_stream(Stream)
  282    ->  Error = error(_,_),
  283        catch(system:format(Stream, Format, Args), % use operators from `system`
  284              Error,
  285              log_error(Error))
  286    ;   true
  287    ).
  288
  289
  290%!  log_started(+Request, +Id, +Stream) is det.
  291%
  292%   Write log message that Request was started to Stream.
  293%
  294%   @arg  Filled with sequence identifier for the request
  295
  296log_started(Request, Id, Stream) :-
  297    is_stream(Stream),
  298    !,
  299    get_time(Now),
  300    add_post_data(Request, Request1),
  301    log_request(Request1, LogRequest),
  302    format_time(string(HDate), '%+', Now),
  303    format(Stream,
  304           '/*~s*/ request(~q, ~3f, ~q).~n',
  305           [HDate, Id, Now, LogRequest]).
  306log_started(_, _, _).
  307
  308%!  log_request(+Request, -Log)
  309%
  310%   Remove passwords from the request to avoid sending them to the
  311%   logfiles.
  312
  313log_request([], []).
  314log_request([search(Search0)|T0], [search(Search)|T]) :-
  315    !,
  316    mask_passwords(Search0, Search),
  317    log_request(T0, T).
  318log_request([request_uri(URI0)|T0], [request_uri(URI)|T]) :-
  319    !,
  320    mask_request_uri(URI0, URI),
  321    log_request(T0, T).
  322log_request([H0|T0], [H|T]) :-
  323    mask_field(H0, H),
  324    !,
  325    log_request(T0, T).
  326log_request([H|T0], T) :-
  327    nolog(H),
  328    !,
  329    log_request(T0, T).
  330log_request([H|T0], [H|T]) :-
  331    log_request(T0, T).
  332
  333%   mask_request_uri(+URI0, -URI) is det.
  334%
  335%   Mask password fields in the query string of the request URI.
  336
  337mask_request_uri(URI0, URI) :-
  338    uri_components(URI0, Components0),
  339    uri_data(search, Components0, Search0),
  340    atom(Search0),
  341    catch(uri_query_components(Search0, Query0), _, fail),
  342    mask_passwords(Query0, Query),
  343    Query \== Query0,
  344    !,
  345    uri_query_components(Search, Query),
  346    uri_data(search, Components0, Search, Components),
  347    uri_components(URI, Components).
  348mask_request_uri(URI, URI).
  349
  350%   mask_field(+Field0, -Field) is semidet.
  351%
  352%   Mask header fields that hold credentials.
  353
  354mask_field(authorization(_), authorization(xxx)).
  355mask_field(proxy_authorization(_), proxy_authorization(xxx)).
  356mask_field(cookie(Cookies0), cookie(Cookies)) :-
  357    is_list(Cookies0),
  358    maplist(mask_cookie, Cookies0, Cookies).
  359
  360mask_cookie(Name=_, Name=xxx) :- !.
  361mask_cookie(Cookie, Cookie).
  362
  363mask_passwords([], []).
  364mask_passwords([Name=_|T0], [Name=xxx|T]) :-
  365    password_field(Name),
  366    !,
  367    mask_passwords(T0, T).
  368mask_passwords([H|T0], [H|T]) :-
  369    mask_passwords(T0, T).
  370
  371%!  password_field(+Field) is semidet.
  372%
  373%   Multifile predicate that can be defined to hide passwords from
  374%   the logfile.
  375
  376password_field(password).
  377password_field(passwd).
  378password_field('openid.password').
  379password_field(pwd0).
  380password_field(pwd1).
  381password_field(pwd2).
  382
  383
  384%!  nolog(+HTTPField)
  385%
  386%   Multifile  predicate  that  can  be   defined  to  hide  request
  387%   parameters from the request logfile.
  388
  389nolog(input(_)).
  390nolog(accept(_)).
  391nolog(accept_language(_)).
  392nolog(accept_encoding(_)).
  393nolog(accept_charset(_)).
  394nolog(pool(_)).
  395nolog(protocol(_)).
  396nolog(referer(R)) :-
  397    sub_atom(R, _, _, _, password),
  398    !.
  399
  400%!  nolog_post_content_type(+Type) is semidet.
  401%
  402%   Multifile hook called with the   =|Content-type|= header. If the
  403%   hook succeeds, the POST data is not logged. For example, to stop
  404%   logging  anything  but  application/json   messages:
  405%
  406%     ==
  407%     :- multifile http_log:nolog_post_content_type/1.
  408%
  409%     http_log:nolog_post_content_type(Type) :-
  410%        Type \= (application/json).
  411%     ==
  412%
  413%   @arg Type is a term MainType/SubType
  414
  415%!  add_post_data(+Request0, -Request) is det.
  416%
  417%   Add   a   request   field   post_data(Data)   if   the   setting
  418%   http:log_post_data is an integer > 0,  the content length < this
  419%   setting and nolog_post_content_type/1 does not   succeed  on the
  420%   provided content type.
  421
  422add_post_data(Request0, Request) :-
  423    setting(http:log_post_data, MaxLen),
  424    integer(MaxLen), MaxLen > 0,
  425    memberchk(input(In), Request0),
  426    memberchk(content_length(CLen), Request0),
  427    CLen =< MaxLen,
  428    memberchk(content_type(Type), Request0),
  429    http_parse_header_value(content_type, Type, media(MType/MSubType, _)),
  430    \+ nolog_post_content_type(MType/MSubType),
  431    catch(peek_string(In, CLen, PostData), _, fail),
  432    !,
  433    post_data_encoded(PostData, Encoded),
  434    Request = [post_data(Encoded)|Request0].
  435add_post_data(Request, Request).
  436
  437%!  post_data_encoded(?Bytes:string, ?Encoded:string) is det.
  438%
  439%   Encode the POST body for inclusion into   the HTTP log file. The
  440%   POST data is (in/de)flated  using   zopen/3  and  base64 encoded
  441%   using base64//1. The encoding makes   long text messages shorter
  442%   and keeps readable logfiles if binary data is posted.
  443
  444post_data_encoded(Bytes, Hex) :-
  445    nonvar(Bytes),
  446    !,
  447    setup_call_cleanup(
  448        new_memory_file(HMem),
  449        ( setup_call_cleanup(
  450              ( open_memory_file(HMem, write, Out, [encoding(octet)]),
  451                zopen(Out, ZOut, [])
  452              ),
  453              format(ZOut, '~s', [Bytes]),
  454              close(ZOut)),
  455          memory_file_to_codes(HMem, Codes, octet)
  456        ),
  457        free_memory_file(HMem)),
  458    phrase(base64(Codes), EncCodes),
  459    string_codes(Hex, EncCodes).
  460post_data_encoded(Bytes, Hex) :-
  461    string_codes(Hex, EncCodes),
  462    phrase(base64(Codes), EncCodes),
  463    string_codes(ZBytes, Codes),
  464    setup_call_cleanup(
  465        open_string(ZBytes, In),
  466        zopen(In, Zin, []),
  467        read_string(Zin, _, Bytes)).
  468
  469%!  log_completed(+Code, +Status, +Bytes, +Id, +CPU, +Stream) is det.
  470%
  471%   Write log message to Stream from a call_cleanup/3 call.
  472%
  473%   @param Status   2nd argument of call_cleanup/3
  474%   @param Id       Term identifying the completed request
  475%   @param CPU0     CPU time at time of entrance
  476%   @param Stream   Stream to write to (normally from http_log_stream/1).
  477
  478log_completed(Code, Status, Bytes, Id, CPU, Stream) :-
  479    is_stream(Stream),
  480    log_check_deleted(Stream),
  481    !,
  482    log(Code, Status, Bytes, Id, CPU, Stream).
  483log_completed(Code, Status, Bytes, Id, CPU0, _) :-
  484    http_log_stream(Stream),       % Logfile has changed!
  485    !,
  486    log_completed(Code, Status, Bytes, Id, CPU0, Stream).
  487log_completed(_,_,_,_,_,_).
  488
  489
  490log(Code, ok, Bytes, Id, CPU, Stream) :-
  491    !,
  492    format(Stream, 'completed(~q, ~q, ~q, ~q, ok).~n',
  493           [ Id, CPU, Bytes, Code ]).
  494log(Code, Status, Bytes, Id, CPU, Stream) :-
  495    (   map_exception(Status, Term)
  496    ->  true
  497    ;   message_to_string(Status, String),
  498        Term = error(String)
  499    ),
  500    format(Stream, 'completed(~q, ~q, ~q, ~q, ~W).~n',
  501           [ Id, CPU, Bytes, Code,
  502             Term, [ quoted(true),
  503                     ignore_ops(true),
  504                     blobs(portray),
  505                     portray_goal(write_blob)
  506                   ]
  507           ]).
  508
  509:- public write_blob/2.  510write_blob(Blob, _Options) :-
  511    format(string(S), '~q', [Blob]),
  512    writeq(blob(S)).
  513
  514map_exception(http_reply(bytes(ContentType,Bytes),_), bytes(ContentType,L)) :-
  515    string_length(Bytes, L).        % also does lists
  516map_exception(http_reply(Reply), Reply).
  517map_exception(http_reply(Reply, _), Reply).
  518map_exception(error(existence_error(http_location, Location), _Stack),
  519              error(404, Location)).
  520
  521
  522                 /*******************************
  523                 *      LOGROTATE SUPPORT       *
  524                 *******************************/
  525
  526%!  log_check_deleted(+Stream) is semidet.
  527%
  528%   If the link-count of the stream has   dropped  to zero, the file
  529%   has been deleted/moved. In this case the  log file is closed and
  530%   log_check_deleted/6 will open a  new   one.  This  provides some
  531%   support for cleaning up the logfile   without  shutting down the
  532%   server.
  533%
  534%   @see logrotate(1) to manage logfiles on Unix systems.
  535
  536log_check_deleted(Stream) :-
  537    stream_property(Stream, nlink(Links)),
  538    Links == 0,
  539    !,
  540    http_log_close(log_file_deleted),
  541    fail.
  542log_check_deleted(_).
  543
  544%!  http_logrotate(+Options) is det.
  545%
  546%   Rotate the available log files. Note that  there are two ways to
  547%   deal with the rotation of log files:
  548%
  549%     1. Use the OS log rotation facility. In that case the OS must
  550%     (1) move the logfile and (2) have something calling
  551%     http_log_close/1 to close the (moved) file and make this
  552%     server create a new one on the next log message.  If
  553%     library(http/http_unix_daemon) is used, closing is
  554%     achieved by sending SIGHUP or SIGUSR1 to the process.
  555%
  556%     2. Call this predicate at scheduled intervals.  This can
  557%     be achieved by calling http_schedule_logrotate/2 in the
  558%     context of library(http/http_unix_daemon) which schedules
  559%     the maintenance actions.
  560%
  561%   Options:
  562%
  563%     - min_size(+Bytes)
  564%     Do not rotate if the log file is smaller than Bytes.
  565%     The default is 1Mbytes.
  566%     - keep_logs(+Count)
  567%     Number of rotated log files to keep (default 10)
  568%     - compress_logs(+Format)
  569%     Compress the log files to the given format.  Default
  570%     `gzip` and this is currently the only supported compressor.
  571%     - background(+Boolean)
  572%     If `true`, rotate the log files in the background.
  573
  574http_logrotate(Options) :-
  575    select_option(background(true), Options, Options1),
  576    !,
  577    thread_create(http_logrotate(Options1), _,
  578                  [ alias('__logrotate'),
  579                    detached(true)
  580                  ]).
  581http_logrotate(Options) :-
  582    option(keep_logs(Keep), Options, 10),
  583    option(compress_logs(Format), Options, gzip),
  584    compress_extension(Format, ZExt),
  585    log_file_and_ext(Base, Ext),
  586    (   log_too_small(Base, Ext, Options)
  587    ->  true
  588    ;   rotate_logs(Base, Ext, ZExt, Keep)
  589    ).
  590
  591rotate_logs(Base, Ext, ZExt, N1) :-
  592    N1 > 0,
  593    !,
  594    N0 is N1 - 1,
  595    old_log_file(Base, Ext, N0, ZO, Old),
  596    (   exists_file(Old)
  597    ->  new_log_file(Base, Ext, N1, ZO, ZExt, ZN, New),
  598        rename_log_file(ZO, Old, ZN, New)
  599    ;   true
  600    ),
  601    rotate_logs(Base, Ext, ZExt, N0).
  602rotate_logs(_, _, _, _).
  603
  604rename_log_file(ZExt, Old, ZExt, New) :-
  605    !,
  606    debug(logrotate, 'Rename ~p --> ~p', [Old, New]),
  607    rename_file(Old, New).
  608rename_log_file('', Old, ZExt, New) :-
  609    file_name_extension(NoExt, ZExt, New),
  610    debug(logrotate, 'Rename ~p --> ~p', [Old, NoExt]),
  611    rename_file(Old, NoExt),
  612    debug(logrotate, 'Closing log file', []),
  613    http_log_close(logrotate),
  614    compress_extension(Format, ZExt),
  615    debug(logrotate, 'Compressing (~w) ~p', [Format, NoExt]),
  616    compress_file(NoExt, Format).
  617
  618old_log_file(Base, Ext, N, ZExt, File) :-
  619    log_file(Base, Ext, N, File0),
  620    (   compress_extension(_, ZExt),
  621        file_name_extension(File0, ZExt, File1),
  622        exists_file(File1)
  623    ->  File = File1
  624    ;   ZExt = '',
  625        File = File0
  626    ).
  627
  628new_log_file(Base, Ext, N, '', '', '', File) :-
  629    !,
  630    log_file(Base, Ext, N, File).
  631new_log_file(Base, Ext, N, '', ZExt, ZExt, File) :-
  632    !,
  633    log_file(Base, Ext, N, File0),
  634    file_name_extension(File0, ZExt, File).
  635new_log_file(Base, Ext, N, ZExt, _, ZExt, File) :-
  636    log_file(Base, Ext, N, File0),
  637    file_name_extension(File0, ZExt, File).
  638
  639log_file(Base, Ext, 0, File) :-
  640    !,
  641    file_name_extension(Base, Ext, File).
  642log_file(Base, Ext, N, File) :-
  643    atomic_list_concat([Base, -, N], Base1),
  644    file_name_extension(Base1, Ext, File).
  645
  646log_file_and_ext(Base, Ext) :-
  647    setting(http:logfile, Term),
  648    catch(absolute_file_name(Term, File,
  649                             [ access(exist)
  650                             ]), _, fail),
  651    file_name_extension(Base, Ext, File).
  652
  653log_too_small(Base, Ext, Options) :-
  654    DefMin is 1024*1024,
  655    option(min_size(MinBytes), Options, DefMin),
  656    file_name_extension(Base, Ext, File),
  657    (   exists_file(File)
  658    ->  size_file(File, Bytes),
  659        Bytes < MinBytes,
  660        debug(logrotate, '~w has ~D bytes; not rotating', [File, Bytes])
  661    ;   debug(logrotate, '~w does not exist; not rotating', [File])
  662    ).
  663
  664%!  compress_file(+File, +Format)
  665%
  666%   Compress a file according  to   Format.  Currently only supports
  667%   gzip.
  668
  669compress_file(File, Format) :-
  670    (   compress_extension(Format, Ext)
  671    ->  true
  672    ;   domain_error(compress_format, Format)
  673    ),
  674    file_name_extension(File, Ext, ZFile),
  675    catch(setup_call_cleanup(
  676              gzopen(ZFile, write, Out, [type(binary)]),
  677              setup_call_cleanup(
  678                  open(File, read, In, [type(binary)]),
  679                  copy_stream_data(In, Out),
  680                  close(In)),
  681              close(Out)),
  682          Error,
  683          ( print_message(error, Error),
  684            catch(delete_file(Out), _, true),
  685            throw(Error)
  686          )),
  687    delete_file(File).
  688
  689compress_extension(gzip, gz).
  690
  691:- dynamic
  692    scheduled_logrotate/2.  % Schedule, Options
  693
  694%!  http_schedule_logrotate(When, Options)
  695%
  696%   Schedule log rotation based on maintenance broadcasts.  When
  697%   is one of:
  698%
  699%     - daily(Hour:Min)
  700%     Run each day at Hour:Min.  Min is rounded to a multitude
  701%     of 5.
  702%     - weekly(Day, Hour:Min)
  703%     Run at the given Day and Time each week.  Day is either a
  704%     number 1..7 (1 is Monday) or a weekday name or abbreviation.
  705%     - monthly(DayOfTheMonth, Hour:Min)
  706%     Run each month at the given Day (1..31).  Note that not all
  707%     months have all days.
  708%
  709%   This  must  be  used   with   a    timer   that   broadcasts   a
  710%   maintenance(_,_) message (see broadcast/1). Such a timer is part
  711%   of library(http/http_unix_daemon).
  712
  713http_schedule_logrotate(When, Options) :-
  714    listen(maintenance(_,_), http_consider_logrotate),
  715    compile_schedule(When, Schedule),
  716    retractall(scheduled_logrotate(_,_)),
  717    asserta(scheduled_logrotate(Schedule, Options)).
  718
  719compile_schedule(Var, _) :-
  720    var(Var),
  721    !,
  722    instantiation_error(Var).
  723compile_schedule(daily(Time0), daily(Time)) :-
  724    compile_time(Time0, Time).
  725compile_schedule(weekly(Day0, Time0), weekly(Day, Time)) :-
  726    compile_weekday(Day0, Day),
  727    compile_time(Time0, Time).
  728compile_schedule(monthly(Day, Time0), monthly(Day, Time)) :-
  729    must_be(between(0, 31), Day),
  730    compile_time(Time0, Time).
  731
  732compile_time(HH:MM0, HH:MM) :-
  733    must_be(between(0, 23), HH),
  734    must_be(between(0, 59), MM0),
  735    MM is ((MM0+4)//5)*5.
  736
  737compile_weekday(N, _) :-
  738    var(N),
  739    !,
  740    instantiation_error(N).
  741compile_weekday(N, N) :-
  742    integer(N),
  743    !,
  744    must_be(between(1,7), N).
  745compile_weekday(Day, N) :-
  746    downcase_atom(Day, Lwr),
  747    (   sub_atom(Lwr, 0, 3, _, Abbr),
  748        day(N, Abbr)
  749    ->  !
  750    ;   domain_error(day, Day)
  751    ).
  752
  753%!  http_consider_logrotate
  754%
  755%   Perform a log rotation if the schedule is met
  756
  757http_consider_logrotate :-
  758    scheduled_logrotate(Schedule, Options),
  759    get_time(NowF),
  760    Now is round(NowF/60.0)*60,
  761    scheduled(Schedule, Now),
  762    !,
  763    http_logrotate([background(true)|Options]).
  764
  765scheduled(daily(HH:MM), Now) :-
  766    stamp_date_time(Now, DateTime, local),
  767    date_time_value(time, DateTime, time(HH,MM,_)).
  768scheduled(weekly(Day, Time), Now) :-
  769    stamp_date_time(Now, DateTime, local),
  770    date_time_value(date, DateTime, Date),
  771    day_of_the_week(Date, Day),
  772    scheduled(daily(Time), Now).
  773scheduled(monthly(Day, Time), Now) :-
  774    stamp_date_time(Now, DateTime, local),
  775    date_time_value(day, DateTime, Day),
  776    scheduled(daily(Time), Now).
  777
  778day(1, mon).
  779day(2, tue).
  780day(3, wed).
  781day(4, thu).
  782day(5, fri).
  783day(6, sat).
  784day(7, sun)