]> sjero.net Git - wget/blob - src/log.c
[svn] Use stdarg only if compiling with an ANSI C compiler.
[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 #include <config.h>
21
22 /* Use stdarg only if the compiler supports ANSI C and stdarg.h is
23    present.  We check for both because there are configurations where
24    stdarg.h exists, but doesn't work. */
25 #undef WGET_USE_STDARG
26 #ifdef __STDC__
27 # ifdef HAVE_STDARG_H
28 #  define WGET_USE_STDARG
29 # endif
30 #endif
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
53 #ifndef errno
54 extern int errno;
55 #endif
56
57 /* This file impplement 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 non-zero, it means logging is inhibited, i.e. nothing is printed
83    or stored.  */
84 static int inhibit_logging;
85
86 /* Whether the last output lines are stored for use as context.  */
87 static int save_context_p;
88
89 /* Whether the log is flushed after each command. */
90 static int flush_log_p = 1;
91
92 /* Whether any output has been received while flush_log_p was 0. */
93 static int 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 int trailing_line;
138
139 static void check_redirect_output PARAMS ((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 ()))
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 = 1;
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    It is not possible to code this function in a "natural" way, using
340    a loop, because of the braindeadness of the varargs API.
341    Specifically, each call to vsnprintf() must be preceded by va_start
342    and followed by va_end.  And this is possible only in the function
343    that contains the `...' declaration.  The alternative would be to
344    use va_copy, but that's not portable.  */
345
346 static int
347 logvprintf (struct logvprintf_state *state, const char *fmt, va_list args)
348 {
349   char smallmsg[128];
350   char *write_ptr = smallmsg;
351   int available_size = sizeof (smallmsg);
352   int numwritten;
353   FILE *fp = get_log_fp ();
354
355   if (!save_context_p)
356     {
357       /* In the simple case just call vfprintf(), to avoid needless
358          allocation and games with vsnprintf(). */
359       vfprintf (fp, fmt, args);
360       goto flush;
361     }
362
363   if (state->allocated != 0)
364     {
365       write_ptr = state->bigmsg;
366       available_size = state->allocated;
367     }
368
369   /* The GNU coding standards advise not to rely on the return value
370      of sprintf().  However, vsnprintf() is a relatively new function
371      missing from legacy systems.  Therefore I consider it safe to
372      assume that its return value is meaningful.  On the systems where
373      vsnprintf() is not available, we use the implementation from
374      snprintf.c which does return the correct value.  */
375   numwritten = vsnprintf (write_ptr, available_size, fmt, args);
376
377   /* vsnprintf() will not step over the limit given by available_size.
378      If it fails, it will return either -1 (POSIX?) or the number of
379      characters that *would have* been written, if there had been
380      enough room.  In the former case, we double the available_size
381      and malloc() to get a larger buffer, and try again.  In the
382      latter case, we use the returned information to build a buffer of
383      the correct size.  */
384
385   if (numwritten == -1)
386     {
387       /* Writing failed, and we don't know the needed size.  Try
388          again with doubled size. */
389       int newsize = available_size << 1;
390       state->bigmsg = xrealloc (state->bigmsg, newsize);
391       state->allocated = newsize;
392       return 0;
393     }
394   else if (numwritten >= available_size)
395     {
396       /* Writing failed, but we know exactly how much space we
397          need. */
398       int newsize = numwritten + 1;
399       state->bigmsg = xrealloc (state->bigmsg, newsize);
400       state->allocated = newsize;
401       return 0;
402     }
403
404   /* Writing succeeded. */
405   saved_append (write_ptr);
406   fputs (write_ptr, fp);
407   if (state->bigmsg)
408     xfree (state->bigmsg);
409
410  flush:
411   if (flush_log_p)
412     logflush ();
413   else
414     needs_flushing = 1;
415
416   return 1;
417 }
418
419 /* Flush LOGFP.  Useful while flushing is disabled.  */
420 void
421 logflush (void)
422 {
423   FILE *fp = get_log_fp ();
424   if (fp)
425     fflush (fp);
426   needs_flushing = 0;
427 }
428
429 /* Enable or disable log flushing. */
430 void
431 log_set_flush (int flush)
432 {
433   if (flush == flush_log_p)
434     return;
435
436   if (flush == 0)
437     {
438       /* Disable flushing by setting flush_log_p to 0. */
439       flush_log_p = 0;
440     }
441   else
442     {
443       /* Reenable flushing.  If anything was printed in no-flush mode,
444          flush the log now.  */
445       if (needs_flushing)
446         logflush ();
447       flush_log_p = 1;
448     }
449 }
450
451 /* (Temporarily) disable storing log to memory.  Returns the old
452    status of storing, with which this function can be called again to
453    reestablish storing. */
454
455 int
456 log_set_save_context (int savep)
457 {
458   int old = save_context_p;
459   save_context_p = savep;
460   return old;
461 }
462
463 #ifdef WGET_USE_STDARG
464 # define VA_START_1(arg1_type, arg1, args) va_start(args, arg1)
465 # define VA_START_2(arg1_type, arg1, arg2_type, arg2, args) va_start(args, arg2)
466 #else  /* not WGET_USE_STDARG */
467 # define VA_START_1(arg1_type, arg1, args) do { \
468   va_start (args);                                                      \
469   arg1 = va_arg (args, arg1_type);                                      \
470 } while (0)
471 # define VA_START_2(arg1_type, arg1, arg2_type, arg2, args) do {        \
472   va_start (args);                                                      \
473   arg1 = va_arg (args, arg1_type);                                      \
474   arg2 = va_arg (args, arg2_type);                                      \
475 } while (0)
476 #endif /* not WGET_USE_STDARG */
477
478 /* Portability with pre-ANSI compilers makes these two functions look
479    like @#%#@$@#$.  */
480
481 #ifdef WGET_USE_STDARG
482 void
483 logprintf (enum log_options o, const char *fmt, ...)
484 #else  /* not WGET_USE_STDARG */
485 void
486 logprintf (va_alist)
487      va_dcl
488 #endif /* not WGET_USE_STDARG */
489 {
490   va_list args;
491   struct logvprintf_state lpstate;
492   int done;
493
494 #ifndef WGET_USE_STDARG
495   enum log_options o;
496   const char *fmt;
497
498   /* Perform a "dry run" of VA_START_2 to get the value of O. */
499   VA_START_2 (enum log_options, o, char *, fmt, args);
500   va_end (args);
501 #endif
502
503   check_redirect_output ();
504   if (inhibit_logging)
505     return;
506   CHECK_VERBOSE (o);
507
508   memset (&lpstate, '\0', sizeof (lpstate));
509   do
510     {
511       VA_START_2 (enum log_options, o, char *, fmt, args);
512       done = logvprintf (&lpstate, fmt, args);
513       va_end (args);
514     }
515   while (!done);
516 }
517
518 #ifdef DEBUG
519 /* The same as logprintf(), but does anything only if opt.debug is
520    non-zero.  */
521 #ifdef WGET_USE_STDARG
522 void
523 debug_logprintf (const char *fmt, ...)
524 #else  /* not WGET_USE_STDARG */
525 void
526 debug_logprintf (va_alist)
527      va_dcl
528 #endif /* not WGET_USE_STDARG */
529 {
530   if (opt.debug)
531     {
532       va_list args;
533 #ifndef WGET_USE_STDARG
534       const char *fmt;
535 #endif
536       struct logvprintf_state lpstate;
537       int done;
538
539       check_redirect_output ();
540       if (inhibit_logging)
541         return;
542
543       memset (&lpstate, '\0', sizeof (lpstate));
544       do
545         {
546           VA_START_1 (char *, fmt, args);
547           done = logvprintf (&lpstate, fmt, args);
548           va_end (args);
549         }
550       while (!done);
551     }
552 }
553 #endif /* DEBUG */
554 \f
555 /* Open FILE and set up a logging stream.  If FILE cannot be opened,
556    exit with status of 1.  */
557 void
558 log_init (const char *file, int appendp)
559 {
560   if (file)
561     {
562       logfp = fopen (file, appendp ? "a" : "w");
563       if (!logfp)
564         {
565           perror (opt.lfilename);
566           exit (1);
567         }
568     }
569   else
570     {
571       /* The log goes to stderr to avoid collisions with the output if
572          the user specifies `-O -'.  #### Francois Pinard suggests
573          that it's a better idea to print to stdout by default, and to
574          stderr only if the user actually specifies `-O -'.  He says
575          this inconsistency is harder to document, but is overall
576          easier on the user.  */
577       logfp = stderr;
578
579       /* If the output is a TTY, enable storing, which will make Wget
580          remember all the printed messages, to be able to dump them to
581          a log file in case SIGHUP or SIGUSR1 is received (or
582          Ctrl+Break is pressed under Windows).  */
583       if (1
584 #ifdef HAVE_ISATTY
585           && isatty (fileno (logfp))
586 #endif
587           )
588         {
589           save_context_p = 1;
590         }
591     }
592 }
593
594 /* Close LOGFP, inhibit further logging and free the memory associated
595    with it.  */
596 void
597 log_close (void)
598 {
599   int i;
600
601   if (logfp)
602     fclose (logfp);
603   logfp = NULL;
604   inhibit_logging = 1;
605   save_context_p = 0;
606
607   for (i = 0; i < SAVED_LOG_LINES; i++)
608     free_log_line (i);
609   log_line_current = -1;
610   trailing_line = 0;
611 }
612
613 /* Dump saved lines to logfp. */
614 static void
615 log_dump_context (void)
616 {
617   int num = log_line_current;
618   FILE *fp = get_log_fp ();
619   if (!fp)
620     return;
621
622   if (num == -1)
623     return;
624   if (trailing_line)
625     ROT_ADVANCE (num);
626   do
627     {
628       struct log_ln *ln = log_lines + num;
629       if (ln->content)
630         fputs (ln->content, fp);
631       ROT_ADVANCE (num);
632     }
633   while (num != log_line_current);
634   if (trailing_line)
635     if (log_lines[log_line_current].content)
636       fputs (log_lines[log_line_current].content, fp);
637   fflush (fp);
638 }
639 \f
640 /* When SIGHUP or SIGUSR1 are received, the output is redirected
641    elsewhere.  Such redirection is only allowed once. */
642 enum { RR_NONE, RR_REQUESTED, RR_DONE } redirect_request = RR_NONE;
643 static const char *redirect_request_signal_name;
644
645 /* Redirect output to `wget-log'.  */
646
647 static void
648 redirect_output (void)
649 {
650   char *logfile = unique_name (DEFAULT_LOGFILE);
651   fprintf (stderr, _("\n%s received, redirecting output to `%s'.\n"),
652            redirect_request_signal_name, logfile);
653   logfp = fopen (logfile, "w");
654   if (!logfp)
655     {
656       /* Eek!  Opening the alternate log file has failed.  Nothing we
657          can do but disable printing completely. */
658       fprintf (stderr, _("%s: %s; disabling logging.\n"),
659                logfile, strerror (errno));
660       inhibit_logging = 1;
661     }
662   else
663     {
664       /* Dump the context output to the newly opened log.  */
665       log_dump_context ();
666     }
667   xfree (logfile);
668   save_context_p = 0;
669 }
670
671 /* Check whether a signal handler requested the output to be
672    redirected. */
673
674 static void
675 check_redirect_output (void)
676 {
677   if (redirect_request == RR_REQUESTED)
678     {
679       redirect_request = RR_DONE;
680       redirect_output ();
681     }
682 }
683
684 /* Request redirection at a convenient time.  This may be called from
685    a signal handler. */
686
687 void
688 log_request_redirect_output (const char *signal_name)
689 {
690   if (redirect_request == RR_NONE && save_context_p)
691     /* Request output redirection.  The request will be processed by
692        check_redirect_output(), which is called from entry point log
693        functions. */
694     redirect_request = RR_REQUESTED;
695   redirect_request_signal_name = signal_name;
696 }