Added 'S' to the itemized output for special files.
[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                 goto pre_scan;
269         case FINFO:
270                 f = am_server ? stderr : stdout;
271         pre_scan:
272                 while (len > 1 && (*buf == '\n' || *buf == '\t')) {
273                         fputc(*buf, f);
274                         buf++;
275                         len--;
276                 }
277                 break;
278         case FNAME:
279                 f = am_server ? stderr : stdout;
280                 break;
281         default:
282                 exit_cleanup(RERR_MESSAGEIO);
283         }
284
285         trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
286                           ? buf[--len] : 0;
287
288         filtered_fwrite(buf, len, f);
289
290         if (trailing_CR_or_NL) {
291                 fputc(trailing_CR_or_NL, f);
292                 fflush(f);
293         }
294 }
295
296 /* This is the rsync debugging function. Call it with FINFO, FERROR or
297  * FLOG. */
298 void rprintf(enum logcode code, const char *format, ...)
299 {
300         va_list ap;
301         char buf[BIGPATHBUFLEN];
302         size_t len;
303
304         va_start(ap, format);
305         len = vsnprintf(buf, sizeof buf, format, ap);
306         va_end(ap);
307
308         /* Deal with buffer overruns.  Instead of panicking, just
309          * truncate the resulting string.  (Note that configure ensures
310          * that we have a vsnprintf() that doesn't ever return -1.) */
311         if (len > sizeof buf - 1) {
312                 static const char ellipsis[] = "[...]";
313
314                 /* Reset length, and zero-terminate the end of our buffer */
315                 len = sizeof buf - 1;
316                 buf[len] = '\0';
317
318                 /* Copy the ellipsis to the end of the string, but give
319                  * us one extra character:
320                  *
321                  *                  v--- null byte at buf[sizeof buf - 1]
322                  *        abcdefghij0
323                  *     -> abcd[...]00  <-- now two null bytes at end
324                  *
325                  * If the input format string has a trailing newline,
326                  * we copy it into that extra null; if it doesn't, well,
327                  * all we lose is one byte.  */
328                 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
329                 if (format[strlen(format)-1] == '\n') {
330                         buf[len-1] = '\n';
331                 }
332         }
333
334         rwrite(code, buf, len);
335 }
336
337 /* This is like rprintf, but it also tries to print some
338  * representation of the error code.  Normally errcode = errno.
339  *
340  * Unlike rprintf, this always adds a newline and there should not be
341  * one in the format string.
342  *
343  * Note that since strerror might involve dynamically loading a
344  * message catalog we need to call it once before chroot-ing. */
345 void rsyserr(enum logcode code, int errcode, const char *format, ...)
346 {
347         va_list ap;
348         char buf[BIGPATHBUFLEN];
349         size_t len;
350
351         strcpy(buf, RSYNC_NAME ": ");
352         len = (sizeof RSYNC_NAME ": ") - 1;
353
354         va_start(ap, format);
355         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
356         va_end(ap);
357
358         if (len < sizeof buf) {
359                 len += snprintf(buf + len, sizeof buf - len,
360                                 ": %s (%d)\n", strerror(errcode), errcode);
361         }
362         if (len >= sizeof buf)
363                 exit_cleanup(RERR_MESSAGEIO);
364
365         rwrite(code, buf, len);
366 }
367
368 void rflush(enum logcode code)
369 {
370         FILE *f = NULL;
371
372         if (am_daemon) {
373                 return;
374         }
375
376         if (code == FLOG) {
377                 return;
378         }
379
380         if (code == FERROR) {
381                 f = stderr;
382         }
383
384         if (code == FINFO) {
385                 if (am_server)
386                         f = stderr;
387                 else
388                         f = stdout;
389         }
390
391         if (!f) exit_cleanup(RERR_MESSAGEIO);
392         fflush(f);
393 }
394
395 /* a generic logging routine for send/recv, with parameter
396  * substitiution */
397 static void log_formatted(enum logcode code, char *format, char *op,
398                           struct file_struct *file, struct stats *initial_stats,
399                           int iflags, char *hlink)
400 {
401         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
402         char *p, *s, *n;
403         size_t len, total;
404         int64 b;
405
406         *fmt = '%';
407
408         /* We expand % codes one by one in place in buf.  We don't
409          * copy in the terminating null of the inserted strings, but
410          * rather keep going until we reach the null of the format. */
411         total = strlcpy(buf, format, sizeof buf);
412         if (total > MAXPATHLEN) {
413                 rprintf(FERROR, "log-format string is WAY too long!\n");
414                 exit_cleanup(RERR_MESSAGEIO);
415         }
416         buf[total++] = '\n';
417         buf[total] = '\0';
418
419         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
420                 s = p++;
421                 n = fmt + 1;
422                 if (*p == '-')
423                         *n++ = *p++;
424                 while (isdigit(*(uchar*)p) && n - fmt < (int)(sizeof fmt) - 8)
425                         *n++ = *p++;
426                 if (!*p)
427                         break;
428                 *n = '\0';
429                 n = NULL;
430
431                 switch (*p) {
432                 case 'h':
433                         if (am_daemon)
434                                 n = client_name(0);
435                         break;
436                 case 'a':
437                         if (am_daemon)
438                                 n = client_addr(0);
439                         break;
440                 case 'l':
441                         strlcat(fmt, ".0f", sizeof fmt);
442                         snprintf(buf2, sizeof buf2, fmt,
443                                  (double)file->length);
444                         n = buf2;
445                         break;
446                 case 'p':
447                         strlcat(fmt, "ld", sizeof fmt);
448                         snprintf(buf2, sizeof buf2, fmt,
449                                  (long)getpid());
450                         n = buf2;
451                         break;
452                 case 'o':
453                         n = op;
454                         break;
455                 case 'f':
456                         n = f_name(file, NULL);
457                         if (am_sender && file->dir.root) {
458                                 pathjoin(buf2, sizeof buf2,
459                                          file->dir.root, n);
460                                 clean_fname(buf2, 0);
461                                 if (fmt[1])
462                                         strlcpy(n, buf2, MAXPATHLEN);
463                                 else
464                                         n = buf2;
465                         } else
466                                 clean_fname(n, 0);
467                         if (*n == '/')
468                                 n++;
469                         break;
470                 case 'n':
471                         n = f_name(file, NULL);
472                         if (S_ISDIR(file->mode))
473                                 strlcat(n, "/", MAXPATHLEN);
474                         break;
475                 case 'L':
476                         if (hlink && *hlink) {
477                                 n = hlink;
478                                 strcpy(buf2, " => ");
479                         } else if (S_ISLNK(file->mode) && file->u.link) {
480                                 n = file->u.link;
481                                 strcpy(buf2, " -> ");
482                         } else {
483                                 n = "";
484                                 if (!fmt[1])
485                                         break;
486                                 strcpy(buf2, "    ");
487                         }
488                         strlcat(fmt, "s", sizeof fmt);
489                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
490                         n = buf2;
491                         break;
492                 case 'm':
493                         n = lp_name(module_id);
494                         break;
495                 case 't':
496                         n = timestring(time(NULL));
497                         break;
498                 case 'P':
499                         n = lp_path(module_id);
500                         break;
501                 case 'u':
502                         n = auth_user;
503                         break;
504                 case 'b':
505                         if (am_sender) {
506                                 b = stats.total_written -
507                                         initial_stats->total_written;
508                         } else {
509                                 b = stats.total_read -
510                                         initial_stats->total_read;
511                         }
512                         strlcat(fmt, ".0f", sizeof fmt);
513                         snprintf(buf2, sizeof buf2, fmt, (double)b);
514                         n = buf2;
515                         break;
516                 case 'c':
517                         if (!am_sender) {
518                                 b = stats.total_written -
519                                         initial_stats->total_written;
520                         } else {
521                                 b = stats.total_read -
522                                         initial_stats->total_read;
523                         }
524                         strlcat(fmt, ".0f", sizeof fmt);
525                         snprintf(buf2, sizeof buf2, fmt, (double)b);
526                         n = buf2;
527                         break;
528                 case 'i':
529                         if (iflags & ITEM_DELETED) {
530                                 n = "*deleting";
531                                 break;
532                         }
533                         n = buf2 + MAXPATHLEN - 32;
534                         n[0] = iflags & ITEM_LOCAL_CHANGE
535                               ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
536                              : !(iflags & ITEM_TRANSFER) ? '.'
537                              : !local_server && *op == 's' ? '<' : '>';
538                         n[1] = S_ISDIR(file->mode) ? 'd'
539                              : IS_SPECIAL(file->mode) ? 'S'
540                              : IS_DEVICE(file->mode) ? 'D'
541                              : S_ISLNK(file->mode) ? 'L' : 'f';
542                         n[2] = !(iflags & ITEM_REPORT_CHECKSUM) ? '.' : 'c';
543                         n[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
544                         n[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
545                              : !preserve_times || S_ISLNK(file->mode) ? 'T' : 't';
546                         n[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
547                         n[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
548                         n[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
549                         n[8] = '\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                 || log_format_has_i > 1 || (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 }