- We now filter all rwrite() output when it goes out to the terminal
[rsync/rsync.git] / log.c
1 /* -*- c-file-style: "linux"; -*-
2
3    Copyright (C) 1998-2001 by Andrew Tridgell <tridge@samba.org>
4    Copyright (C) 2000-2001 by Martin Pool <mbp@samba.org>
5
6    This program 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    This program 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 this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 /*
22   Logging and utility functions.
23   tridge, May 1998
24
25   Mapping to human-readable messages added by Martin Pool
26   <mbp@samba.org>, Oct 2000.
27   */
28 #include "rsync.h"
29
30 extern int verbose;
31 extern int dry_run;
32 extern int am_daemon;
33 extern int am_server;
34 extern int am_sender;
35 extern int local_server;
36 extern int quiet;
37 extern int module_id;
38 extern int msg_fd_out;
39 extern int protocol_version;
40 extern int preserve_times;
41 extern int log_format_has_i;
42 extern int log_format_has_o_or_i;
43 extern int daemon_log_format_has_o_or_i;
44 extern char *auth_user;
45 extern char *log_format;
46
47 static int log_initialised;
48 static int logfile_was_closed;
49 static char *logfname;
50 static FILE *logfile;
51 struct stats stats;
52
53 int log_got_error = 0;
54
55 struct {
56         int code;
57         char const *name;
58 } const rerr_names[] = {
59         { RERR_SYNTAX     , "syntax or usage error" },
60         { RERR_PROTOCOL   , "protocol incompatibility" },
61         { RERR_FILESELECT , "errors selecting input/output files, dirs" },
62         { RERR_UNSUPPORTED, "requested action not supported" },
63         { RERR_STARTCLIENT, "error starting client-server protocol" },
64         { RERR_SOCKETIO   , "error in socket IO" },
65         { RERR_FILEIO     , "error in file IO" },
66         { RERR_STREAMIO   , "error in rsync protocol data stream" },
67         { RERR_MESSAGEIO  , "errors with program diagnostics" },
68         { RERR_IPC        , "error in IPC code" },
69         { RERR_CRASHED    , "sibling process crashed" },
70         { RERR_TERMINATED , "sibling process terminated abnormally" },
71         { RERR_SIGNAL1    , "received SIGUSR1" },
72         { RERR_SIGNAL     , "received SIGINT, SIGTERM, or SIGHUP" },
73         { RERR_WAITCHILD  , "waitpid() failed" },
74         { RERR_MALLOC     , "error allocating core memory buffers" },
75         { RERR_PARTIAL    , "some files could not be transferred" },
76         { RERR_VANISHED   , "some files vanished before they could be transferred" },
77         { RERR_TIMEOUT    , "timeout in data send/receive" },
78         { RERR_CMD_FAILED , "remote shell failed" },
79         { RERR_CMD_KILLED , "remote shell killed" },
80         { RERR_CMD_RUN    , "remote command could not be run" },
81         { RERR_CMD_NOTFOUND,"remote command not found" },
82         { RERR_DEL_LIMIT  , "the --max-delete limit stopped deletions" },
83         { 0, NULL }
84 };
85
86
87
88 /*
89  * Map from rsync error code to name, or return NULL.
90  */
91 static char const *rerr_name(int code)
92 {
93         int i;
94         for (i = 0; rerr_names[i].name; i++) {
95                 if (rerr_names[i].code == code)
96                         return rerr_names[i].name;
97         }
98         return NULL;
99 }
100
101
102 static void logit(int priority, char *buf)
103 {
104         if (logfile_was_closed)
105                 logfile_reopen();
106         if (logfile) {
107                 fprintf(logfile,"%s [%d] %s",
108                         timestring(time(NULL)), (int)getpid(), buf);
109                 fflush(logfile);
110         } else {
111                 syslog(priority, "%s", buf);
112         }
113 }
114
115 static void syslog_init()
116 {
117         static int been_here = 0;
118         int options = LOG_PID;
119
120         if (been_here)
121                 return;
122         been_here = 1;
123
124 #ifdef LOG_NDELAY
125         options |= LOG_NDELAY;
126 #endif
127
128 #ifdef LOG_DAEMON
129         openlog("rsyncd", options, lp_syslog_facility());
130 #else
131         openlog("rsyncd", options);
132 #endif
133
134 #ifndef LOG_NDELAY
135         logit(LOG_INFO, "rsyncd started\n");
136 #endif
137 }
138
139 static void logfile_open(void)
140 {
141         extern int orig_umask;
142         int old_umask = umask(022 | orig_umask);
143         logfile = fopen(logfname, "a");
144         umask(old_umask);
145         if (!logfile) {
146                 int fopen_errno = errno;
147                 /* Rsync falls back to using syslog on failure. */
148                 syslog_init();
149                 rsyserr(FERROR, fopen_errno,
150                         "failed to open log-file %s", logfname);
151                 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
152         }
153 }
154
155 void log_init(void)
156 {
157         time_t t;
158
159         if (log_initialised)
160                 return;
161         log_initialised = 1;
162
163         /* this looks pointless, but it is needed in order for the
164          * C library on some systems to fetch the timezone info
165          * before the chroot */
166         t = time(NULL);
167         localtime(&t);
168
169         /* optionally use a log file instead of syslog */
170         logfname = lp_log_file();
171         if (logfname && *logfname)
172                 logfile_open();
173         else
174                 syslog_init();
175 }
176
177 void logfile_close(void)
178 {
179         if (logfile) {
180                 logfile_was_closed = 1;
181                 fclose(logfile);
182                 logfile = NULL;
183         }
184 }
185
186 void logfile_reopen(void)
187 {
188         if (logfile_was_closed) {
189                 logfile_was_closed = 0;
190                 logfile_open();
191         }
192 }
193
194 static void filtered_fwrite(const char *buf, int len, FILE *f)
195 {
196         const char *s, *end = buf + len;
197         for (s = buf; s < end; s++) {
198                 if ((s < end - 4
199                   && *s == '\\' && s[1] == '0'
200                   && isdigit(*(uchar*)(s+2))
201                   && isdigit(*(uchar*)(s+3))
202                   && isdigit(*(uchar*)(s+4)))
203                  || !isprint(*(uchar*)s)
204                  || *(uchar*)s < ' ') {
205                         if (s != buf && fwrite(buf, s - buf, 1, f) != 1)
206                                 exit_cleanup(RERR_MESSAGEIO);
207                         fprintf(f, "\\%04o", *(uchar*)s);
208                         buf = s + 1;
209                 }
210         }
211         if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
212                 exit_cleanup(RERR_MESSAGEIO);
213 }
214
215 /* this is the underlying (unformatted) rsync debugging function. Call
216  * it with FINFO, FERROR or FLOG.  Note: recursion can happen with
217  * certain fatal conditions. */
218 void rwrite(enum logcode code, char *buf, int len)
219 {
220         int trailing_CR_or_NL;
221         FILE *f = NULL;
222
223         if (quiet && code == FINFO)
224                 return;
225
226         if (len < 0)
227                 exit_cleanup(RERR_MESSAGEIO);
228
229         if (am_server && msg_fd_out >= 0) {
230                 /* Pass the message to our sibling. */
231                 send_msg((enum msgcode)code, buf, len);
232                 return;
233         }
234
235         if (code == FCLIENT)
236                 code = FINFO;
237         else if (am_daemon) {
238                 static int in_block;
239                 char msg[2048];
240                 int priority = code == FERROR ? LOG_WARNING : LOG_INFO;
241
242                 if (in_block)
243                         return;
244                 in_block = 1;
245                 if (!log_initialised)
246                         log_init();
247                 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
248                 logit(priority, msg);
249                 in_block = 0;
250
251                 if (code == FLOG || !am_server)
252                         return;
253         } else if (code == FLOG)
254                 return;
255
256         if (am_server) {
257                 /* Pass the message to the non-server side. */
258                 if (io_multiplex_write((enum msgcode)code, buf, len))
259                         return;
260                 if (am_daemon) {
261                         /* TODO: can we send the error to the user somehow? */
262                         return;
263                 }
264         }
265
266         switch (code) {
267         case FERROR:
268                 log_got_error = 1;
269                 f = stderr;
270                 break;
271         case FINFO:
272                 f = am_server ? stderr : stdout;
273                 while (len && (*buf == '\n' || *buf == '\t')) {
274                         fputc(*buf, f);
275                         buf++;
276                         len--;
277                 }
278                 break;
279         case FNAME:
280                 f = am_server ? stderr : stdout;
281                 break;
282         default:
283                 exit_cleanup(RERR_MESSAGEIO);
284         }
285
286         trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
287                           ? buf[--len] : 0;
288
289         filtered_fwrite(buf, len, f);
290
291         if (trailing_CR_or_NL) {
292                 fputc(trailing_CR_or_NL, f);
293                 fflush(f);
294         }
295 }
296
297
298 /* This is the rsync debugging function. Call it with FINFO, FERROR or
299  * FLOG. */
300 void rprintf(enum logcode code, const char *format, ...)
301 {
302         va_list ap;
303         char buf[BIGPATHBUFLEN];
304         size_t len;
305
306         va_start(ap, format);
307         len = vsnprintf(buf, sizeof buf, format, ap);
308         va_end(ap);
309
310         /* Deal with buffer overruns.  Instead of panicking, just
311          * truncate the resulting string.  (Note that configure ensures
312          * that we have a vsnprintf() that doesn't ever return -1.) */
313         if (len > sizeof buf - 1) {
314                 static const char ellipsis[] = "[...]";
315
316                 /* Reset length, and zero-terminate the end of our buffer */
317                 len = sizeof buf - 1;
318                 buf[len] = '\0';
319
320                 /* Copy the ellipsis to the end of the string, but give
321                  * us one extra character:
322                  *
323                  *                  v--- null byte at buf[sizeof buf - 1]
324                  *        abcdefghij0
325                  *     -> abcd[...]00  <-- now two null bytes at end
326                  *
327                  * If the input format string has a trailing newline,
328                  * we copy it into that extra null; if it doesn't, well,
329                  * all we lose is one byte.  */
330                 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
331                 if (format[strlen(format)-1] == '\n') {
332                         buf[len-1] = '\n';
333                 }
334         }
335
336         rwrite(code, buf, len);
337 }
338
339
340 /* This is like rprintf, but it also tries to print some
341  * representation of the error code.  Normally errcode = errno.
342  *
343  * Unlike rprintf, this always adds a newline and there should not be
344  * one in the format string.
345  *
346  * Note that since strerror might involve dynamically loading a
347  * message catalog we need to call it once before chroot-ing. */
348 void rsyserr(enum logcode code, int errcode, const char *format, ...)
349 {
350         va_list ap;
351         char buf[BIGPATHBUFLEN];
352         size_t len;
353
354         strcpy(buf, RSYNC_NAME ": ");
355         len = (sizeof RSYNC_NAME ": ") - 1;
356
357         va_start(ap, format);
358         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
359         va_end(ap);
360
361         if (len < sizeof buf) {
362                 len += snprintf(buf + len, sizeof buf - len,
363                                 ": %s (%d)\n", strerror(errcode), errcode);
364         }
365         if (len >= sizeof buf)
366                 exit_cleanup(RERR_MESSAGEIO);
367
368         rwrite(code, buf, len);
369 }
370
371
372
373 void rflush(enum logcode code)
374 {
375         FILE *f = NULL;
376
377         if (am_daemon) {
378                 return;
379         }
380
381         if (code == FLOG) {
382                 return;
383         }
384
385         if (code == FERROR) {
386                 f = stderr;
387         }
388
389         if (code == FINFO) {
390                 if (am_server)
391                         f = stderr;
392                 else
393                         f = stdout;
394         }
395
396         if (!f) exit_cleanup(RERR_MESSAGEIO);
397         fflush(f);
398 }
399
400
401
402 /* a generic logging routine for send/recv, with parameter
403  * substitiution */
404 static void log_formatted(enum logcode code, char *format, char *op,
405                           struct file_struct *file, struct stats *initial_stats,
406                           int iflags, char *hlink)
407 {
408         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
409         char *p, *s, *n;
410         size_t len, total;
411         int64 b;
412
413         *fmt = '%';
414
415         /* We expand % codes one by one in place in buf.  We don't
416          * copy in the terminating null of the inserted strings, but
417          * rather keep going until we reach the null of the format. */
418         total = strlcpy(buf, format, sizeof buf);
419         if (total > MAXPATHLEN) {
420                 rprintf(FERROR, "log-format string is WAY too long!\n");
421                 exit_cleanup(RERR_MESSAGEIO);
422         }
423         buf[total++] = '\n';
424         buf[total] = '\0';
425
426         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
427                 s = p++;
428                 n = fmt + 1;
429                 if (*p == '-')
430                         *n++ = *p++;
431                 while (isdigit(*(uchar*)p) && n - fmt < (int)(sizeof fmt) - 8)
432                         *n++ = *p++;
433                 if (!*p)
434                         break;
435                 *n = '\0';
436                 n = NULL;
437
438                 switch (*p) {
439                 case 'h':
440                         if (am_daemon)
441                                 n = client_name(0);
442                         break;
443                 case 'a':
444                         if (am_daemon)
445                                 n = client_addr(0);
446                         break;
447                 case 'l':
448                         strlcat(fmt, ".0f", sizeof fmt);
449                         snprintf(buf2, sizeof buf2, fmt,
450                                  (double)file->length);
451                         n = buf2;
452                         break;
453                 case 'p':
454                         strlcat(fmt, "ld", sizeof fmt);
455                         snprintf(buf2, sizeof buf2, fmt,
456                                  (long)getpid());
457                         n = buf2;
458                         break;
459                 case 'o':
460                         n = op;
461                         break;
462                 case 'f':
463                         n = f_name(file, NULL);
464                         if (am_sender && file->dir.root) {
465                                 pathjoin(buf2, sizeof buf2,
466                                          file->dir.root, n);
467                                 clean_fname(buf2, 0);
468                                 if (fmt[1])
469                                         strlcpy(n, buf2, MAXPATHLEN);
470                                 else
471                                         n = buf2;
472                         } else
473                                 clean_fname(n, 0);
474                         if (*n == '/')
475                                 n++;
476                         break;
477                 case 'n':
478                         n = f_name(file, NULL);
479                         if (S_ISDIR(file->mode))
480                                 strlcat(n, "/", MAXPATHLEN);
481                         break;
482                 case 'L':
483                         if (hlink && *hlink) {
484                                 n = hlink;
485                                 strcpy(buf2, " => ");
486                         } else if (S_ISLNK(file->mode) && file->u.link) {
487                                 n = file->u.link;
488                                 strcpy(buf2, " -> ");
489                         } else {
490                                 n = "";
491                                 if (!fmt[1])
492                                         break;
493                                 strcpy(buf2, "    ");
494                         }
495                         strlcat(fmt, "s", sizeof fmt);
496                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
497                         n = buf2;
498                         break;
499                 case 'm':
500                         n = lp_name(module_id);
501                         break;
502                 case 't':
503                         n = timestring(time(NULL));
504                         break;
505                 case 'P':
506                         n = lp_path(module_id);
507                         break;
508                 case 'u':
509                         n = auth_user;
510                         break;
511                 case 'b':
512                         if (am_sender) {
513                                 b = stats.total_written -
514                                         initial_stats->total_written;
515                         } else {
516                                 b = stats.total_read -
517                                         initial_stats->total_read;
518                         }
519                         strlcat(fmt, ".0f", sizeof fmt);
520                         snprintf(buf2, sizeof buf2, fmt, (double)b);
521                         n = buf2;
522                         break;
523                 case 'c':
524                         if (!am_sender) {
525                                 b = stats.total_written -
526                                         initial_stats->total_written;
527                         } else {
528                                 b = stats.total_read -
529                                         initial_stats->total_read;
530                         }
531                         strlcat(fmt, ".0f", sizeof fmt);
532                         snprintf(buf2, sizeof buf2, fmt, (double)b);
533                         n = buf2;
534                         break;
535                 case 'i':
536                         if (iflags & ITEM_DELETED) {
537                                 n = "*deleting";
538                                 break;
539                         }
540                         n = buf2 + MAXPATHLEN - 32;
541                         n[0] = iflags & ITEM_LOCAL_CHANGE
542                               ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
543                              : !(iflags & ITEM_TRANSFER) ? '.'
544                              : !local_server && *op == 's' ? '<' : '>';
545                         n[1] = S_ISDIR(file->mode) ? 'd'
546                              : IS_DEVICE(file->mode) ? 'D'
547                              : S_ISLNK(file->mode) ? 'L' : 'f';
548                         n[2] = !(iflags & ITEM_REPORT_CHECKSUM) ? '.' : 'c';
549                         n[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
550                         n[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
551                              : !preserve_times || IS_DEVICE(file->mode)
552                                                || S_ISLNK(file->mode) ? 'T' : 't';
553                         n[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
554                         n[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
555                         n[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
556                         n[8] = !(iflags & ITEM_REPORT_XATTRS) ? '.' : 'a';
557                         n[9] = '\0';
558
559                         if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
560                                 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
561                                 int i;
562                                 for (i = 2; n[i]; i++)
563                                         n[i] = ch;
564                         } else if (n[0] == '.' || n[0] == 'h'
565                                 || (n[0] == 'c' && n[1] == 'f')) {
566                                 int i;
567                                 for (i = 2; n[i]; i++) {
568                                         if (n[i] != '.')
569                                                 break;
570                                 }
571                                 if (!n[i]) {
572                                         for (i = 2; n[i]; i++)
573                                                 n[i] = ' ';
574                                 }
575                         }
576                         break;
577                 }
578
579                 /* "n" is the string to be inserted in place of this % code. */
580                 if (!n)
581                         continue;
582                 if (n != buf2 && fmt[1]) {
583                         strlcat(fmt, "s", sizeof fmt);
584                         snprintf(buf2, sizeof buf2, fmt, n);
585                         n = buf2;
586                 }
587                 len = strlen(n);
588
589                 /* Subtract the length of the escape from the string's size. */
590                 total -= p - s + 1;
591
592                 if (len + total >= (size_t)sizeof buf) {
593                         rprintf(FERROR,
594                                 "buffer overflow expanding %%%c -- exiting\n",
595                                 p[0]);
596                         exit_cleanup(RERR_MESSAGEIO);
597                 }
598
599                 /* Shuffle the rest of the string along to make space for n */
600                 if (len != (size_t)(p - s + 1))
601                         memmove(s + len, p + 1, total - (s - buf) + 1);
602                 total += len;
603
604                 /* Insert the contents of string "n", but NOT its null. */
605                 if (len)
606                         memcpy(s, n, len);
607
608                 /* Skip over inserted string; continue looking */
609                 p = s + len;
610         }
611
612         rwrite(code, buf, total);
613 }
614
615 /* Return 1 if the format escape is in the log-format string (e.g. look for
616  * the 'b' in the "%9b" format escape). */
617 int log_format_has(const char *format, char esc)
618 {
619         const char *p;
620
621         if (!format)
622                 return 0;
623
624         for (p = format; (p = strchr(p, '%')) != NULL; ) {
625                 if (*++p == '-')
626                         p++;
627                 while (isdigit(*(uchar*)p))
628                         p++;
629                 if (!*p)
630                         break;
631                 if (*p == esc)
632                         return 1;
633         }
634         return 0;
635 }
636
637 /* log the transfer of a file */
638 void log_item(struct file_struct *file, struct stats *initial_stats,
639               int iflags, char *hlink)
640 {
641         char *s_or_r = am_sender ? "send" : "recv";
642
643         if (lp_transfer_logging(module_id)) {
644                 log_formatted(FLOG, lp_log_format(module_id), s_or_r,
645                               file, initial_stats, iflags, hlink);
646         } else if (log_format && !am_server) {
647                 log_formatted(FNAME, log_format, s_or_r,
648                               file, initial_stats, iflags, hlink);
649         }
650 }
651
652 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
653                     char *buf)
654 {
655         int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
656         int see_item = itemizing && (significant_flags || *buf
657                                   || (verbose > 1 && log_format_has_i));
658         int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
659         if (am_server) {
660                 if (am_daemon && !dry_run && see_item)
661                         log_item(file, &stats, iflags, buf);
662         } else if (see_item || local_change || *buf
663             || (S_ISDIR(file->mode) && significant_flags))
664                 log_item(file, &stats, iflags, buf);
665 }
666
667 void log_delete(char *fname, int mode)
668 {
669         static struct file_struct file;
670         int len = strlen(fname);
671         char *fmt;
672
673         file.mode = mode;
674         file.basename = fname;
675
676         if (!verbose && !log_format)
677                 ;
678         else if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
679                 if (S_ISDIR(mode))
680                         len++; /* directories include trailing null */
681                 send_msg(MSG_DELETED, fname, len);
682         } else {
683                 fmt = log_format_has_o_or_i ? log_format : "deleting %n";
684                 log_formatted(FCLIENT, fmt, "del.", &file, &stats,
685                               ITEM_DELETED, NULL);
686         }
687
688         if (!am_daemon || dry_run || !lp_transfer_logging(module_id))
689                 return;
690
691         fmt = daemon_log_format_has_o_or_i ? lp_log_format(module_id) : "deleting %n";
692         log_formatted(FLOG, fmt, "del.", &file, &stats, ITEM_DELETED, NULL);
693 }
694
695
696 /*
697  * Called when the transfer is interrupted for some reason.
698  *
699  * Code is one of the RERR_* codes from errcode.h, or terminating
700  * successfully.
701  */
702 void log_exit(int code, const char *file, int line)
703 {
704         if (code == 0) {
705                 rprintf(FLOG,"sent %.0f bytes  received %.0f bytes  total size %.0f\n",
706                         (double)stats.total_written,
707                         (double)stats.total_read,
708                         (double)stats.total_size);
709         } else {
710                 const char *name;
711
712                 name = rerr_name(code);
713                 if (!name)
714                         name = "unexplained error";
715
716                 /* VANISHED is not an error, only a warning */
717                 if (code == RERR_VANISHED) {
718                         rprintf(FINFO, "rsync warning: %s (code %d) at %s(%d)\n", 
719                                 name, code, file, line);
720                 } else {
721                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d)\n",
722                                 name, code, file, line);
723                 }
724         }
725 }