2 * Logging and utility functions.
4 * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5 * Copyright (C) 2000-2001 Martin Pool <mbp@samba.org>
6 * Copyright (C) 2003-2009 Wayne Davison
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
30 extern int am_generator;
31 extern int local_server;
34 extern int checksum_len;
35 extern int allow_8bit_chars;
36 extern int protocol_version;
37 extern int always_checksum;
38 extern int preserve_times;
39 extern int msgs2stderr;
42 extern int stdout_format_has_i;
43 extern int stdout_format_has_o_or_i;
44 extern int logfile_format_has_i;
45 extern int logfile_format_has_o_or_i;
46 extern int receiver_symlink_times;
47 extern int64 total_data_written;
48 extern int64 total_data_read;
49 extern mode_t orig_umask;
50 extern char *auth_user;
51 extern char *stdout_format;
52 extern char *logfile_format;
53 extern char *logfile_name;
55 extern iconv_t ic_chck;
58 extern iconv_t ic_recv;
60 extern char curr_dir[MAXPATHLEN];
61 extern char *full_module_path;
62 extern unsigned int module_dirlen;
63 extern char sender_file_sum[MAX_DIGEST_LEN];
64 extern const char undetermined_hostname[];
66 static int log_initialised;
67 static int logfile_was_closed;
68 static FILE *logfile_fp;
71 int got_xfer_error = 0;
72 int output_needs_newline = 0;
73 int send_msgs_to_gen = 0;
75 static int64 initial_data_written;
76 static int64 initial_data_read;
81 } const rerr_names[] = {
82 { RERR_SYNTAX , "syntax or usage error" },
83 { RERR_PROTOCOL , "protocol incompatibility" },
84 { RERR_FILESELECT , "errors selecting input/output files, dirs" },
85 { RERR_UNSUPPORTED, "requested action not supported" },
86 { RERR_STARTCLIENT, "error starting client-server protocol" },
87 { RERR_SOCKETIO , "error in socket IO" },
88 { RERR_FILEIO , "error in file IO" },
89 { RERR_STREAMIO , "error in rsync protocol data stream" },
90 { RERR_MESSAGEIO , "errors with program diagnostics" },
91 { RERR_IPC , "error in IPC code" },
92 { RERR_CRASHED , "sibling process crashed" },
93 { RERR_TERMINATED , "sibling process terminated abnormally" },
94 { RERR_SIGNAL1 , "received SIGUSR1" },
95 { RERR_SIGNAL , "received SIGINT, SIGTERM, or SIGHUP" },
96 { RERR_WAITCHILD , "waitpid() failed" },
97 { RERR_MALLOC , "error allocating core memory buffers" },
98 { RERR_PARTIAL , "some files/attrs were not transferred (see previous errors)" },
99 { RERR_VANISHED , "some files vanished before they could be transferred" },
100 { RERR_DEL_LIMIT , "the --max-delete limit stopped deletions" },
101 { RERR_TIMEOUT , "timeout in data send/receive" },
102 { RERR_CONTIMEOUT , "timeout waiting for daemon connection" },
103 { RERR_RCVR_ERROR , "exiting due to receiver error" },
104 { RERR_CMD_FAILED , "remote shell failed" },
105 { RERR_CMD_KILLED , "remote shell killed" },
106 { RERR_CMD_RUN , "remote command could not be run" },
107 { RERR_CMD_NOTFOUND,"remote command not found" },
112 * Map from rsync error code to name, or return NULL.
114 static char const *rerr_name(int code)
117 for (i = 0; rerr_names[i].name; i++) {
118 if (rerr_names[i].code == code)
119 return rerr_names[i].name;
124 static void logit(int priority, const char *buf)
126 if (logfile_was_closed)
129 fprintf(logfile_fp, "%s [%d] %s",
130 timestring(time(NULL)), (int)getpid(), buf);
133 syslog(priority, "%s", buf);
137 static void syslog_init()
139 static int been_here = 0;
140 int options = LOG_PID;
147 options |= LOG_NDELAY;
151 openlog("rsyncd", options, lp_syslog_facility(module_id));
153 openlog("rsyncd", options);
157 logit(LOG_INFO, "rsyncd started\n");
161 static void logfile_open(void)
163 mode_t old_umask = umask(022 | orig_umask);
164 logfile_fp = fopen(logfile_name, "a");
167 int fopen_errno = errno;
168 /* Rsync falls back to using syslog on failure. */
170 rsyserr(FERROR, fopen_errno,
171 "failed to open log-file %s", logfile_name);
172 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
176 void log_init(int restart)
178 if (log_initialised) {
181 if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
188 } else if (*logfile_name)
189 return; /* unchanged, non-empty "log file" names */
190 else if (lp_syslog_facility(-1) != lp_syslog_facility(module_id))
193 return; /* unchanged syslog settings */
197 /* This looks pointless, but it is needed in order for the
198 * C library on some systems to fetch the timezone info
199 * before the chroot. */
200 timestring(time(NULL));
202 /* Optionally use a log file instead of syslog. (Non-daemon
203 * rsyncs will have already set logfile_name, as needed.) */
204 if (am_daemon && !logfile_name)
205 logfile_name = lp_log_file(module_id);
206 if (logfile_name && *logfile_name)
212 void logfile_close(void)
215 logfile_was_closed = 1;
221 void logfile_reopen(void)
223 if (logfile_was_closed) {
224 logfile_was_closed = 0;
229 static void filtered_fwrite(FILE *f, const char *buf, int len, int use_isprint)
231 const char *s, *end = buf + len;
232 for (s = buf; s < end; s++) {
234 && *s == '\\' && s[1] == '#'
239 && ((use_isprint && !isPrint(s))
240 || *(uchar*)s < ' '))) {
241 if (s != buf && fwrite(buf, s - buf, 1, f) != 1)
242 exit_cleanup(RERR_MESSAGEIO);
243 fprintf(f, "\\#%03o", *(uchar*)s);
247 if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
248 exit_cleanup(RERR_MESSAGEIO);
251 /* this is the underlying (unformatted) rsync debugging function. Call
252 * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT. Note: recursion
253 * can happen with certain fatal conditions. */
254 void rwrite(enum logcode code, const char *buf, int len, int is_utf8)
256 int trailing_CR_or_NL;
257 FILE *f = msgs2stderr ? stderr : stdout;
259 iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
262 iconv_t ic = ic_chck;
267 exit_cleanup(RERR_MESSAGEIO);
278 } else if (send_msgs_to_gen) {
280 /* Pass the message to our sibling in native charset. */
281 send_msg((enum msgcode)code, buf, len, 0);
285 if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
287 else if (code == FERROR_UTF8) {
294 else if (am_daemon || logfile_name) {
297 int priority = code == FINFO || code == FLOG ? LOG_INFO : LOG_WARNING;
302 if (!log_initialised)
304 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
305 logit(priority, msg);
308 if (code == FLOG || (am_daemon && !am_server))
310 } else if (code == FLOG)
313 if (quiet && code == FINFO)
317 enum msgcode msg = (enum msgcode)code;
318 if (protocol_version < 30) {
319 if (msg == MSG_ERROR)
320 msg = MSG_ERROR_XFER;
321 else if (msg == MSG_WARNING)
324 /* Pass the message to the non-server side. */
325 if (send_msg(msg, buf, len, !is_utf8))
328 /* TODO: can we send the error to the user somehow? */
350 fprintf(stderr, "Unknown logcode in rwrite(): %d\n", (int)code);
351 exit_cleanup(RERR_MESSAGEIO);
354 if (output_needs_newline) {
356 output_needs_newline = 0;
359 trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
362 if (len && buf[0] == '\r') {
369 if (ic != (iconv_t)-1) {
374 INIT_CONST_XBUF(outbuf, convbuf);
375 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
378 iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
381 filtered_fwrite(f, convbuf, outbuf.len, 0);
384 if (!ierrno || ierrno == E2BIG)
386 fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
391 filtered_fwrite(f, buf, len, !allow_8bit_chars);
393 if (trailing_CR_or_NL) {
394 fputc(trailing_CR_or_NL, f);
399 /* This is the rsync debugging function. Call it with FINFO, FERROR_*,
400 * FWARNING, FLOG, or FCLIENT. */
401 void rprintf(enum logcode code, const char *format, ...)
404 char buf[BIGPATHBUFLEN];
407 va_start(ap, format);
408 len = vsnprintf(buf, sizeof buf, format, ap);
411 /* Deal with buffer overruns. Instead of panicking, just
412 * truncate the resulting string. (Note that configure ensures
413 * that we have a vsnprintf() that doesn't ever return -1.) */
414 if (len > sizeof buf - 1) {
415 static const char ellipsis[] = "[...]";
417 /* Reset length, and zero-terminate the end of our buffer */
418 len = sizeof buf - 1;
421 /* Copy the ellipsis to the end of the string, but give
422 * us one extra character:
424 * v--- null byte at buf[sizeof buf - 1]
426 * -> abcd[...]00 <-- now two null bytes at end
428 * If the input format string has a trailing newline,
429 * we copy it into that extra null; if it doesn't, well,
430 * all we lose is one byte. */
431 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
432 if (format[strlen(format)-1] == '\n') {
437 rwrite(code, buf, len, 0);
440 /* This is like rprintf, but it also tries to print some
441 * representation of the error code. Normally errcode = errno.
443 * Unlike rprintf, this always adds a newline and there should not be
444 * one in the format string.
446 * Note that since strerror might involve dynamically loading a
447 * message catalog we need to call it once before chroot-ing. */
448 void rsyserr(enum logcode code, int errcode, const char *format, ...)
451 char buf[BIGPATHBUFLEN];
454 strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
455 len = (sizeof RSYNC_NAME ": ") - 1;
457 va_start(ap, format);
458 len += vsnprintf(buf + len, sizeof buf - len, format, ap);
461 if (len < sizeof buf) {
462 len += snprintf(buf + len, sizeof buf - len,
463 ": %s (%d)\n", strerror(errcode), errcode);
465 if (len >= sizeof buf)
466 exit_cleanup(RERR_MESSAGEIO);
468 rwrite(code, buf, len, 0);
471 void rflush(enum logcode code)
475 if (am_daemon || code == FLOG)
478 if (!am_server && (code == FINFO || code == FCLIENT))
486 void remember_initial_stats(void)
488 initial_data_read = total_data_read;
489 initial_data_written = total_data_written;
492 /* A generic logging routine for send/recv, with parameter substitiution. */
493 static void log_formatted(enum logcode code, const char *format, const char *op,
494 struct file_struct *file, const char *fname, int iflags,
497 char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
505 /* We expand % codes one by one in place in buf. We don't
506 * copy in the terminating null of the inserted strings, but
507 * rather keep going until we reach the null of the format. */
508 total = strlcpy(buf, format, sizeof buf);
509 if (total > MAXPATHLEN) {
510 rprintf(FERROR, "log-format string is WAY too long!\n");
511 exit_cleanup(RERR_MESSAGEIO);
516 for (p = buf; (p = strchr(p, '%')) != NULL; ) {
526 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
537 /* Note for %h and %a: it doesn't matter what fd we pass to
538 * client_{name,addr} because rsync_module will already have
539 * forced the answer to be cached (assuming, of course, for %h
540 * that lp_reverse_lookup(module_id) is true). */
544 n = lp_reverse_lookup(module_id)
545 ? client_name(0) : undetermined_hostname;
553 strlcat(fmt, "s", sizeof fmt);
554 snprintf(buf2, sizeof buf2, fmt,
555 do_big_num(F_LENGTH(file), humanize, NULL));
559 strlcat(fmt, "u", sizeof fmt);
560 snprintf(buf2, sizeof buf2, fmt,
561 uid_ndx ? F_OWNER(file) : 0);
565 if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
568 strlcat(fmt, "u", sizeof fmt);
569 snprintf(buf2, sizeof buf2, fmt,
575 strlcat(fmt, "ld", sizeof fmt);
576 snprintf(buf2, sizeof buf2, fmt,
581 n = c = timestring(file->modtime);
582 while ((c = strchr(c, ' ')) != NULL)
586 c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
587 permstring(c, file->mode);
588 n = c + 1; /* skip the type char */
596 strlcpy(c, fname, MAXPATHLEN);
598 c = f_name(file, NULL);
599 if (am_sender && F_PATHNAME(file)) {
600 pathjoin(buf2, sizeof buf2,
601 F_PATHNAME(file), c);
602 clean_fname(buf2, 0);
604 strlcpy(c, buf2, MAXPATHLEN);
608 } else if (am_daemon && *c != '/') {
609 pathjoin(buf2, sizeof buf2,
610 curr_dir + module_dirlen, c);
611 clean_fname(buf2, 0);
613 strlcpy(c, buf2, MAXPATHLEN);
627 strlcpy(c, fname, MAXPATHLEN);
629 c = f_name(file, NULL);
630 if (S_ISDIR(file->mode))
631 strlcat(c, "/", MAXPATHLEN);
635 if (hlink && *hlink) {
637 strlcpy(buf2, " => ", sizeof buf2);
638 } else if (S_ISLNK(file->mode) && !fname) {
640 strlcpy(buf2, " -> ", sizeof buf2);
645 strlcpy(buf2, " ", sizeof buf2);
647 strlcat(fmt, "s", sizeof fmt);
648 snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
652 n = lp_name(module_id);
655 n = timestring(time(NULL));
658 n = full_module_path;
664 if (!(iflags & ITEM_TRANSFER))
667 b = total_data_written - initial_data_written;
669 b = total_data_read - initial_data_read;
670 strlcat(fmt, "s", sizeof fmt);
671 snprintf(buf2, sizeof buf2, fmt,
672 do_big_num(b, humanize, NULL));
676 if (!(iflags & ITEM_TRANSFER))
679 b = total_data_written - initial_data_written;
681 b = total_data_read - initial_data_read;
682 strlcat(fmt, "s", sizeof fmt);
683 snprintf(buf2, sizeof buf2, fmt,
684 do_big_num(b, humanize, NULL));
688 if (protocol_version >= 30
689 && (iflags & ITEM_TRANSFER
690 || (always_checksum && S_ISREG(file->mode)))) {
692 const char *sum = iflags & ITEM_TRANSFER
693 ? sender_file_sum : F_SUM(file);
694 c = buf2 + checksum_len*2;
696 for (i = checksum_len; --i >= 0; ) {
700 *--c = x1 <= 9 ? x1 + '0' : x1 + 'a' - 10;
701 *--c = x2 <= 9 ? x2 + '0' : x2 + 'a' - 10;
704 memset(buf2, ' ', checksum_len*2);
705 buf2[checksum_len*2] = '\0';
710 if (iflags & ITEM_DELETED) {
714 n = c = buf2 + MAXPATHLEN - 32;
715 c[0] = iflags & ITEM_LOCAL_CHANGE
716 ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
717 : !(iflags & ITEM_TRANSFER) ? '.'
718 : !local_server && *op == 's' ? '<' : '>';
719 if (S_ISLNK(file->mode)) {
722 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
723 : !preserve_times || !receiver_symlink_times
724 || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
726 c[1] = S_ISDIR(file->mode) ? 'd'
727 : IS_SPECIAL(file->mode) ? 'S'
728 : IS_DEVICE(file->mode) ? 'D' : 'f';
729 c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
730 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
731 : !preserve_times ? 'T' : 't';
733 c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
734 c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
735 c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
736 c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
737 c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.' : 'u';
738 c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
739 c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
742 if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
743 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
745 for (i = 2; c[i]; i++)
747 } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
749 for (i = 2; c[i]; i++) {
754 for (i = 2; c[i]; i++)
761 /* "n" is the string to be inserted in place of this % code. */
764 if (n != buf2 && fmt[1]) {
765 strlcat(fmt, "s", sizeof fmt);
766 snprintf(buf2, sizeof buf2, fmt, n);
771 /* Subtract the length of the escape from the string's size. */
774 if (len + total >= (size_t)sizeof buf) {
776 "buffer overflow expanding %%%c -- exiting\n",
778 exit_cleanup(RERR_MESSAGEIO);
781 /* Shuffle the rest of the string along to make space for n */
782 if (len != (size_t)(p - s + 1))
783 memmove(s + len, p + 1, total - (s - buf) + 1);
786 /* Insert the contents of string "n", but NOT its null. */
790 /* Skip over inserted string; continue looking */
794 rwrite(code, buf, total, 0);
797 /* Return 1 if the format escape is in the log-format string (e.g. look for
798 * the 'b' in the "%9b" format escape). */
799 int log_format_has(const char *format, char esc)
806 for (p = format; (p = strchr(p, '%')) != NULL; ) {
807 for (p++; *p == '\''; p++) {}
812 while (*p == '\'') p++;
821 /* Log the transfer of a file. If the code is FCLIENT, the output just goes
822 * to stdout. If it is FLOG, it just goes to the log file. Otherwise we
824 void log_item(enum logcode code, struct file_struct *file, int iflags, const char *hlink)
826 const char *s_or_r = am_sender ? "send" : "recv";
828 if (code != FLOG && stdout_format && !am_server)
829 log_formatted(FCLIENT, stdout_format, s_or_r, file, NULL, iflags, hlink);
830 if (code != FCLIENT && logfile_format && *logfile_format)
831 log_formatted(FLOG, logfile_format, s_or_r, file, NULL, iflags, hlink);
834 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
837 int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
838 int see_item = itemizing && (significant_flags || *buf
839 || stdout_format_has_i > 1 || (INFO_GTE(NAME, 2) && stdout_format_has_i));
840 int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
842 if (logfile_name && !dry_run && see_item
843 && (significant_flags || logfile_format_has_i))
844 log_item(FLOG, file, iflags, buf);
845 } else if (see_item || local_change || *buf
846 || (S_ISDIR(file->mode) && significant_flags)) {
847 enum logcode code = significant_flags || logfile_format_has_i ? FINFO : FCLIENT;
848 log_item(code, file, iflags, buf);
852 void log_delete(const char *fname, int mode)
855 union file_extras ex[4]; /* just in case... */
856 struct file_struct file;
858 int len = strlen(fname);
863 if (!INFO_GTE(DEL, 1) && !stdout_format)
865 else if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
867 len++; /* directories include trailing null */
868 send_msg(MSG_DELETED, fname, len, am_generator);
870 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
871 log_formatted(FCLIENT, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
874 if (!logfile_name || dry_run || !logfile_format)
877 fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
878 log_formatted(FLOG, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
882 * Called when the transfer is interrupted for some reason.
884 * Code is one of the RERR_* codes from errcode.h, or terminating
887 void log_exit(int code, const char *file, int line)
890 rprintf(FLOG,"sent %s bytes received %s bytes total size %s\n",
891 comma_num(stats.total_written),
892 comma_num(stats.total_read),
893 comma_num(stats.total_size));
894 } else if (am_server != 2) {
897 name = rerr_name(code);
899 name = "unexplained error";
901 /* VANISHED is not an error, only a warning */
902 if (code == RERR_VANISHED) {
903 rprintf(FWARNING, "rsync warning: %s (code %d) at %s(%d) [%s=%s]\n",
904 name, code, file, line, who_am_i(), RSYNC_VERSION);
906 rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
907 name, code, file, line, who_am_i(), RSYNC_VERSION);