Debian Codegraph @

log.c

raw symbols SCIP
1 /*
2 * Logging and utility functions.
3 *
4 * Copyright (C) 1998-2001 Andrew Tridgell <[email protected]>
5 * Copyright (C) 2000-2001 Martin Pool <[email protected]>
6 * Copyright (C) 2003-2022 Wayne Davison
7 *
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.
12 *
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.
17 *
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.
20 */
21
22 #include "rsync.h"
23 #include "itypes.h"
24 #include "inums.h"
25 #include "rounding.h" /* EXTRA_ROUNDING, so log_delete() aligns its file_struct */
26
27 extern int dry_run;
28 extern int am_daemon;
29 extern int am_server;
30 extern int am_sender;
31 extern int am_generator;
32 extern int local_server;
33 extern int quiet;
34 extern int module_id;
35 extern int allow_8bit_chars;
36 extern int protocol_version;
37 extern int always_checksum;
38 extern int preserve_mtimes;
39 extern int msgs2stderr;
40 extern int stdout_format_has_i;
41 extern int stdout_format_has_o_or_i;
42 extern int logfile_format_has_i;
43 extern int logfile_format_has_o_or_i;
44 extern int receiver_symlink_times;
45 extern int64 total_data_written;
46 extern int64 total_data_read;
47 extern mode_t orig_umask;
48 extern char *auth_user;
49 extern char *stdout_format;
50 extern char *logfile_format;
51 extern char *logfile_name;
52 #ifdef ICONV_CONST
53 extern iconv_t ic_chck;
54 #endif
55 #ifdef ICONV_OPTION
56 extern iconv_t ic_recv;
57 #endif
58 extern char curr_dir[MAXPATHLEN];
59 extern char *full_module_path;
60 extern unsigned int module_dirlen;
61 extern char sender_file_sum[MAX_DIGEST_LEN];
62 extern const char undetermined_hostname[];
63
64 extern struct name_num_item *xfer_sum_nni, *file_sum_nni;
65
66 static int log_initialised;
67 static int logfile_was_closed;
68 static FILE *logfile_fp;
69 struct stats stats;
70
71 int got_xfer_error = 0;
72 int output_needs_newline = 0;
73 int send_msgs_to_gen = 0;
74
75 static int64 initial_data_written;
76 static int64 initial_data_read;
77
78 struct {
79 int code;
80 char const *name;
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" },
107 { 0, NULL }
108 };
109
110 /*
111 * Map from rsync error code to name, or return NULL.
112 */
113 static char const *rerr_name(int code)
114 {
115 int i;
116 for (i = 0; rerr_names[i].name; i++) {
117 if (rerr_names[i].code == code)
118 return rerr_names[i].name;
119 }
120 return NULL;
121 }
122
123 static void filtered_fwrite(FILE *f, const char *in_buf, int in_len, int use_isprint, int escape_c1, char end_char);
124
125 static void logit(int priority, const char *buf)
126 {
127 if (logfile_was_closed)
128 logfile_reopen();
129 if (logfile_fp) {
130 /* Escape control chars in the message so an attacker-controlled
131 * filename can't inject terminal escapes into the log an admin later
132 * cat's (CWE-117); keep the trailing newline raw via end_char. */
133 int len = strlen(buf);
134 char trailing = len && (buf[len-1] == '\n' || buf[len-1] == '\r') ? buf[--len] : '\0';
135 fprintf(logfile_fp, "%s [%d] ", timestring(time(NULL)), (int)getpid());
136 filtered_fwrite(logfile_fp, buf, len, 0, 1, trailing);
137 fflush(logfile_fp);
138 } else {
139 syslog(priority, "%s", buf);
140 }
141 }
142
143 static void syslog_init()
144 {
145 int options = LOG_PID;
146
147 #ifdef LOG_NDELAY
148 options |= LOG_NDELAY;
149 #endif
150
151 #ifdef LOG_DAEMON
152 openlog(lp_syslog_tag(module_id), options, lp_syslog_facility(module_id));
153 #else
154 openlog(lp_syslog_tag(module_id), options);
155 #endif
156
157 #ifndef LOG_NDELAY
158 logit(LOG_INFO, "rsyncd started\n");
159 #endif
160 }
161
162 static void logfile_open(void)
163 {
164 mode_t old_umask = umask(022 | orig_umask);
165 /* --log-file/`log file =` are operator-supplied paths that may transit
166 * attacker-writable dirs; a planted symlink could redirect root's log
167 * into e.g. /root/.ssh/authorized_keys. Refuse symlinks not owned by
168 * uid 0 or our euid. */
169 int fd = open_no_attacker_symlinks(logfile_name,
170 O_WRONLY | O_APPEND | O_CREAT, 0644);
171 logfile_fp = fd >= 0 ? fdopen(fd, "a") : NULL;
172 if (!logfile_fp && fd >= 0)
173 close(fd);
174 umask(old_umask);
175 if (!logfile_fp) {
176 int fopen_errno = errno;
177 /* Rsync falls back to using syslog on failure. */
178 syslog_init();
179 rsyserr(FERROR, fopen_errno,
180 "failed to open log-file %s", logfile_name);
181 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
182 logfile_name = "";
183 }
184 }
185
186 void log_init(int restart)
187 {
188 if (log_initialised) {
189 if (!restart) /* Note: a restart only happens with am_daemon */
190 return;
191 assert(logfile_name); /* all am_daemon procs got at least an empty string */
192 if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
193 if (logfile_fp) {
194 fclose(logfile_fp);
195 logfile_fp = NULL;
196 } else
197 closelog();
198 logfile_name = NULL;
199 } else if (*logfile_name)
200 return; /* unchanged, non-empty "log file" names */
201 else if (lp_syslog_facility(-1) != lp_syslog_facility(module_id)
202 || strcmp(lp_syslog_tag(-1), lp_syslog_tag(module_id)) != 0)
203 closelog();
204 else
205 return; /* unchanged syslog settings */
206 } else
207 log_initialised = 1;
208
209 /* This looks pointless, but it is needed in order for the
210 * C library on some systems to fetch the timezone info
211 * before the chroot. */
212 timestring(time(NULL));
213
214 /* Optionally use a log file instead of syslog. (Non-daemon
215 * rsyncs will have already set logfile_name, as needed.) */
216 if (am_daemon && !logfile_name)
217 logfile_name = lp_log_file(module_id);
218 if (logfile_name && *logfile_name)
219 logfile_open();
220 else
221 syslog_init();
222 }
223
224 /* Note that this close & reopen idiom intentionally ignores syslog logging. */
225 void logfile_close(void)
226 {
227 if (logfile_fp) {
228 logfile_was_closed = 1;
229 fclose(logfile_fp);
230 logfile_fp = NULL;
231 }
232 }
233
234 void logfile_reopen(void)
235 {
236 if (logfile_was_closed) {
237 logfile_was_closed = 0;
238 logfile_open();
239 }
240 }
241
242 static void filtered_fwrite(FILE *f, const char *in_buf, int in_len, int use_isprint, int escape_c1, char end_char)
243 {
244 char outbuf[1024], *ob = outbuf;
245 const char *end = in_buf + in_len;
246 while (in_buf < end) {
247 if (ob - outbuf >= (int)sizeof outbuf - 10) {
248 if (fwrite(outbuf, ob - outbuf, 1, f) != 1)
249 exit_cleanup(RERR_MESSAGEIO);
250 ob = outbuf;
251 }
252 if ((in_buf < end - 4 && *in_buf == '\\' && in_buf[1] == '#'
253 && isDigit(in_buf + 2) && isDigit(in_buf + 3) && isDigit(in_buf + 4))
254 || (*in_buf != '\t' && ((use_isprint && !isPrint(in_buf)) || *(uchar*)in_buf < ' '
255 || (escape_c1 && *(uchar*)in_buf >= 0x80 && *(uchar*)in_buf <= 0x9f))))
256 ob += snprintf(ob, 6, "\\#%03o", *(uchar*)in_buf++);
257 else
258 *ob++ = *in_buf++;
259 }
260 if (end_char) /* The "- 10" above means that there is always room for one more char here. */
261 *ob++ = end_char;
262 if (ob != outbuf && fwrite(outbuf, ob - outbuf, 1, f) != 1)
263 exit_cleanup(RERR_MESSAGEIO);
264 }
265
266 /* this is the underlying (unformatted) rsync debugging function. Call
267 * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT. Note: recursion
268 * can happen with certain fatal conditions. */
269 void rwrite(enum logcode code, const char *buf, int len, int is_utf8)
270 {
271 char trailing_CR_or_NL;
272 FILE *f = msgs2stderr == 1 ? stderr : stdout;
273 #ifdef ICONV_OPTION
274 iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
275 #else
276 #ifdef ICONV_CONST
277 iconv_t ic = ic_chck;
278 #endif
279 #endif
280
281 if (len < 0)
282 exit_cleanup(RERR_MESSAGEIO);
283
284 if (msgs2stderr == 1) {
285 /* A normal daemon can get msgs2stderr set if the socket is busted, so we
286 * change the message destination into an FLOG message in order to try to
287 * get some info about an abnormal-exit into the log file. An rsh daemon
288 * can have this set via user request, so we'll leave the code alone so
289 * that the msg gets logged and then sent to stderr after that. */
290 if (am_daemon > 0 && code != FCLIENT)
291 code = FLOG;
292 } else if (send_msgs_to_gen) {
293 /* Pass the message to our sibling in native charset. is_utf8
294 * may be set here if a malicious peer sends MSG_INFO/MSG_ERROR
295 * to a daemon receiver (read_a_msg passes !am_generator); the
296 * old assert(!is_utf8) made that a remotely-reachable abort.
297 * Forwarding the bytes raw is safe -- the generator's rwrite()
298 * gets is_utf8=0 and filtered_fwrite escapes non-printables. */
299 send_msg((enum msgcode)code, buf, len, 0);
300 return;
301 }
302
303 if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
304 code = FERROR;
305 else if (code == FERROR_UTF8) {
306 is_utf8 = 1;
307 code = FERROR;
308 }
309
310 if (code == FCLIENT)
311 code = FINFO;
312 else if (am_daemon || logfile_name) {
313 static int in_block;
314 char msg[2048];
315 int priority = code == FINFO || code == FLOG ? LOG_INFO : LOG_WARNING;
316
317 if (in_block)
318 return;
319 in_block = 1;
320 if (!log_initialised)
321 log_init(0);
322 /* buf holds exactly len bytes and is not necessarily NUL-terminated
323 * (e.g. a forwarded MSG_* payload from read_a_msg), so copy by length
324 * rather than strlcpy(), which would strlen() past the end of buf. */
325 int mlen = MIN((int)sizeof msg - 1, len);
326 memcpy(msg, buf, mlen);
327 msg[mlen] = '\0';
328 logit(priority, msg);
329 in_block = 0;
330
331 if (code == FLOG || (am_daemon && !am_server))
332 return;
333 } else if (code == FLOG)
334 return;
335
336 switch (code) {
337 case FERROR_XFER:
338 got_xfer_error = 1;
339 /* FALL THROUGH */
340 case FERROR:
341 case FWARNING:
342 f = stderr;
343 break;
344 case FINFO:
345 if (quiet)
346 return;
347 break;
348 /*case FLOG:*/
349 /*case FCLIENT:*/
350 /*case FERROR_UTF8:*/
351 /*case FERROR_SOCKET:*/
352 default:
353 fprintf(stderr, "Bad logcode in rwrite(): %d [%s]\n", (int)code, who_am_i());
354 exit_cleanup(RERR_MESSAGEIO);
355 }
356
357 if (am_server && msgs2stderr != 1 && (msgs2stderr != 2 || f != stderr)) {
358 enum msgcode msg = (enum msgcode)code;
359 if (protocol_version < 30) {
360 if (msg == MSG_ERROR)
361 msg = MSG_ERROR_XFER;
362 else if (msg == MSG_WARNING)
363 msg = MSG_INFO;
364 }
365 /* Pass the message to the non-server side. */
366 if (send_msg(msg, buf, len, !is_utf8))
367 return;
368 if (am_daemon > 0) {
369 /* TODO: can we send the error to the user somehow? */
370 return;
371 }
372 f = stderr;
373 }
374
375 if (output_needs_newline) {
376 fputc('\n', f);
377 output_needs_newline = 0;
378 }
379
380 trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r') ? buf[--len] : '\0';
381
382 if (len && buf[0] == '\r') {
383 fputc('\r', f);
384 buf++;
385 len--;
386 }
387
388 #ifdef ICONV_CONST
389 if (ic != (iconv_t)-1) {
390 xbuf outbuf, inbuf;
391 char convbuf[1024];
392 int ierrno;
393
394 INIT_CONST_XBUF(outbuf, convbuf);
395 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
396
397 while (inbuf.len) {
398 iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
399 ierrno = errno;
400 if (outbuf.len) {
401 char trailing = inbuf.len ? '\0' : trailing_CR_or_NL;
402 filtered_fwrite(f, convbuf, outbuf.len, 0, 0, trailing);
403 if (trailing) {
404 trailing_CR_or_NL = '\0';
405 fflush(f);
406 }
407 outbuf.len = 0;
408 }
409 /* Log one byte of illegal/incomplete sequence and continue with
410 * the next character. Check that the buffer is non-empty for the
411 * sake of robustness. */
412 if ((ierrno == EILSEQ || ierrno == EINVAL) && inbuf.len) {
413 fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
414 inbuf.len--;
415 }
416 }
417
418 if (trailing_CR_or_NL) {
419 fputc(trailing_CR_or_NL, f);
420 fflush(f);
421 }
422 } else
423 #endif
424 {
425 filtered_fwrite(f, buf, len, !allow_8bit_chars, 0, trailing_CR_or_NL);
426 if (trailing_CR_or_NL)
427 fflush(f);
428 }
429 }
430
431 /* This is the rsync debugging function. Call it with FINFO, FERROR_*,
432 * FWARNING, FLOG, or FCLIENT. */
433 void rprintf(enum logcode code, const char *format, ...)
434 {
435 va_list ap;
436 char buf[BIGPATHBUFLEN];
437 size_t len;
438
439 va_start(ap, format);
440 len = vsnprintf(buf, sizeof buf, format, ap);
441 va_end(ap);
442
443 /* Deal with buffer overruns. Instead of panicking, just
444 * truncate the resulting string. (Note that configure ensures
445 * that we have a vsnprintf() that doesn't ever return -1.) */
446 if (len > sizeof buf - 1) {
447 static const char ellipsis[] = "[...]";
448
449 /* Reset length, and zero-terminate the end of our buffer */
450 len = sizeof buf - 1;
451 buf[len] = '\0';
452
453 /* Copy the ellipsis to the end of the string, but give
454 * us one extra character:
455 *
456 * v--- null byte at buf[sizeof buf - 1]
457 * abcdefghij0
458 * -> abcd[...]00 <-- now two null bytes at end
459 *
460 * If the input format string has a trailing newline,
461 * we copy it into that extra null; if it doesn't, well,
462 * all we lose is one byte. */
463 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
464 if (format[strlen(format)-1] == '\n') {
465 buf[len-1] = '\n';
466 }
467 }
468
469 rwrite(code, buf, len, 0);
470 }
471
472 /* This is like rprintf, but it also tries to print some
473 * representation of the error code. Normally errcode = errno.
474 *
475 * Unlike rprintf, this always adds a newline and there should not be
476 * one in the format string.
477 *
478 * Note that since strerror might involve dynamically loading a
479 * message catalog we need to call it once before chroot-ing. */
480 void rsyserr(enum logcode code, int errcode, const char *format, ...)
481 {
482 va_list ap;
483 char buf[BIGPATHBUFLEN];
484 size_t len;
485
486 /* snprintf returns the would-have-been length on truncation, so
487 * each cumulative call must be guarded; if not, sizeof buf - len
488 * can underflow when promoted to size_t and the next call writes
489 * past the buffer. */
490 len = snprintf(buf, sizeof buf, RSYNC_NAME ": [%s] ", who_am_i());
491
492 if (len < sizeof buf) {
493 va_start(ap, format);
494 len += vsnprintf(buf + len, sizeof buf - len, format, ap);
495 va_end(ap);
496 }
497
498 if (len < sizeof buf) {
499 len += snprintf(buf + len, sizeof buf - len,
500 ": %s (%d)\n", strerror(errcode), errcode);
501 }
502 if (len >= sizeof buf)
503 exit_cleanup(RERR_MESSAGEIO);
504
505 rwrite(code, buf, len, 0);
506 }
507
508 void rflush(enum logcode code)
509 {
510 FILE *f;
511
512 if (am_daemon || code == FLOG)
513 return;
514
515 if (!am_server && (code == FINFO || code == FCLIENT))
516 f = stdout;
517 else
518 f = stderr;
519
520 fflush(f);
521 }
522
523 void remember_initial_stats(void)
524 {
525 initial_data_read = total_data_read;
526 initial_data_written = total_data_written;
527 }
528
529 /* Size of log_formatted()'s per-escape "fmt" scratch buffer. log_format_has()
530 * must bound its width-digit scan to the same limit so the two parsers agree on
531 * where an escape letter falls (see the digit loop in each). */
532 #define LOG_FMT_SIZE 32
533
534 /* A generic logging routine for send/recv, with parameter substitiution. */
535 static void log_formatted(enum logcode code, const char *format, const char *op,
536 struct file_struct *file, const char *fname, int iflags,
537 const char *hlink)
538 {
539 char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[LOG_FMT_SIZE];
540 char *p, *s, *c;
541 const char *n;
542 size_t len, total;
543 int64 b;
544
545 *fmt = '%';
546
547 /* We expand % codes one by one in place in buf. We don't
548 * copy in the terminating null of the inserted strings, but
549 * rather keep going until we reach the null of the format. */
550 total = strlcpy(buf, format, sizeof buf);
551 if (total > MAXPATHLEN) {
552 rprintf(FERROR, "log-format string is WAY too long!\n");
553 exit_cleanup(RERR_MESSAGEIO);
554 }
555 buf[total++] = '\n';
556 buf[total] = '\0';
557
558 for (p = buf; (p = strchr(p, '%')) != NULL; ) {
559 int humanize = 0;
560 s = p++;
561 c = fmt + 1;
562 while (*p == '\'') {
563 humanize++;
564 p++;
565 }
566 if (*p == '-')
567 *c++ = *p++;
568 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
569 *c++ = *p++;
570 while (*p == '\'') {
571 humanize++;
572 p++;
573 }
574 if (!*p)
575 break;
576 *c = '\0';
577 n = NULL;
578
579 /* Note for %h and %a: it doesn't matter what fd we pass to
580 * client_{name,addr} because rsync_module will already have
581 * forced the answer to be cached (assuming, of course, for %h
582 * that lp_reverse_lookup(module_id) is true). */
583 switch (*p) {
584 case 'h':
585 if (am_daemon) {
586 n = lp_reverse_lookup(module_id)
587 ? client_name(0) : undetermined_hostname;
588 }
589 break;
590 case 'a':
591 if (am_daemon)
592 n = client_addr(0);
593 break;
594 case 'l':
595 strlcat(fmt, "s", sizeof fmt);
596 snprintf(buf2, sizeof buf2, fmt,
597 do_big_num(F_LENGTH(file), humanize, NULL));
598 n = buf2;
599 break;
600 case 'U':
601 strlcat(fmt, "u", sizeof fmt);
602 snprintf(buf2, sizeof buf2, fmt,
603 uid_ndx ? F_OWNER(file) : 0);
604 n = buf2;
605 break;
606 case 'G':
607 if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
608 n = "DEFAULT";
609 else {
610 strlcat(fmt, "u", sizeof fmt);
611 snprintf(buf2, sizeof buf2, fmt,
612 F_GROUP(file));
613 n = buf2;
614 }
615 break;
616 case 'p':
617 strlcat(fmt, "d", sizeof fmt);
618 snprintf(buf2, sizeof buf2, fmt, (int)getpid());
619 n = buf2;
620 break;
621 case 'M':
622 n = c = timestring(file->modtime);
623 while ((c = strchr(c, ' ')) != NULL)
624 *c = '-';
625 break;
626 case 'B':
627 c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
628 permstring(c, file->mode);
629 n = c + 1; /* skip the type char */
630 break;
631 case 'o':
632 n = op;
633 break;
634 case 'f':
635 if (fname) {
636 c = f_name_buf();
637 strlcpy(c, fname, MAXPATHLEN);
638 } else
639 c = f_name(file, NULL);
640 if (am_sender && F_PATHNAME(file)) {
641 pathjoin(buf2, sizeof buf2,
642 F_PATHNAME(file), c);
643 clean_fname(buf2, 0);
644 if (fmt[1]) {
645 strlcpy(c, buf2, MAXPATHLEN);
646 n = c;
647 } else
648 n = buf2;
649 } else if (am_daemon && *c != '/') {
650 pathjoin(buf2, sizeof buf2,
651 curr_dir + module_dirlen, c);
652 clean_fname(buf2, 0);
653 if (fmt[1]) {
654 strlcpy(c, buf2, MAXPATHLEN);
655 n = c;
656 } else
657 n = buf2;
658 } else {
659 clean_fname(c, 0);
660 n = c;
661 }
662 if (*n == '/')
663 n++;
664 break;
665 case 'n':
666 if (fname) {
667 c = f_name_buf();
668 strlcpy(c, fname, MAXPATHLEN);
669 } else
670 c = f_name(file, NULL);
671 if (S_ISDIR(file->mode))
672 strlcat(c, "/", MAXPATHLEN);
673 n = c;
674 break;
675 case 'L':
676 if (hlink && *hlink) {
677 n = hlink;
678 strlcpy(buf2, " => ", sizeof buf2);
679 } else if (S_ISLNK(file->mode) && !fname) {
680 n = F_SYMLINK(file);
681 strlcpy(buf2, " -> ", sizeof buf2);
682 } else {
683 n = "";
684 if (!fmt[1])
685 break;
686 strlcpy(buf2, " ", sizeof buf2);
687 }
688 strlcat(fmt, "s", sizeof fmt);
689 snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
690 n = buf2;
691 break;
692 case 'm':
693 n = lp_name(module_id);
694 break;
695 case 't':
696 n = timestring(time(NULL));
697 break;
698 case 'P':
699 n = full_module_path;
700 break;
701 case 'u':
702 n = auth_user;
703 break;
704 case 'b':
705 case 'c':
706 if (!(iflags & ITEM_TRANSFER))
707 b = 0;
708 else if ((!!am_sender) ^ (*p == 'c'))
709 b = total_data_written - initial_data_written;
710 else
711 b = total_data_read - initial_data_read;
712 strlcat(fmt, "s", sizeof fmt);
713 snprintf(buf2, sizeof buf2, fmt,
714 do_big_num(b, humanize, NULL));
715 n = buf2;
716 break;
717 case 'C':
718 n = NULL;
719 if (S_ISREG(file->mode)) {
720 if (always_checksum && !(iflags & ITEM_DELETED))
721 n = sum_as_hex(file_sum_nni->num, F_SUM(file), 1);
722 else if (iflags & ITEM_TRANSFER)
723 n = sum_as_hex(xfer_sum_nni->num, sender_file_sum, 0);
724 }
725 if (!n) {
726 int sum_len = csum_len_for_type(always_checksum ? file_sum_nni->num : xfer_sum_nni->num,
727 always_checksum);
728 memset(buf2, ' ', sum_len*2);
729 buf2[sum_len*2] = '\0';
730 n = buf2;
731 }
732 break;
733 case 'i':
734 if (iflags & ITEM_DELETED) {
735 n = "*deleting ";
736 break;
737 }
738 n = c = buf2 + MAXPATHLEN - 32;
739 c[0] = iflags & ITEM_LOCAL_CHANGE
740 ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
741 : !(iflags & ITEM_TRANSFER) ? '.'
742 : !local_server && *op == 's' ? '<' : '>';
743 if (S_ISLNK(file->mode)) {
744 c[1] = 'L';
745 c[3] = '.';
746 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
747 : !preserve_mtimes || !receiver_symlink_times
748 || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
749 } else {
750 c[1] = S_ISDIR(file->mode) ? 'd'
751 : IS_SPECIAL(file->mode) ? 'S'
752 : IS_DEVICE(file->mode) ? 'D' : 'f';
753 c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
754 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
755 : !preserve_mtimes ? 'T' : 't';
756 }
757 c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
758 c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
759 c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
760 c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
761 c[8] = !(iflags & (ITEM_REPORT_ATIME|ITEM_REPORT_CRTIME)) ? '.'
762 : BITS_SET(iflags, ITEM_REPORT_ATIME|ITEM_REPORT_CRTIME) ? 'b'
763 : iflags & ITEM_REPORT_ATIME ? 'u' : 'n';
764 c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
765 c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
766 c[11] = '\0';
767
768 if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
769 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
770 int i;
771 for (i = 2; c[i]; i++)
772 c[i] = ch;
773 } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
774 int i;
775 for (i = 2; c[i]; i++) {
776 if (c[i] != '.')
777 break;
778 }
779 if (!c[i]) {
780 for (i = 2; c[i]; i++)
781 c[i] = ' ';
782 }
783 }
784 break;
785 case '%':
786 n = "%";
787 break;
788 }
789
790 /* "n" is the string to be inserted in place of this % code. */
791 if (!n)
792 continue;
793 if (n != buf2 && fmt[1]) {
794 strlcat(fmt, "s", sizeof fmt);
795 snprintf(buf2, sizeof buf2, fmt, n);
796 n = buf2;
797 }
798 len = strlen(n);
799
800 /* Subtract the length of the escape from the string's size. */
801 total -= p - s + 1;
802
803 if (len + total >= (size_t)sizeof buf) {
804 rprintf(FERROR,
805 "buffer overflow expanding %%%c -- exiting\n",
806 p[0]);
807 exit_cleanup(RERR_MESSAGEIO);
808 }
809
810 /* Shuffle the rest of the string along to make space for n */
811 if (len != (size_t)(p - s + 1))
812 memmove(s + len, p + 1, total - (s - buf) + 1);
813 total += len;
814
815 /* Insert the contents of string "n", but NOT its null. */
816 if (len)
817 memcpy(s, n, len);
818
819 /* Skip over inserted string; continue looking */
820 p = s + len;
821 }
822
823 rwrite(code, buf, total, 0);
824 }
825
826 /* Return 1 if the format escape is in the log-format string (e.g. look for
827 * the 'b' in the "%9b" format escape). */
828 int log_format_has(const char *format, char esc)
829 {
830 const char *p;
831 int width;
832
833 if (!format)
834 return 0;
835
836 for (p = format; (p = strchr(p, '%')) != NULL; ) {
837 for (p++; *p == '\''; p++) {} /*SHARED ITERATOR*/
838 /* Mirror log_formatted()'s width-digit scan exactly (c starts at
839 * fmt+1, so width starts at 1): both must stop at the same digit
840 * or they disagree on where the escape letter is, which for %C
841 * can leave sender_keeps_checksum unset and over-read F_SUM. */
842 width = 1;
843 if (*p == '-') {
844 p++;
845 width++;
846 }
847 while (isDigit(p) && width < LOG_FMT_SIZE - 8) {
848 p++;
849 width++;
850 }
851 while (*p == '\'') p++;
852 if (!*p)
853 break;
854 if (*p == esc)
855 return 1;
856 if (*p == '%') /* %% is a literal '%', not the start of an escape */
857 p++;
858 }
859 return 0;
860 }
861
862 /* Log the transfer of a file. If the code is FCLIENT, the output just goes
863 * to stdout. If it is FLOG, it just goes to the log file. Otherwise we
864 * output to both. */
865 void log_item(enum logcode code, struct file_struct *file, int iflags, const char *hlink)
866 {
867 const char *s_or_r = am_sender ? "send" : "recv";
868
869 if (code != FLOG && stdout_format && !am_server)
870 log_formatted(FCLIENT, stdout_format, s_or_r, file, NULL, iflags, hlink);
871 if (code != FCLIENT && logfile_format && *logfile_format)
872 log_formatted(FLOG, logfile_format, s_or_r, file, NULL, iflags, hlink);
873 }
874
875 void maybe_log_item(struct file_struct *file, int iflags, int itemizing, const char *buf)
876 {
877 int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
878 int see_item = itemizing && (significant_flags || *buf
879 || stdout_format_has_i > 1 || (INFO_GTE(NAME, 2) && stdout_format_has_i));
880 int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
881 if (am_server) {
882 if (logfile_name && !dry_run && see_item
883 && (significant_flags || logfile_format_has_i))
884 log_item(FLOG, file, iflags, buf);
885 } else if (see_item || local_change || *buf
886 || (S_ISDIR(file->mode) && significant_flags)) {
887 enum logcode code = significant_flags || logfile_format_has_i ? FINFO : FCLIENT;
888 log_item(code, file, iflags, buf);
889 }
890 }
891
892 void log_delete(const char *fname, int mode)
893 {
894 static struct file_struct *file = NULL;
895 int len = strlen(fname);
896 const char *fmt;
897
898 if (!file) {
899 int extra_len = (file_extra_cnt + 2) * EXTRA_LEN;
900 char *bp;
901 #if EXTRA_ROUNDING > 0
902 if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
903 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
904 #endif
905
906 bp = new_array0(char, FILE_STRUCT_LEN + extra_len + 1);
907 bp += extra_len;
908 file = (struct file_struct *)bp;
909 }
910
911 file->mode = mode;
912
913 if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
914 if (S_ISDIR(mode))
915 len++; /* directories include trailing null */
916 send_msg(MSG_DELETED, fname, len, am_generator);
917 } else if (!INFO_GTE(DEL, 1) && !stdout_format)
918 ;
919 else {
920 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
921 log_formatted(FCLIENT, fmt, "del.", file, fname, ITEM_DELETED, NULL);
922 }
923
924 if (!logfile_name || dry_run || !logfile_format)
925 return;
926
927 fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
928 log_formatted(FLOG, fmt, "del.", file, fname, ITEM_DELETED, NULL);
929 }
930
931 /*
932 * Called when the transfer is interrupted for some reason.
933 *
934 * Code is one of the RERR_* codes from errcode.h, or terminating
935 * successfully.
936 */
937 void log_exit(int code, const char *file, int line)
938 {
939 /* The receiving side's stats are split between 2 procs until the
940 * end of the run, so only the sender can output non-final info. */
941 if (code == 0 || am_sender) {
942 rprintf(FLOG,"sent %s bytes received %s bytes total size %s\n",
943 big_num(stats.total_written),
944 big_num(stats.total_read),
945 big_num(stats.total_size));
946 }
947 if (code != 0 && am_server != 2) {
948 const char *name;
949
950 name = rerr_name(code);
951 if (!name)
952 name = "unexplained error";
953
954 /* VANISHED is not an error, only a warning */
955 if (code == RERR_VANISHED) {
956 rprintf(FWARNING, "rsync warning: %s (code %d) at %s(%d) [%s=%s]\n",
957 name, code, src_file(file), line, who_am_i(), rsync_version());
958 } else {
959 rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
960 name, code, src_file(file), line, who_am_i(), rsync_version());
961 }
962 }
963 }