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-2015 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 allow_8bit_chars;
35 extern int protocol_version;
36 extern int always_checksum;
37 extern int preserve_times;
38 extern int msgs2stderr;
39 extern int xfersum_type;
40 extern int checksum_type;
41 extern int stdout_format_has_i;
42 extern int stdout_format_has_o_or_i;
43 extern int logfile_format_has_i;
44 extern int logfile_format_has_o_or_i;
45 extern int receiver_symlink_times;
46 extern int64 total_data_written;
47 extern int64 total_data_read;
48 extern mode_t orig_umask;
49 extern char *auth_user;
50 extern char *checksum_choice;
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_CMD_FAILED , "remote shell failed" },
104 { RERR_CMD_KILLED , "remote shell killed" },
105 { RERR_CMD_RUN , "remote command could not be run" },
106 { RERR_CMD_NOTFOUND,"remote command not found" },
111 * Map from rsync error code to name, or return NULL.
113 static char const *rerr_name(int code)
116 for (i = 0; rerr_names[i].name; i++) {
117 if (rerr_names[i].code == code)
118 return rerr_names[i].name;
123 static void logit(int priority, const char *buf)
125 if (logfile_was_closed)
128 fprintf(logfile_fp, "%s [%d] %s", timestring(time(NULL)), (int)getpid(), buf);
131 syslog(priority, "%s", buf);
135 static void syslog_init()
137 static int been_here = 0;
138 int options = LOG_PID;
145 options |= LOG_NDELAY;
149 openlog("rsyncd", options, lp_syslog_facility(module_id));
151 openlog("rsyncd", options);
155 logit(LOG_INFO, "rsyncd started\n");
159 static void logfile_open(void)
161 mode_t old_umask = umask(022 | orig_umask);
162 logfile_fp = fopen(logfile_name, "a");
165 int fopen_errno = errno;
166 /* Rsync falls back to using syslog on failure. */
168 rsyserr(FERROR, fopen_errno,
169 "failed to open log-file %s", logfile_name);
170 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
174 void log_init(int restart)
176 if (log_initialised) {
179 if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
186 } else if (*logfile_name)
187 return; /* unchanged, non-empty "log file" names */
188 else if (lp_syslog_facility(-1) != lp_syslog_facility(module_id))
191 return; /* unchanged syslog settings */
195 /* This looks pointless, but it is needed in order for the
196 * C library on some systems to fetch the timezone info
197 * before the chroot. */
198 timestring(time(NULL));
200 /* Optionally use a log file instead of syslog. (Non-daemon
201 * rsyncs will have already set logfile_name, as needed.) */
202 if (am_daemon && !logfile_name)
203 logfile_name = lp_log_file(module_id);
204 if (logfile_name && *logfile_name)
210 void logfile_close(void)
213 logfile_was_closed = 1;
219 void logfile_reopen(void)
221 if (logfile_was_closed) {
222 logfile_was_closed = 0;
227 static void filtered_fwrite(FILE *f, const char *buf, int len, int use_isprint)
229 const char *s, *end = buf + len;
230 for (s = buf; s < end; s++) {
232 && *s == '\\' && s[1] == '#'
237 && ((use_isprint && !isPrint(s))
238 || *(uchar*)s < ' '))) {
239 if (s != buf && fwrite(buf, s - buf, 1, f) != 1)
240 exit_cleanup(RERR_MESSAGEIO);
241 fprintf(f, "\\#%03o", *(uchar*)s);
245 if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
246 exit_cleanup(RERR_MESSAGEIO);
249 /* this is the underlying (unformatted) rsync debugging function. Call
250 * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT. Note: recursion
251 * can happen with certain fatal conditions. */
252 void rwrite(enum logcode code, const char *buf, int len, int is_utf8)
254 int trailing_CR_or_NL;
255 FILE *f = msgs2stderr ? stderr : stdout;
257 iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
260 iconv_t ic = ic_chck;
265 exit_cleanup(RERR_MESSAGEIO);
276 } else if (send_msgs_to_gen) {
278 /* Pass the message to our sibling in native charset. */
279 send_msg((enum msgcode)code, buf, len, 0);
283 if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
285 else if (code == FERROR_UTF8) {
292 else if (am_daemon || logfile_name) {
295 int priority = code == FINFO || code == FLOG ? LOG_INFO : LOG_WARNING;
300 if (!log_initialised)
302 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
303 logit(priority, msg);
306 if (code == FLOG || (am_daemon && !am_server))
308 } else if (code == FLOG)
311 if (quiet && code == FINFO)
315 enum msgcode msg = (enum msgcode)code;
316 if (protocol_version < 30) {
317 if (msg == MSG_ERROR)
318 msg = MSG_ERROR_XFER;
319 else if (msg == MSG_WARNING)
322 /* Pass the message to the non-server side. */
323 if (send_msg(msg, buf, len, !is_utf8))
326 /* TODO: can we send the error to the user somehow? */
348 fprintf(stderr, "Unknown logcode in rwrite(): %d [%s]\n", (int)code, who_am_i());
349 exit_cleanup(RERR_MESSAGEIO);
352 if (output_needs_newline) {
354 output_needs_newline = 0;
357 trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
360 if (len && buf[0] == '\r') {
367 if (ic != (iconv_t)-1) {
372 INIT_CONST_XBUF(outbuf, convbuf);
373 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
376 iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
379 filtered_fwrite(f, convbuf, outbuf.len, 0);
382 if (!ierrno || ierrno == E2BIG)
384 fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
389 filtered_fwrite(f, buf, len, !allow_8bit_chars);
391 if (trailing_CR_or_NL) {
392 fputc(trailing_CR_or_NL, f);
397 /* This is the rsync debugging function. Call it with FINFO, FERROR_*,
398 * FWARNING, FLOG, or FCLIENT. */
399 void rprintf(enum logcode code, const char *format, ...)
402 char buf[BIGPATHBUFLEN];
405 va_start(ap, format);
406 len = vsnprintf(buf, sizeof buf, format, ap);
409 /* Deal with buffer overruns. Instead of panicking, just
410 * truncate the resulting string. (Note that configure ensures
411 * that we have a vsnprintf() that doesn't ever return -1.) */
412 if (len > sizeof buf - 1) {
413 static const char ellipsis[] = "[...]";
415 /* Reset length, and zero-terminate the end of our buffer */
416 len = sizeof buf - 1;
419 /* Copy the ellipsis to the end of the string, but give
420 * us one extra character:
422 * v--- null byte at buf[sizeof buf - 1]
424 * -> abcd[...]00 <-- now two null bytes at end
426 * If the input format string has a trailing newline,
427 * we copy it into that extra null; if it doesn't, well,
428 * all we lose is one byte. */
429 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
430 if (format[strlen(format)-1] == '\n') {
435 rwrite(code, buf, len, 0);
438 /* This is like rprintf, but it also tries to print some
439 * representation of the error code. Normally errcode = errno.
441 * Unlike rprintf, this always adds a newline and there should not be
442 * one in the format string.
444 * Note that since strerror might involve dynamically loading a
445 * message catalog we need to call it once before chroot-ing. */
446 void rsyserr(enum logcode code, int errcode, const char *format, ...)
449 char buf[BIGPATHBUFLEN];
452 strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
453 len = (sizeof RSYNC_NAME ": ") - 1;
455 va_start(ap, format);
456 len += vsnprintf(buf + len, sizeof buf - len, format, ap);
459 if (len < sizeof buf) {
460 len += snprintf(buf + len, sizeof buf - len,
461 ": %s (%d)\n", strerror(errcode), errcode);
463 if (len >= sizeof buf)
464 exit_cleanup(RERR_MESSAGEIO);
466 rwrite(code, buf, len, 0);
469 void rflush(enum logcode code)
473 if (am_daemon || code == FLOG)
476 if (!am_server && (code == FINFO || code == FCLIENT))
484 void remember_initial_stats(void)
486 initial_data_read = total_data_read;
487 initial_data_written = total_data_written;
490 /* A generic logging routine for send/recv, with parameter substitiution. */
491 static void log_formatted(enum logcode code, const char *format, const char *op,
492 struct file_struct *file, const char *fname, int iflags,
495 char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
503 /* We expand % codes one by one in place in buf. We don't
504 * copy in the terminating null of the inserted strings, but
505 * rather keep going until we reach the null of the format. */
506 total = strlcpy(buf, format, sizeof buf);
507 if (total > MAXPATHLEN) {
508 rprintf(FERROR, "log-format string is WAY too long!\n");
509 exit_cleanup(RERR_MESSAGEIO);
514 for (p = buf; (p = strchr(p, '%')) != NULL; ) {
524 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
535 /* Note for %h and %a: it doesn't matter what fd we pass to
536 * client_{name,addr} because rsync_module will already have
537 * forced the answer to be cached (assuming, of course, for %h
538 * that lp_reverse_lookup(module_id) is true). */
542 n = lp_reverse_lookup(module_id)
543 ? client_name(0) : undetermined_hostname;
551 strlcat(fmt, "s", sizeof fmt);
552 snprintf(buf2, sizeof buf2, fmt,
553 do_big_num(F_LENGTH(file), humanize, NULL));
557 strlcat(fmt, "u", sizeof fmt);
558 snprintf(buf2, sizeof buf2, fmt,
559 uid_ndx ? F_OWNER(file) : 0);
563 if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
566 strlcat(fmt, "u", sizeof fmt);
567 snprintf(buf2, sizeof buf2, fmt,
573 strlcat(fmt, "d", sizeof fmt);
574 snprintf(buf2, sizeof buf2, fmt, (int)getpid());
578 n = c = timestring(file->modtime);
579 while ((c = strchr(c, ' ')) != NULL)
583 c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
584 permstring(c, file->mode);
585 n = c + 1; /* skip the type char */
593 strlcpy(c, fname, MAXPATHLEN);
595 c = f_name(file, NULL);
596 if (am_sender && F_PATHNAME(file)) {
597 pathjoin(buf2, sizeof buf2,
598 F_PATHNAME(file), c);
599 clean_fname(buf2, 0);
601 strlcpy(c, buf2, MAXPATHLEN);
605 } else if (am_daemon && *c != '/') {
606 pathjoin(buf2, sizeof buf2,
607 curr_dir + module_dirlen, c);
608 clean_fname(buf2, 0);
610 strlcpy(c, buf2, MAXPATHLEN);
624 strlcpy(c, fname, MAXPATHLEN);
626 c = f_name(file, NULL);
627 if (S_ISDIR(file->mode))
628 strlcat(c, "/", MAXPATHLEN);
632 if (hlink && *hlink) {
634 strlcpy(buf2, " => ", sizeof buf2);
635 } else if (S_ISLNK(file->mode) && !fname) {
637 strlcpy(buf2, " -> ", sizeof buf2);
642 strlcpy(buf2, " ", sizeof buf2);
644 strlcat(fmt, "s", sizeof fmt);
645 snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
649 n = lp_name(module_id);
652 n = timestring(time(NULL));
655 n = full_module_path;
662 if (!(iflags & ITEM_TRANSFER))
664 else if ((!!am_sender) ^ (*p == 'c'))
665 b = total_data_written - initial_data_written;
667 b = total_data_read - initial_data_read;
668 strlcat(fmt, "s", sizeof fmt);
669 snprintf(buf2, sizeof buf2, fmt,
670 do_big_num(b, humanize, NULL));
675 if (S_ISREG(file->mode)) {
676 if (always_checksum && canonical_checksum(checksum_type))
677 n = sum_as_hex(checksum_type, F_SUM(file));
678 else if (iflags & ITEM_TRANSFER && canonical_checksum(xfersum_type))
679 n = sum_as_hex(xfersum_type, sender_file_sum);
682 int checksum_len = csum_len_for_type(always_checksum ? checksum_type : xfersum_type);
683 memset(buf2, ' ', checksum_len*2);
684 buf2[checksum_len*2] = '\0';
689 if (iflags & ITEM_DELETED) {
693 n = c = buf2 + MAXPATHLEN - 32;
694 c[0] = iflags & ITEM_LOCAL_CHANGE
695 ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
696 : !(iflags & ITEM_TRANSFER) ? '.'
697 : !local_server && *op == 's' ? '<' : '>';
698 if (S_ISLNK(file->mode)) {
701 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
702 : !preserve_times || !receiver_symlink_times
703 || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
705 c[1] = S_ISDIR(file->mode) ? 'd'
706 : IS_SPECIAL(file->mode) ? 'S'
707 : IS_DEVICE(file->mode) ? 'D' : 'f';
708 c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
709 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
710 : !preserve_times ? 'T' : 't';
712 c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
713 c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
714 c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
715 c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
716 c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.' : 'u';
717 c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
718 c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
721 if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
722 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
724 for (i = 2; c[i]; i++)
726 } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
728 for (i = 2; c[i]; i++) {
733 for (i = 2; c[i]; i++)
740 /* "n" is the string to be inserted in place of this % code. */
743 if (n != buf2 && fmt[1]) {
744 strlcat(fmt, "s", sizeof fmt);
745 snprintf(buf2, sizeof buf2, fmt, n);
750 /* Subtract the length of the escape from the string's size. */
753 if (len + total >= (size_t)sizeof buf) {
755 "buffer overflow expanding %%%c -- exiting\n",
757 exit_cleanup(RERR_MESSAGEIO);
760 /* Shuffle the rest of the string along to make space for n */
761 if (len != (size_t)(p - s + 1))
762 memmove(s + len, p + 1, total - (s - buf) + 1);
765 /* Insert the contents of string "n", but NOT its null. */
769 /* Skip over inserted string; continue looking */
773 rwrite(code, buf, total, 0);
776 /* Return 1 if the format escape is in the log-format string (e.g. look for
777 * the 'b' in the "%9b" format escape). */
778 int log_format_has(const char *format, char esc)
785 for (p = format; (p = strchr(p, '%')) != NULL; ) {
786 for (p++; *p == '\''; p++) {} /*SHARED ITERATOR*/
791 while (*p == '\'') p++;
800 /* Log the transfer of a file. If the code is FCLIENT, the output just goes
801 * to stdout. If it is FLOG, it just goes to the log file. Otherwise we
803 void log_item(enum logcode code, struct file_struct *file, int iflags, const char *hlink)
805 const char *s_or_r = am_sender ? "send" : "recv";
807 if (code != FLOG && stdout_format && !am_server)
808 log_formatted(FCLIENT, stdout_format, s_or_r, file, NULL, iflags, hlink);
809 if (code != FCLIENT && logfile_format && *logfile_format)
810 log_formatted(FLOG, logfile_format, s_or_r, file, NULL, iflags, hlink);
813 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
816 int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
817 int see_item = itemizing && (significant_flags || *buf
818 || stdout_format_has_i > 1 || (INFO_GTE(NAME, 2) && stdout_format_has_i));
819 int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
821 if (logfile_name && !dry_run && see_item
822 && (significant_flags || logfile_format_has_i))
823 log_item(FLOG, file, iflags, buf);
824 } else if (see_item || local_change || *buf
825 || (S_ISDIR(file->mode) && significant_flags)) {
826 enum logcode code = significant_flags || logfile_format_has_i ? FINFO : FCLIENT;
827 log_item(code, file, iflags, buf);
831 void log_delete(const char *fname, int mode)
834 union file_extras ex[4]; /* just in case... */
835 struct file_struct file;
836 } x; /* Zero-initialized due to static declaration. */
837 int len = strlen(fname);
842 if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
844 len++; /* directories include trailing null */
845 send_msg(MSG_DELETED, fname, len, am_generator);
846 } else if (!INFO_GTE(DEL, 1) && !stdout_format)
849 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
850 log_formatted(FCLIENT, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
853 if (!logfile_name || dry_run || !logfile_format)
856 fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
857 log_formatted(FLOG, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
861 * Called when the transfer is interrupted for some reason.
863 * Code is one of the RERR_* codes from errcode.h, or terminating
866 void log_exit(int code, const char *file, int line)
869 rprintf(FLOG,"sent %s bytes received %s bytes total size %s\n",
870 big_num(stats.total_written),
871 big_num(stats.total_read),
872 big_num(stats.total_size));
873 } else if (am_server != 2) {
876 name = rerr_name(code);
878 name = "unexplained error";
880 /* VANISHED is not an error, only a warning */
881 if (code == RERR_VANISHED) {
882 rprintf(FWARNING, "rsync warning: %s (code %d) at %s(%d) [%s=%s]\n",
883 name, code, file, line, who_am_i(), RSYNC_VERSION);
885 rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
886 name, code, file, line, who_am_i(), RSYNC_VERSION);