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