]> sjero.net Git - wget/blob - src/log.c
96582d522a640008850df1d097270b055f51bdfb
[wget] / src / log.c
1 /* Messages logging.
2    Copyright (C) 1998, 2000, 2001 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables.  You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL".  If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so.  If you do not wish to do
28 so, delete this exception statement from your version.  */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #ifdef HAVE_STRING_H
34 # include <string.h>
35 #else
36 # include <strings.h>
37 #endif
38 #include <stdlib.h>
39 #ifdef WGET_USE_STDARG
40 # include <stdarg.h>
41 #else
42 # include <varargs.h>
43 #endif
44 #ifdef HAVE_UNISTD_H
45 # include <unistd.h>
46 #endif
47 #include <assert.h>
48 #include <errno.h>
49
50 #include "wget.h"
51 #include "utils.h"
52 #include "log.h"
53
54 #ifndef errno
55 extern int errno;
56 #endif
57
58 /* This file impplement support for "logging".  Logging means printing
59    output, plus several additional features:
60
61    - Cataloguing output by importance.  You can specify that a log
62    message is "verbose" or "debug", and it will not be printed unless
63    in verbose or debug mode, respectively.
64
65    - Redirecting the log to the file.  When Wget's output goes to the
66    terminal, and Wget receives SIGHUP, all further output is
67    redirected to a log file.  When this is the case, Wget can also
68    print the last several lines of "context" to the log file so that
69    it does not begin in the middle of a line.  For this to work, the
70    logging code stores the last several lines of context.  Callers may
71    request for certain output not to be stored.
72
73    - Inhibiting output.  When Wget receives SIGHUP, but redirecting
74    the output fails, logging is inhibited.  */
75
76 \f
77 /* The file descriptor used for logging.  This is NULL before log_init
78    is called; logging functions log to stderr then.  log_init sets it
79    either to stderr or to a file pointer obtained from fopen().  If
80    logging is inhibited, logfp is set back to NULL. */
81 static FILE *logfp;
82
83 /* If non-zero, it means logging is inhibited, i.e. nothing is printed
84    or stored.  */
85 static int inhibit_logging;
86
87 /* Whether the last output lines are stored for use as context.  */
88 static int save_context_p;
89
90 /* Whether the log is flushed after each command. */
91 static int flush_log_p = 1;
92
93 /* Whether any output has been received while flush_log_p was 0. */
94 static int needs_flushing;
95
96 /* In the event of a hang-up, and if its output was on a TTY, Wget
97    redirects its output to `wget-log'.
98
99    For the convenience of reading this newly-created log, we store the
100    last several lines ("screenful", hence the choice of 24) of Wget
101    output, and dump them as context when the time comes.  */
102 #define SAVED_LOG_LINES 24
103
104 /* log_lines is a circular buffer that stores SAVED_LOG_LINES lines of
105    output.  log_line_current always points to the position in the
106    buffer that will be written to next.  When log_line_current reaches
107    SAVED_LOG_LINES, it is reset to zero.
108
109    The problem here is that we'd have to either (re)allocate and free
110    strings all the time, or limit the lines to an arbitrary number of
111    characters.  Instead of settling for either of these, we do both:
112    if the line is smaller than a certain "usual" line length (128
113    chars by default), a preallocated memory is used.  The rare lines
114    that are longer than 128 characters are malloc'ed and freed
115    separately.  This gives good performance with minimum memory
116    consumption and fragmentation.  */
117
118 #define STATIC_LENGTH 128
119
120 static struct log_ln {
121   char static_line[STATIC_LENGTH + 1]; /* statically allocated
122                                           line. */
123   char *malloced_line;          /* malloc'ed line, for lines of output
124                                    larger than 80 characters. */
125   char *content;                /* this points either to malloced_line
126                                    or to the appropriate static_line.
127                                    If this is NULL, it means the line
128                                    has not yet been used. */
129 } log_lines[SAVED_LOG_LINES];
130
131 /* The current position in the ring. */
132 static int log_line_current = -1;
133
134 /* Whether the most recently written line was "trailing", i.e. did not
135    finish with \n.  This is an important piece of information because
136    the code is always careful to append data to trailing lines, rather
137    than create new ones.  */
138 static int trailing_line;
139
140 static void check_redirect_output PARAMS ((void));
141 \f
142 #define ROT_ADVANCE(num) do {                   \
143   if (++num >= SAVED_LOG_LINES)                 \
144     num = 0;                                    \
145 } while (0)
146
147 /* Free the log line index with NUM.  This calls free on
148    ln->malloced_line if it's non-NULL, and it also resets
149    ln->malloced_line and ln->content to NULL.  */
150
151 static void
152 free_log_line (int num)
153 {
154   struct log_ln *ln = log_lines + num;
155   if (ln->malloced_line)
156     {
157       xfree (ln->malloced_line);
158       ln->malloced_line = NULL;
159     }
160   ln->content = NULL;
161 }
162
163 /* Append bytes in the range [start, end) to one line in the log.  The
164    region is not supposed to contain newlines, except for the last
165    character (at end[-1]).  */
166
167 static void
168 saved_append_1 (const char *start, const char *end)
169 {
170   int len = end - start;
171   if (!len)
172     return;
173
174   /* First, check whether we need to append to an existing line or to
175      create a new one.  */
176   if (!trailing_line)
177     {
178       /* Create a new line. */
179       struct log_ln *ln;
180
181       if (log_line_current == -1)
182         log_line_current = 0;
183       else
184         free_log_line (log_line_current);
185       ln = log_lines + log_line_current;
186       if (len > STATIC_LENGTH)
187         {
188           ln->malloced_line = strdupdelim (start, end);
189           ln->content = ln->malloced_line;
190         }
191       else
192         {
193           memcpy (ln->static_line, start, len);
194           ln->static_line[len] = '\0';
195           ln->content = ln->static_line;
196         }
197     }
198   else
199     {
200       /* Append to the last line.  If the line is malloc'ed, we just
201          call realloc and append the new string.  If the line is
202          static, we have to check whether appending the new string
203          would make it exceed STATIC_LENGTH characters, and if so,
204          convert it to malloc(). */
205       struct log_ln *ln = log_lines + log_line_current;
206       if (ln->malloced_line)
207         {
208           /* Resize malloc'ed line and append. */
209           int old_len = strlen (ln->malloced_line);
210           ln->malloced_line = xrealloc (ln->malloced_line, old_len + len + 1);
211           memcpy (ln->malloced_line + old_len, start, len);
212           ln->malloced_line[old_len + len] = '\0';
213           /* might have changed due to realloc */
214           ln->content = ln->malloced_line;
215         }
216       else
217         {
218           int old_len = strlen (ln->static_line);
219           if (old_len + len > STATIC_LENGTH)
220             {
221               /* Allocate memory and concatenate the old and the new
222                  contents. */
223               ln->malloced_line = (char *)xmalloc (old_len + len + 1);
224               memcpy (ln->malloced_line, ln->static_line,
225                       old_len);
226               memcpy (ln->malloced_line + old_len, start, len);
227               ln->malloced_line[old_len + len] = '\0';
228               ln->content = ln->malloced_line;
229             }
230           else
231             {
232               /* Just append to the old, statically allocated
233                  contents.  */
234               memcpy (ln->static_line + old_len, start, len);
235               ln->static_line[old_len + len] = '\0';
236               ln->content = ln->static_line;
237             }
238         }
239     }
240   trailing_line = !(end[-1] == '\n');
241   if (!trailing_line)
242     ROT_ADVANCE (log_line_current);
243 }
244
245 /* Log the contents of S, as explained above.  If S consists of
246    multiple lines, they are logged separately.  If S does not end with
247    a newline, it will form a "trailing" line, to which things will get
248    appended the next time this function is called.  */
249
250 static void
251 saved_append (const char *s)
252 {
253   while (*s)
254     {
255       const char *end = strchr (s, '\n');
256       if (!end)
257         end = s + strlen (s);
258       else
259         ++end;
260       saved_append_1 (s, end);
261       s = end;
262     }
263 }
264 \f
265 /* Check X against opt.verbose and opt.quiet.  The semantics is as
266    follows:
267
268    * LOG_ALWAYS - print the message unconditionally;
269
270    * LOG_NOTQUIET - print the message if opt.quiet is non-zero;
271
272    * LOG_NONVERBOSE - print the message if opt.verbose is zero;
273
274    * LOG_VERBOSE - print the message if opt.verbose is non-zero.  */
275 #define CHECK_VERBOSE(x)                        \
276   switch (x)                                    \
277     {                                           \
278     case LOG_ALWAYS:                            \
279       break;                                    \
280     case LOG_NOTQUIET:                          \
281       if (opt.quiet)                            \
282         return;                                 \
283       break;                                    \
284     case LOG_NONVERBOSE:                        \
285       if (opt.verbose || opt.quiet)             \
286         return;                                 \
287       break;                                    \
288     case LOG_VERBOSE:                           \
289       if (!opt.verbose)                         \
290         return;                                 \
291     }
292
293 /* Returns the file descriptor for logging.  This is LOGFP, except if
294    called before log_init, in which case it returns stderr.  This is
295    useful in case someone calls a logging function before log_init.
296
297    If logging is inhibited, return NULL.  */
298
299 static FILE *
300 get_log_fp (void)
301 {
302   if (inhibit_logging)
303     return NULL;
304   if (logfp)
305     return logfp;
306   return stderr;
307 }
308 \f
309 /* Log a literal string S.  The string is logged as-is, without a
310    newline appended.  */
311
312 void
313 logputs (enum log_options o, const char *s)
314 {
315   FILE *fp;
316
317   check_redirect_output ();
318   if (!(fp = get_log_fp ()))
319     return;
320   CHECK_VERBOSE (o);
321
322   fputs (s, fp);
323   if (save_context_p)
324     saved_append (s);
325   if (flush_log_p)
326     logflush ();
327   else
328     needs_flushing = 1;
329 }
330
331 struct logvprintf_state {
332   char *bigmsg;
333   int expected_size;
334   int allocated;
335 };
336
337 /* Print a message to the log.  A copy of message will be saved to
338    saved_log, for later reusal by log_dump_context().
339
340    Normally we'd want this function to loop around vsnprintf until
341    sufficient room is allocated, as the Linux man page recommends.
342    However each call to vsnprintf() must be preceded by va_start and
343    followed by va_end.  Since calling va_start/va_end is possible only
344    in the function that contains the `...' declaration, we cannot call
345    vsnprintf more than once.  Therefore this function saves its state
346    to logvprintf_state and signals the parent to call it again.
347
348    (An alternative approach would be to use va_copy, but that's not
349    portable.)  */
350
351 static int
352 log_vprintf_internal (struct logvprintf_state *state, const char *fmt,
353                       va_list args)
354 {
355   char smallmsg[128];
356   char *write_ptr = smallmsg;
357   int available_size = sizeof (smallmsg);
358   int numwritten;
359   FILE *fp = get_log_fp ();
360
361   if (!save_context_p)
362     {
363       /* In the simple case just call vfprintf(), to avoid needless
364          allocation and games with vsnprintf(). */
365       vfprintf (fp, fmt, args);
366       goto flush;
367     }
368
369   if (state->allocated != 0)
370     {
371       write_ptr = state->bigmsg;
372       available_size = state->allocated;
373     }
374
375   /* The GNU coding standards advise not to rely on the return value
376      of sprintf().  However, vsnprintf() is a relatively new function
377      missing from legacy systems.  Therefore I consider it safe to
378      assume that its return value is meaningful.  On the systems where
379      vsnprintf() is not available, we use the implementation from
380      snprintf.c which does return the correct value.  */
381   numwritten = vsnprintf (write_ptr, available_size, fmt, args);
382
383   /* vsnprintf() will not step over the limit given by available_size.
384      If it fails, it will return either -1 (POSIX?) or the number of
385      characters that *would have* been written, if there had been
386      enough room (C99).  In the former case, we double the
387      available_size and malloc to get a larger buffer, and try again.
388      In the latter case, we use the returned information to build a
389      buffer of the correct size.  */
390
391   if (numwritten == -1)
392     {
393       /* Writing failed, and we don't know the needed size.  Try
394          again with doubled size. */
395       int newsize = available_size << 1;
396       state->bigmsg = xrealloc (state->bigmsg, newsize);
397       state->allocated = newsize;
398       return 0;
399     }
400   else if (numwritten >= available_size)
401     {
402       /* Writing failed, but we know exactly how much space we
403          need. */
404       int newsize = numwritten + 1;
405       state->bigmsg = xrealloc (state->bigmsg, newsize);
406       state->allocated = newsize;
407       return 0;
408     }
409
410   /* Writing succeeded. */
411   saved_append (write_ptr);
412   fputs (write_ptr, fp);
413   if (state->bigmsg)
414     xfree (state->bigmsg);
415
416  flush:
417   if (flush_log_p)
418     logflush ();
419   else
420     needs_flushing = 1;
421
422   return 1;
423 }
424
425 /* Flush LOGFP.  Useful while flushing is disabled.  */
426 void
427 logflush (void)
428 {
429   FILE *fp = get_log_fp ();
430   if (fp)
431     fflush (fp);
432   needs_flushing = 0;
433 }
434
435 /* Enable or disable log flushing. */
436 void
437 log_set_flush (int flush)
438 {
439   if (flush == flush_log_p)
440     return;
441
442   if (flush == 0)
443     {
444       /* Disable flushing by setting flush_log_p to 0. */
445       flush_log_p = 0;
446     }
447   else
448     {
449       /* Reenable flushing.  If anything was printed in no-flush mode,
450          flush the log now.  */
451       if (needs_flushing)
452         logflush ();
453       flush_log_p = 1;
454     }
455 }
456
457 /* (Temporarily) disable storing log to memory.  Returns the old
458    status of storing, with which this function can be called again to
459    reestablish storing. */
460
461 int
462 log_set_save_context (int savep)
463 {
464   int old = save_context_p;
465   save_context_p = savep;
466   return old;
467 }
468
469 /* Handle difference in va_start between pre-ANSI and ANSI C.  Note
470    that we always use `...' in function definitions and let ansi2knr
471    convert it for us.  */
472
473 #ifdef WGET_USE_STDARG
474 # define VA_START(args, arg1) va_start (args, arg1)
475 #else
476 # define VA_START(args, ignored) va_start (args)
477 #endif
478
479 /* Print a message to the screen or to the log.  The first argument
480    defines the verbosity of the message, and the rest are as in
481    printf(3).  */
482
483 void
484 logprintf (enum log_options o, const char *fmt, ...)
485 {
486   va_list args;
487   struct logvprintf_state lpstate;
488   int done;
489
490   check_redirect_output ();
491   if (inhibit_logging)
492     return;
493   CHECK_VERBOSE (o);
494
495   xzero (lpstate);
496   do
497     {
498       VA_START (args, fmt);
499       done = log_vprintf_internal (&lpstate, fmt, args);
500       va_end (args);
501     }
502   while (!done);
503 }
504
505 #ifdef ENABLE_DEBUG
506 /* The same as logprintf(), but does anything only if opt.debug is
507    non-zero.  */
508 void
509 debug_logprintf (const char *fmt, ...)
510 {
511   if (opt.debug)
512     {
513       va_list args;
514       struct logvprintf_state lpstate;
515       int done;
516
517       check_redirect_output ();
518       if (inhibit_logging)
519         return;
520
521       xzero (lpstate);
522       do
523         {
524           VA_START (args, fmt);
525           done = log_vprintf_internal (&lpstate, fmt, args);
526           va_end (args);
527         }
528       while (!done);
529     }
530 }
531 #endif /* ENABLE_DEBUG */
532 \f
533 /* Open FILE and set up a logging stream.  If FILE cannot be opened,
534    exit with status of 1.  */
535 void
536 log_init (const char *file, int appendp)
537 {
538   if (file)
539     {
540       logfp = fopen (file, appendp ? "a" : "w");
541       if (!logfp)
542         {
543           fprintf (stderr, "%s: %s: %s\n", exec_name, file, strerror (errno));
544           exit (1);
545         }
546     }
547   else
548     {
549       /* The log goes to stderr to avoid collisions with the output if
550          the user specifies `-O -'.  #### Francois Pinard suggests
551          that it's a better idea to print to stdout by default, and to
552          stderr only if the user actually specifies `-O -'.  He says
553          this inconsistency is harder to document, but is overall
554          easier on the user.  */
555       logfp = stderr;
556
557       if (1
558 #ifdef HAVE_ISATTY
559           && isatty (fileno (logfp))
560 #endif
561           )
562         {
563           /* If the output is a TTY, enable save context, i.e. store
564              the most recent several messages ("context") and dump
565              them to a log file in case SIGHUP or SIGUSR1 is received
566              (or Ctrl+Break is pressed under Windows).  */
567           save_context_p = 1;
568         }
569     }
570 }
571
572 /* Close LOGFP, inhibit further logging and free the memory associated
573    with it.  */
574 void
575 log_close (void)
576 {
577   int i;
578
579   if (logfp)
580     fclose (logfp);
581   logfp = NULL;
582   inhibit_logging = 1;
583   save_context_p = 0;
584
585   for (i = 0; i < SAVED_LOG_LINES; i++)
586     free_log_line (i);
587   log_line_current = -1;
588   trailing_line = 0;
589 }
590
591 /* Dump saved lines to logfp. */
592 static void
593 log_dump_context (void)
594 {
595   int num = log_line_current;
596   FILE *fp = get_log_fp ();
597   if (!fp)
598     return;
599
600   if (num == -1)
601     return;
602   if (trailing_line)
603     ROT_ADVANCE (num);
604   do
605     {
606       struct log_ln *ln = log_lines + num;
607       if (ln->content)
608         fputs (ln->content, fp);
609       ROT_ADVANCE (num);
610     }
611   while (num != log_line_current);
612   if (trailing_line)
613     if (log_lines[log_line_current].content)
614       fputs (log_lines[log_line_current].content, fp);
615   fflush (fp);
616 }
617 \f
618 /* When SIGHUP or SIGUSR1 are received, the output is redirected
619    elsewhere.  Such redirection is only allowed once. */
620 enum { RR_NONE, RR_REQUESTED, RR_DONE } redirect_request = RR_NONE;
621 static const char *redirect_request_signal_name;
622
623 /* Redirect output to `wget-log'.  */
624
625 static void
626 redirect_output (void)
627 {
628   char *logfile = unique_name (DEFAULT_LOGFILE, 0);
629   fprintf (stderr, _("\n%s received, redirecting output to `%s'.\n"),
630            redirect_request_signal_name, logfile);
631   logfp = fopen (logfile, "w");
632   if (!logfp)
633     {
634       /* Eek!  Opening the alternate log file has failed.  Nothing we
635          can do but disable printing completely. */
636       fprintf (stderr, _("%s: %s; disabling logging.\n"),
637                logfile, strerror (errno));
638       inhibit_logging = 1;
639     }
640   else
641     {
642       /* Dump the context output to the newly opened log.  */
643       log_dump_context ();
644     }
645   xfree (logfile);
646   save_context_p = 0;
647 }
648
649 /* Check whether a signal handler requested the output to be
650    redirected. */
651
652 static void
653 check_redirect_output (void)
654 {
655   if (redirect_request == RR_REQUESTED)
656     {
657       redirect_request = RR_DONE;
658       redirect_output ();
659     }
660 }
661
662 /* Request redirection at a convenient time.  This may be called from
663    a signal handler. */
664
665 void
666 log_request_redirect_output (const char *signal_name)
667 {
668   if (redirect_request == RR_NONE && save_context_p)
669     /* Request output redirection.  The request will be processed by
670        check_redirect_output(), which is called from entry point log
671        functions. */
672     redirect_request = RR_REQUESTED;
673   redirect_request_signal_name = signal_name;
674 }