]> sjero.net Git - wget/blob - src/log.c
mass change: update copyright years.
[wget] / src / log.c
1 /* Messages logging.
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3    2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget.  If not, see <http://www.gnu.org/licenses/>.
19
20 Additional permission under GNU GPL version 3 section 7
21
22 If you modify this program, or any covered work, by linking or
23 combining it with the OpenSSL project's OpenSSL library (or a
24 modified version of that library), containing parts covered by the
25 terms of the OpenSSL or SSLeay licenses, the Free Software Foundation
26 grants you additional permission to convey the resulting work.
27 Corresponding Source for a non-source form of such a combination
28 shall include the source code for the parts of OpenSSL used as well
29 as that of the covered work.  */
30
31 #include "wget.h"
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdarg.h>
37 #include <unistd.h>
38 #include <assert.h>
39 #include <errno.h>
40
41 #include "utils.h"
42 #include "log.h"
43
44 /* 2005-10-25 SMS.
45    VMS log files are often VFC record format, not stream, so fputs() can
46    produce multiple records, even when there's no newline terminator in
47    the buffer.  The result is unsightly output with spurious newlines.
48    Using fprintf() instead of fputs(), along with inhibiting some
49    fflush() activity below, seems to solve the problem.
50 */
51 #ifdef __VMS
52 # define FPUTS( s, f) fprintf( (f), "%s", (s))
53 #else /* def __VMS */
54 # define FPUTS( s, f) fputs( (s), (f))
55 #endif /* def __VMS [else] */
56
57 /* This file implements support for "logging".  Logging means printing
58    output, plus several additional features:
59
60    - Cataloguing output by importance.  You can specify that a log
61    message is "verbose" or "debug", and it will not be printed unless
62    in verbose or debug mode, respectively.
63
64    - Redirecting the log to the file.  When Wget's output goes to the
65    terminal, and Wget receives SIGHUP, all further output is
66    redirected to a log file.  When this is the case, Wget can also
67    print the last several lines of "context" to the log file so that
68    it does not begin in the middle of a line.  For this to work, the
69    logging code stores the last several lines of context.  Callers may
70    request for certain output not to be stored.
71
72    - Inhibiting output.  When Wget receives SIGHUP, but redirecting
73    the output fails, logging is inhibited.  */
74
75 \f
76 /* The file descriptor used for logging.  This is NULL before log_init
77    is called; logging functions log to stderr then.  log_init sets it
78    either to stderr or to a file pointer obtained from fopen().  If
79    logging is inhibited, logfp is set back to NULL. */
80 static FILE *logfp;
81
82 /* If true, it means logging is inhibited, i.e. nothing is printed or
83    stored.  */
84 static bool inhibit_logging;
85
86 /* Whether the last output lines are stored for use as context.  */
87 static bool save_context_p;
88
89 /* Whether the log is flushed after each command. */
90 static bool flush_log_p = true;
91
92 /* Whether any output has been received while flush_log_p was 0. */
93 static bool needs_flushing;
94
95 /* In the event of a hang-up, and if its output was on a TTY, Wget
96    redirects its output to `wget-log'.
97
98    For the convenience of reading this newly-created log, we store the
99    last several lines ("screenful", hence the choice of 24) of Wget
100    output, and dump them as context when the time comes.  */
101 #define SAVED_LOG_LINES 24
102
103 /* log_lines is a circular buffer that stores SAVED_LOG_LINES lines of
104    output.  log_line_current always points to the position in the
105    buffer that will be written to next.  When log_line_current reaches
106    SAVED_LOG_LINES, it is reset to zero.
107
108    The problem here is that we'd have to either (re)allocate and free
109    strings all the time, or limit the lines to an arbitrary number of
110    characters.  Instead of settling for either of these, we do both:
111    if the line is smaller than a certain "usual" line length (128
112    chars by default), a preallocated memory is used.  The rare lines
113    that are longer than 128 characters are malloc'ed and freed
114    separately.  This gives good performance with minimum memory
115    consumption and fragmentation.  */
116
117 #define STATIC_LENGTH 128
118
119 static struct log_ln {
120   char static_line[STATIC_LENGTH + 1]; /* statically allocated
121                                           line. */
122   char *malloced_line;          /* malloc'ed line, for lines of output
123                                    larger than 80 characters. */
124   char *content;                /* this points either to malloced_line
125                                    or to the appropriate static_line.
126                                    If this is NULL, it means the line
127                                    has not yet been used. */
128 } log_lines[SAVED_LOG_LINES];
129
130 /* The current position in the ring. */
131 static int log_line_current = -1;
132
133 /* Whether the most recently written line was "trailing", i.e. did not
134    finish with \n.  This is an important piece of information because
135    the code is always careful to append data to trailing lines, rather
136    than create new ones.  */
137 static bool trailing_line;
138
139 static void check_redirect_output (void);
140 \f
141 #define ROT_ADVANCE(num) do {                   \
142   if (++num >= SAVED_LOG_LINES)                 \
143     num = 0;                                    \
144 } while (0)
145
146 /* Free the log line index with NUM.  This calls free on
147    ln->malloced_line if it's non-NULL, and it also resets
148    ln->malloced_line and ln->content to NULL.  */
149
150 static void
151 free_log_line (int num)
152 {
153   struct log_ln *ln = log_lines + num;
154   if (ln->malloced_line)
155     {
156       xfree (ln->malloced_line);
157       ln->malloced_line = NULL;
158     }
159   ln->content = NULL;
160 }
161
162 /* Append bytes in the range [start, end) to one line in the log.  The
163    region is not supposed to contain newlines, except for the last
164    character (at end[-1]).  */
165
166 static void
167 saved_append_1 (const char *start, const char *end)
168 {
169   int len = end - start;
170   if (!len)
171     return;
172
173   /* First, check whether we need to append to an existing line or to
174      create a new one.  */
175   if (!trailing_line)
176     {
177       /* Create a new line. */
178       struct log_ln *ln;
179
180       if (log_line_current == -1)
181         log_line_current = 0;
182       else
183         free_log_line (log_line_current);
184       ln = log_lines + log_line_current;
185       if (len > STATIC_LENGTH)
186         {
187           ln->malloced_line = strdupdelim (start, end);
188           ln->content = ln->malloced_line;
189         }
190       else
191         {
192           memcpy (ln->static_line, start, len);
193           ln->static_line[len] = '\0';
194           ln->content = ln->static_line;
195         }
196     }
197   else
198     {
199       /* Append to the last line.  If the line is malloc'ed, we just
200          call realloc and append the new string.  If the line is
201          static, we have to check whether appending the new string
202          would make it exceed STATIC_LENGTH characters, and if so,
203          convert it to malloc(). */
204       struct log_ln *ln = log_lines + log_line_current;
205       if (ln->malloced_line)
206         {
207           /* Resize malloc'ed line and append. */
208           int old_len = strlen (ln->malloced_line);
209           ln->malloced_line = xrealloc (ln->malloced_line, old_len + len + 1);
210           memcpy (ln->malloced_line + old_len, start, len);
211           ln->malloced_line[old_len + len] = '\0';
212           /* might have changed due to realloc */
213           ln->content = ln->malloced_line;
214         }
215       else
216         {
217           int old_len = strlen (ln->static_line);
218           if (old_len + len > STATIC_LENGTH)
219             {
220               /* Allocate memory and concatenate the old and the new
221                  contents. */
222               ln->malloced_line = xmalloc (old_len + len + 1);
223               memcpy (ln->malloced_line, ln->static_line,
224                       old_len);
225               memcpy (ln->malloced_line + old_len, start, len);
226               ln->malloced_line[old_len + len] = '\0';
227               ln->content = ln->malloced_line;
228             }
229           else
230             {
231               /* Just append to the old, statically allocated
232                  contents.  */
233               memcpy (ln->static_line + old_len, start, len);
234               ln->static_line[old_len + len] = '\0';
235               ln->content = ln->static_line;
236             }
237         }
238     }
239   trailing_line = !(end[-1] == '\n');
240   if (!trailing_line)
241     ROT_ADVANCE (log_line_current);
242 }
243
244 /* Log the contents of S, as explained above.  If S consists of
245    multiple lines, they are logged separately.  If S does not end with
246    a newline, it will form a "trailing" line, to which things will get
247    appended the next time this function is called.  */
248
249 static void
250 saved_append (const char *s)
251 {
252   while (*s)
253     {
254       const char *end = strchr (s, '\n');
255       if (!end)
256         end = s + strlen (s);
257       else
258         ++end;
259       saved_append_1 (s, end);
260       s = end;
261     }
262 }
263 \f
264 /* Check X against opt.verbose and opt.quiet.  The semantics is as
265    follows:
266
267    * LOG_ALWAYS - print the message unconditionally;
268
269    * LOG_NOTQUIET - print the message if opt.quiet is non-zero;
270
271    * LOG_NONVERBOSE - print the message if opt.verbose is zero;
272
273    * LOG_VERBOSE - print the message if opt.verbose is non-zero.  */
274 #define CHECK_VERBOSE(x)                        \
275   switch (x)                                    \
276     {                                           \
277     case LOG_ALWAYS:                            \
278       break;                                    \
279     case LOG_NOTQUIET:                          \
280       if (opt.quiet)                            \
281         return;                                 \
282       break;                                    \
283     case LOG_NONVERBOSE:                        \
284       if (opt.verbose || opt.quiet)             \
285         return;                                 \
286       break;                                    \
287     case LOG_VERBOSE:                           \
288       if (!opt.verbose)                         \
289         return;                                 \
290     }
291
292 /* Returns the file descriptor for logging.  This is LOGFP, except if
293    called before log_init, in which case it returns stderr.  This is
294    useful in case someone calls a logging function before log_init.
295
296    If logging is inhibited, return NULL.  */
297
298 static FILE *
299 get_log_fp (void)
300 {
301   if (inhibit_logging)
302     return NULL;
303   if (logfp)
304     return logfp;
305   return stderr;
306 }
307 \f
308 /* Log a literal string S.  The string is logged as-is, without a
309    newline appended.  */
310
311 void
312 logputs (enum log_options o, const char *s)
313 {
314   FILE *fp;
315
316   check_redirect_output ();
317   if ((fp = get_log_fp ()) == NULL)
318     return;
319   CHECK_VERBOSE (o);
320
321   FPUTS (s, fp);
322   if (save_context_p)
323     saved_append (s);
324   if (flush_log_p)
325     logflush ();
326   else
327     needs_flushing = true;
328 }
329
330 struct logvprintf_state {
331   char *bigmsg;
332   int expected_size;
333   int allocated;
334 };
335
336 /* Print a message to the log.  A copy of message will be saved to
337    saved_log, for later reusal by log_dump_context().
338
339    Normally we'd want this function to loop around vsnprintf until
340    sufficient room is allocated, as the Linux man page recommends.
341    However each call to vsnprintf() must be preceded by va_start and
342    followed by va_end.  Since calling va_start/va_end is possible only
343    in the function that contains the `...' declaration, we cannot call
344    vsnprintf more than once.  Therefore this function saves its state
345    to logvprintf_state and signals the parent to call it again.
346
347    (An alternative approach would be to use va_copy, but that's not
348    portable.)  */
349
350 static bool
351 log_vprintf_internal (struct logvprintf_state *state, const char *fmt,
352                       va_list args)
353 {
354   char smallmsg[128];
355   char *write_ptr = smallmsg;
356   int available_size = sizeof (smallmsg);
357   int numwritten;
358   FILE *fp = get_log_fp ();
359
360   if (!save_context_p)
361     {
362       /* In the simple case just call vfprintf(), to avoid needless
363          allocation and games with vsnprintf(). */
364       vfprintf (fp, fmt, args);
365       goto flush;
366     }
367
368   if (state->allocated != 0)
369     {
370       write_ptr = state->bigmsg;
371       available_size = state->allocated;
372     }
373
374   /* The GNU coding standards advise not to rely on the return value
375      of sprintf().  However, vsnprintf() is a relatively new function
376      missing from legacy systems.  Therefore I consider it safe to
377      assume that its return value is meaningful.  On the systems where
378      vsnprintf() is not available, we use the implementation from
379      snprintf.c which does return the correct value.  */
380   numwritten = vsnprintf (write_ptr, available_size, fmt, args);
381
382   /* vsnprintf() will not step over the limit given by available_size.
383      If it fails, it returns either -1 (older implementations) or the
384      number of characters (not counting the terminating \0) that
385      *would have* been written if there had been enough room (C99).
386      In the former case, we double available_size and malloc to get a
387      larger buffer, and try again.  In the latter case, we use the
388      returned information to build a buffer of the correct size.  */
389
390   if (numwritten == -1)
391     {
392       /* Writing failed, and we don't know the needed size.  Try
393          again with doubled size. */
394       int newsize = available_size << 1;
395       state->bigmsg = xrealloc (state->bigmsg, newsize);
396       state->allocated = newsize;
397       return false;
398     }
399   else if (numwritten >= available_size)
400     {
401       /* Writing failed, but we know exactly how much space we
402          need. */
403       int newsize = numwritten + 1;
404       state->bigmsg = xrealloc (state->bigmsg, newsize);
405       state->allocated = newsize;
406       return false;
407     }
408
409   /* Writing succeeded. */
410   saved_append (write_ptr);
411   FPUTS (write_ptr, fp);
412   if (state->bigmsg)
413     xfree (state->bigmsg);
414
415  flush:
416   if (flush_log_p)
417     logflush ();
418   else
419     needs_flushing = true;
420
421   return true;
422 }
423
424 /* Flush LOGFP.  Useful while flushing is disabled.  */
425 void
426 logflush (void)
427 {
428   FILE *fp = get_log_fp ();
429   if (fp)
430     {
431 /* 2005-10-25 SMS.
432    On VMS, flush only for a terminal.  See note at FPUTS macro, above.
433 */
434 #ifdef __VMS
435       if (isatty( fileno( fp)))
436         {
437           fflush (fp);
438         }
439 #else /* def __VMS */
440       fflush (fp);
441 #endif /* def __VMS [else] */
442     }
443   needs_flushing = false;
444 }
445
446 /* Enable or disable log flushing. */
447 void
448 log_set_flush (bool flush)
449 {
450   if (flush == flush_log_p)
451     return;
452
453   if (flush == false)
454     {
455       /* Disable flushing by setting flush_log_p to 0. */
456       flush_log_p = false;
457     }
458   else
459     {
460       /* Reenable flushing.  If anything was printed in no-flush mode,
461          flush the log now.  */
462       if (needs_flushing)
463         logflush ();
464       flush_log_p = true;
465     }
466 }
467
468 /* (Temporarily) disable storing log to memory.  Returns the old
469    status of storing, with which this function can be called again to
470    reestablish storing. */
471
472 bool
473 log_set_save_context (bool savep)
474 {
475   bool old = save_context_p;
476   save_context_p = savep;
477   return old;
478 }
479
480 /* Print a message to the screen or to the log.  The first argument
481    defines the verbosity of the message, and the rest are as in
482    printf(3).  */
483
484 void
485 logprintf (enum log_options o, const char *fmt, ...)
486 {
487   va_list args;
488   struct logvprintf_state lpstate;
489   bool done;
490
491   check_redirect_output ();
492   if (inhibit_logging)
493     return;
494   CHECK_VERBOSE (o);
495
496   xzero (lpstate);
497   do
498     {
499       va_start (args, fmt);
500       done = log_vprintf_internal (&lpstate, fmt, args);
501       va_end (args);
502     }
503   while (!done);
504 }
505
506 #ifdef ENABLE_DEBUG
507 /* The same as logprintf(), but does anything only if opt.debug is
508    true.  */
509 void
510 debug_logprintf (const char *fmt, ...)
511 {
512   if (opt.debug)
513     {
514       va_list args;
515       struct logvprintf_state lpstate;
516       bool done;
517
518       check_redirect_output ();
519       if (inhibit_logging)
520         return;
521
522       xzero (lpstate);
523       do
524         {
525           va_start (args, fmt);
526           done = log_vprintf_internal (&lpstate, fmt, args);
527           va_end (args);
528         }
529       while (!done);
530     }
531 }
532 #endif /* ENABLE_DEBUG */
533 \f
534 /* Open FILE and set up a logging stream.  If FILE cannot be opened,
535    exit with status of 1.  */
536 void
537 log_init (const char *file, bool appendp)
538 {
539   if (file)
540     {
541       logfp = fopen (file, appendp ? "a" : "w");
542       if (!logfp)
543         {
544           fprintf (stderr, "%s: %s: %s\n", exec_name, file, strerror (errno));
545           exit (1);
546         }
547     }
548   else
549     {
550       /* The log goes to stderr to avoid collisions with the output if
551          the user specifies `-O -'.  #### Francois Pinard suggests
552          that it's a better idea to print to stdout by default, and to
553          stderr only if the user actually specifies `-O -'.  He says
554          this inconsistency is harder to document, but is overall
555          easier on the user.  */
556       logfp = stderr;
557
558       if (1
559 #ifdef HAVE_ISATTY
560           && isatty (fileno (logfp))
561 #endif
562           )
563         {
564           /* If the output is a TTY, enable save context, i.e. store
565              the most recent several messages ("context") and dump
566              them to a log file in case SIGHUP or SIGUSR1 is received
567              (or Ctrl+Break is pressed under Windows).  */
568           save_context_p = true;
569         }
570     }
571 }
572
573 /* Close LOGFP, inhibit further logging and free the memory associated
574    with it.  */
575 void
576 log_close (void)
577 {
578   int i;
579
580   if (logfp)
581     fclose (logfp);
582   logfp = NULL;
583   inhibit_logging = true;
584   save_context_p = false;
585
586   for (i = 0; i < SAVED_LOG_LINES; i++)
587     free_log_line (i);
588   log_line_current = -1;
589   trailing_line = false;
590 }
591
592 /* Dump saved lines to logfp. */
593 static void
594 log_dump_context (void)
595 {
596   int num = log_line_current;
597   FILE *fp = get_log_fp ();
598   if (!fp)
599     return;
600
601   if (num == -1)
602     return;
603   if (trailing_line)
604     ROT_ADVANCE (num);
605   do
606     {
607       struct log_ln *ln = log_lines + num;
608       if (ln->content)
609         FPUTS (ln->content, fp);
610       ROT_ADVANCE (num);
611     }
612   while (num != log_line_current);
613   if (trailing_line)
614     if (log_lines[log_line_current].content)
615       FPUTS (log_lines[log_line_current].content, fp);
616   fflush (fp);
617 }
618 \f
619 /* String escape functions. */
620
621 /* Return the number of non-printable characters in SOURCE.
622    Non-printable characters are determined as per c-ctype.c.  */
623
624 static int
625 count_nonprint (const char *source)
626 {
627   const char *p;
628   int cnt;
629   for (p = source, cnt = 0; *p; p++)
630     if (!c_isprint (*p))
631       ++cnt;
632   return cnt;
633 }
634
635 /* Copy SOURCE to DEST, escaping non-printable characters.
636
637    Non-printable refers to anything outside the non-control ASCII
638    range (32-126) which means that, for example, CR, LF, and TAB are
639    considered non-printable along with ESC, BS, and other control
640    chars.  This is by design: it makes sure that messages from remote
641    servers cannot be easily used to deceive the users by mimicking
642    Wget's output.  Disallowing non-ASCII characters is another
643    necessary security measure, which makes sure that remote servers
644    cannot garble the screen or guess the local charset and perform
645    homographic attacks.
646
647    Of course, the above mandates that escnonprint only be used in
648    contexts expected to be ASCII, such as when printing host names,
649    URL components, HTTP headers, FTP server messages, and the like.
650
651    ESCAPE is the leading character of the escape sequence.  BASE
652    should be the base of the escape sequence, and must be either 8 for
653    octal or 16 for hex.
654
655    DEST must point to a location with sufficient room to store an
656    encoded version of SOURCE.  */
657
658 static void
659 copy_and_escape (const char *source, char *dest, char escape, int base)
660 {
661   const char *from = source;
662   char *to = dest;
663   unsigned char c;
664
665   /* Copy chars from SOURCE to DEST, escaping non-printable ones. */
666   switch (base)
667     {
668     case 8:
669       while ((c = *from++) != '\0')
670         if (c_isprint (c))
671           *to++ = c;
672         else
673           {
674             *to++ = escape;
675             *to++ = '0' + (c >> 6);
676             *to++ = '0' + ((c >> 3) & 7);
677             *to++ = '0' + (c & 7);
678           }
679       break;
680     case 16:
681       while ((c = *from++) != '\0')
682         if (c_isprint (c))
683           *to++ = c;
684         else
685           {
686             *to++ = escape;
687             *to++ = XNUM_TO_DIGIT (c >> 4);
688             *to++ = XNUM_TO_DIGIT (c & 0xf);
689           }
690       break;
691     default:
692       abort ();
693     }
694   *to = '\0';
695 }
696
697 #define RING_SIZE 3
698 struct ringel {
699   char *buffer;
700   int size;
701 };
702 static struct ringel ring[RING_SIZE];   /* ring data */
703
704 static const char *
705 escnonprint_internal (const char *str, char escape, int base)
706 {
707   static int ringpos;                   /* current ring position */
708   int nprcnt;
709
710   assert (base == 8 || base == 16);
711
712   nprcnt = count_nonprint (str);
713   if (nprcnt == 0)
714     /* If there are no non-printable chars in STR, don't bother
715        copying anything, just return STR.  */
716     return str;
717
718   {
719     /* Set up a pointer to the current ring position, so we can write
720        simply r->X instead of ring[ringpos].X. */
721     struct ringel *r = ring + ringpos;
722
723     /* Every non-printable character is replaced with the escape char
724        and three (or two, depending on BASE) *additional* chars.  Size
725        must also include the length of the original string and one
726        additional char for the terminating \0. */
727     int needed_size = strlen (str) + 1 + (base == 8 ? 3 * nprcnt : 2 * nprcnt);
728
729     /* If the current buffer is uninitialized or too small,
730        (re)allocate it.  */
731     if (r->buffer == NULL || r->size < needed_size)
732       {
733         r->buffer = xrealloc (r->buffer, needed_size);
734         r->size = needed_size;
735       }
736
737     copy_and_escape (str, r->buffer, escape, base);
738     ringpos = (ringpos + 1) % RING_SIZE;
739     return r->buffer;
740   }
741 }
742
743 /* Return a pointer to a static copy of STR with the non-printable
744    characters escaped as \ooo.  If there are no non-printable
745    characters in STR, STR is returned.  See copy_and_escape for more
746    information on which characters are considered non-printable.
747
748    DON'T call this function on translated strings because escaping
749    will break them.  Don't call it on literal strings from the source,
750    which are by definition trusted.  If newlines are allowed in the
751    string, escape and print it line by line because escaping the whole
752    string will convert newlines to \012.  (This is so that expectedly
753    single-line messages cannot use embedded newlines to mimic Wget's
754    output and deceive the user.)
755
756    escnonprint doesn't quote its escape character because it is notf
757    meant as a general and reversible quoting mechanism, but as a quick
758    way to defang binary junk sent by malicious or buggy servers.
759
760    NOTE: since this function can return a pointer to static data, be
761    careful to copy its result before calling it again.  However, to be
762    more useful with printf, it maintains an internal ring of static
763    buffers to return.  Currently the ring size is 3, which means you
764    can print up to three values in the same printf; if more is needed,
765    bump RING_SIZE.  */
766
767 const char *
768 escnonprint (const char *str)
769 {
770   return escnonprint_internal (str, '\\', 8);
771 }
772
773 /* Return a pointer to a static copy of STR with the non-printable
774    characters escaped as %XX.  If there are no non-printable
775    characters in STR, STR is returned.
776
777    See escnonprint for usage details.  */
778
779 const char *
780 escnonprint_uri (const char *str)
781 {
782   return escnonprint_internal (str, '%', 16);
783 }
784
785 void
786 log_cleanup (void)
787 {
788   size_t i;
789   for (i = 0; i < countof (ring); i++)
790     xfree_null (ring[i].buffer);
791 }
792 \f
793 /* When SIGHUP or SIGUSR1 are received, the output is redirected
794    elsewhere.  Such redirection is only allowed once. */
795 static enum { RR_NONE, RR_REQUESTED, RR_DONE } redirect_request = RR_NONE;
796 static const char *redirect_request_signal_name;
797
798 /* Redirect output to `wget-log'.  */
799
800 static void
801 redirect_output (void)
802 {
803   char *logfile;
804   logfp = unique_create (DEFAULT_LOGFILE, false, &logfile);
805   if (logfp)
806     {
807       fprintf (stderr, _("\n%s received, redirecting output to %s.\n"),
808                redirect_request_signal_name, quote (logfile));
809       xfree (logfile);
810       /* Dump the context output to the newly opened log.  */
811       log_dump_context ();
812     }
813   else
814     {
815       /* Eek!  Opening the alternate log file has failed.  Nothing we
816          can do but disable printing completely. */
817       fprintf (stderr, _("\n%s received.\n"), redirect_request_signal_name);
818       fprintf (stderr, _("%s: %s; disabling logging.\n"),
819                logfile, strerror (errno));
820       inhibit_logging = true;
821     }
822   save_context_p = false;
823 }
824
825 /* Check whether a signal handler requested the output to be
826    redirected. */
827
828 static void
829 check_redirect_output (void)
830 {
831   if (redirect_request == RR_REQUESTED)
832     {
833       redirect_request = RR_DONE;
834       redirect_output ();
835     }
836 }
837
838 /* Request redirection at a convenient time.  This may be called from
839    a signal handler. */
840
841 void
842 log_request_redirect_output (const char *signal_name)
843 {
844   if (redirect_request == RR_NONE && save_context_p)
845     /* Request output redirection.  The request will be processed by
846        check_redirect_output(), which is called from entry point log
847        functions. */
848     redirect_request = RR_REQUESTED;
849   redirect_request_signal_name = signal_name;
850 }