Added --atimes and --set-noatime options.
[rsync.git] / log.c
1 /*
2  * Logging and utility functions.
3  *
4  * Copyright (C) 1998-2001 Andrew Tridgell <tridge@samba.org>
5  * Copyright (C) 2000-2001 Martin Pool <mbp@samba.org>
6  * Copyright (C) 2003-2020 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
26 extern int dry_run;
27 extern int am_daemon;
28 extern int am_server;
29 extern int am_sender;
30 extern int am_generator;
31 extern int local_server;
32 extern int quiet;
33 extern int module_id;
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;
54 #ifdef ICONV_CONST
55 extern iconv_t ic_chck;
56 #endif
57 #ifdef ICONV_OPTION
58 extern iconv_t ic_recv;
59 #endif
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[];
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 logit(int priority, const char *buf)
124 {
125         if (logfile_was_closed)
126                 logfile_reopen();
127         if (logfile_fp) {
128                 fprintf(logfile_fp, "%s [%d] %s", timestring(time(NULL)), (int)getpid(), buf);
129                 fflush(logfile_fp);
130         } else {
131                 syslog(priority, "%s", buf);
132         }
133 }
134
135 static void syslog_init()
136 {
137         int options = LOG_PID;
138
139 #ifdef LOG_NDELAY
140         options |= LOG_NDELAY;
141 #endif
142
143 #ifdef LOG_DAEMON
144         openlog(lp_syslog_tag(module_id), options, lp_syslog_facility(module_id));
145 #else
146         openlog(lp_syslog_tag(module_id), options);
147 #endif
148
149 #ifndef LOG_NDELAY
150         logit(LOG_INFO, "rsyncd started\n");
151 #endif
152 }
153
154 static void logfile_open(void)
155 {
156         mode_t old_umask = umask(022 | orig_umask);
157         logfile_fp = fopen(logfile_name, "a");
158         umask(old_umask);
159         if (!logfile_fp) {
160                 int fopen_errno = errno;
161                 /* Rsync falls back to using syslog on failure. */
162                 syslog_init();
163                 rsyserr(FERROR, fopen_errno,
164                         "failed to open log-file %s", logfile_name);
165                 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
166                 logfile_name = "";
167         }
168 }
169
170 void log_init(int restart)
171 {
172         if (log_initialised) {
173                 if (!restart) /* Note: a restart only happens with am_daemon */
174                         return;
175                 assert(logfile_name); /* all am_daemon procs got at least an empty string */
176                 if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
177                         if (logfile_fp) {
178                                 fclose(logfile_fp);
179                                 logfile_fp = NULL;
180                         } else
181                                 closelog();
182                         logfile_name = NULL;
183                 } else if (*logfile_name)
184                         return; /* unchanged, non-empty "log file" names */
185                 else if (lp_syslog_facility(-1) != lp_syslog_facility(module_id)
186                       || strcmp(lp_syslog_tag(-1), lp_syslog_tag(module_id)) != 0)
187                         closelog();
188                 else
189                         return; /* unchanged syslog settings */
190         } else
191                 log_initialised = 1;
192
193         /* This looks pointless, but it is needed in order for the
194          * C library on some systems to fetch the timezone info
195          * before the chroot. */
196         timestring(time(NULL));
197
198         /* Optionally use a log file instead of syslog.  (Non-daemon
199          * rsyncs will have already set logfile_name, as needed.) */
200         if (am_daemon && !logfile_name)
201                 logfile_name = lp_log_file(module_id);
202         if (logfile_name && *logfile_name)
203                 logfile_open();
204         else
205                 syslog_init();
206 }
207
208 /* Note that this close & reopen idiom intentionally ignores syslog logging. */
209 void logfile_close(void)
210 {
211         if (logfile_fp) {
212                 logfile_was_closed = 1;
213                 fclose(logfile_fp);
214                 logfile_fp = NULL;
215         }
216 }
217
218 void logfile_reopen(void)
219 {
220         if (logfile_was_closed) {
221                 logfile_was_closed = 0;
222                 logfile_open();
223         }
224 }
225
226 static void filtered_fwrite(FILE *f, const char *buf, int len, int use_isprint)
227 {
228         const char *s, *end = buf + len;
229         for (s = buf; s < end; s++) {
230                 if ((s < end - 4
231                   && *s == '\\' && s[1] == '#'
232                   && isDigit(s + 2)
233                   && isDigit(s + 3)
234                   && isDigit(s + 4))
235                  || (*s != '\t'
236                   && ((use_isprint && !isPrint(s))
237                    || *(uchar*)s < ' '))) {
238                         if (s != buf && fwrite(buf, s - buf, 1, f) != 1)
239                                 exit_cleanup(RERR_MESSAGEIO);
240                         fprintf(f, "\\#%03o", *(uchar*)s);
241                         buf = s + 1;
242                 }
243         }
244         if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
245                 exit_cleanup(RERR_MESSAGEIO);
246 }
247
248 /* this is the underlying (unformatted) rsync debugging function. Call
249  * it with FINFO, FERROR_*, FWARNING, FLOG, or FCLIENT.  Note: recursion
250  * can happen with certain fatal conditions. */
251 void rwrite(enum logcode code, const char *buf, int len, int is_utf8)
252 {
253         int trailing_CR_or_NL;
254         FILE *f = msgs2stderr ? stderr : stdout;
255 #ifdef ICONV_OPTION
256         iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
257 #else
258 #ifdef ICONV_CONST
259         iconv_t ic = ic_chck;
260 #endif
261 #endif
262
263         if (len < 0)
264                 exit_cleanup(RERR_MESSAGEIO);
265
266         if (msgs2stderr) {
267                 if (!am_daemon) {
268                         if (code == FLOG)
269                                 return;
270                         goto output_msg;
271                 }
272                 if (code == FCLIENT)
273                         return;
274                 code = FLOG;
275         } else if (send_msgs_to_gen) {
276                 assert(!is_utf8);
277                 /* Pass the message to our sibling in native charset. */
278                 send_msg((enum msgcode)code, buf, len, 0);
279                 return;
280         }
281
282         if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
283                 code = FERROR;
284         else if (code == FERROR_UTF8) {
285                 is_utf8 = 1;
286                 code = FERROR;
287         }
288
289         if (code == FCLIENT)
290                 code = FINFO;
291         else if (am_daemon || logfile_name) {
292                 static int in_block;
293                 char msg[2048];
294                 int priority = code == FINFO || code == FLOG ? LOG_INFO :  LOG_WARNING;
295
296                 if (in_block)
297                         return;
298                 in_block = 1;
299                 if (!log_initialised)
300                         log_init(0);
301                 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
302                 logit(priority, msg);
303                 in_block = 0;
304
305                 if (code == FLOG || (am_daemon && !am_server))
306                         return;
307         } else if (code == FLOG)
308                 return;
309
310         if (quiet && code == FINFO)
311                 return;
312
313         if (am_server) {
314                 enum msgcode msg = (enum msgcode)code;
315                 if (protocol_version < 30) {
316                         if (msg == MSG_ERROR)
317                                 msg = MSG_ERROR_XFER;
318                         else if (msg == MSG_WARNING)
319                                 msg = MSG_INFO;
320                 }
321                 /* Pass the message to the non-server side. */
322                 if (send_msg(msg, buf, len, !is_utf8))
323                         return;
324                 if (am_daemon) {
325                         /* TODO: can we send the error to the user somehow? */
326                         return;
327                 }
328                 f = stderr;
329         }
330
331 output_msg:
332         switch (code) {
333         case FERROR_XFER:
334                 got_xfer_error = 1;
335                 /* FALL THROUGH */
336         case FERROR:
337         case FERROR_UTF8:
338         case FERROR_SOCKET:
339         case FWARNING:
340                 f = stderr;
341                 break;
342         case FLOG:
343         case FINFO:
344         case FCLIENT:
345                 break;
346         default:
347                 fprintf(stderr, "Unknown logcode in rwrite(): %d [%s]\n", (int)code, who_am_i());
348                 exit_cleanup(RERR_MESSAGEIO);
349         }
350
351         if (output_needs_newline) {
352                 fputc('\n', f);
353                 output_needs_newline = 0;
354         }
355
356         trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
357                           ? buf[--len] : 0;
358
359         if (len && buf[0] == '\r') {
360                 fputc('\r', f);
361                 buf++;
362                 len--;
363         }
364
365 #ifdef ICONV_CONST
366         if (ic != (iconv_t)-1) {
367                 xbuf outbuf, inbuf;
368                 char convbuf[1024];
369                 int ierrno;
370
371                 INIT_CONST_XBUF(outbuf, convbuf);
372                 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
373
374                 while (inbuf.len) {
375                         iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
376                         ierrno = errno;
377                         if (outbuf.len) {
378                                 filtered_fwrite(f, convbuf, outbuf.len, 0);
379                                 outbuf.len = 0;
380                         }
381                         /* Log one byte of illegal/incomplete sequence and continue with
382                          * the next character. Check that the buffer is non-empty for the
383                          * sake of robustness. */
384                         if ((ierrno == EILSEQ || ierrno == EINVAL) && inbuf.len) {
385                                 fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
386                                 inbuf.len--;
387                         }
388                 }
389         } else
390 #endif
391                 filtered_fwrite(f, buf, len, !allow_8bit_chars);
392
393         if (trailing_CR_or_NL) {
394                 fputc(trailing_CR_or_NL, f);
395                 fflush(f);
396         }
397 }
398
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, ...)
402 {
403         va_list ap;
404         char buf[BIGPATHBUFLEN];
405         size_t len;
406
407         va_start(ap, format);
408         len = vsnprintf(buf, sizeof buf, format, ap);
409         va_end(ap);
410
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[] = "[...]";
416
417                 /* Reset length, and zero-terminate the end of our buffer */
418                 len = sizeof buf - 1;
419                 buf[len] = '\0';
420
421                 /* Copy the ellipsis to the end of the string, but give
422                  * us one extra character:
423                  *
424                  *                  v--- null byte at buf[sizeof buf - 1]
425                  *        abcdefghij0
426                  *     -> abcd[...]00  <-- now two null bytes at end
427                  *
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') {
433                         buf[len-1] = '\n';
434                 }
435         }
436
437         rwrite(code, buf, len, 0);
438 }
439
440 /* This is like rprintf, but it also tries to print some
441  * representation of the error code.  Normally errcode = errno.
442  *
443  * Unlike rprintf, this always adds a newline and there should not be
444  * one in the format string.
445  *
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, ...)
449 {
450         va_list ap;
451         char buf[BIGPATHBUFLEN];
452         size_t len;
453
454         strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
455         len = (sizeof RSYNC_NAME ": ") - 1;
456
457         va_start(ap, format);
458         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
459         va_end(ap);
460
461         if (len < sizeof buf) {
462                 len += snprintf(buf + len, sizeof buf - len,
463                                 ": %s (%d)\n", strerror(errcode), errcode);
464         }
465         if (len >= sizeof buf)
466                 exit_cleanup(RERR_MESSAGEIO);
467
468         rwrite(code, buf, len, 0);
469 }
470
471 void rflush(enum logcode code)
472 {
473         FILE *f;
474
475         if (am_daemon || code == FLOG)
476                 return;
477
478         if (!am_server && (code == FINFO || code == FCLIENT))
479                 f = stdout;
480         else
481                 f = stderr;
482
483         fflush(f);
484 }
485
486 void remember_initial_stats(void)
487 {
488         initial_data_read = total_data_read;
489         initial_data_written = total_data_written;
490 }
491
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,
495                           const char *hlink)
496 {
497         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
498         char *p, *s, *c;
499         const char *n;
500         size_t len, total;
501         int64 b;
502
503         *fmt = '%';
504
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);
512         }
513         buf[total++] = '\n';
514         buf[total] = '\0';
515
516         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
517                 int humanize = 0;
518                 s = p++;
519                 c = fmt + 1;
520                 while (*p == '\'') {
521                         humanize++;
522                         p++;
523                 }
524                 if (*p == '-')
525                         *c++ = *p++;
526                 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
527                         *c++ = *p++;
528                 while (*p == '\'') {
529                         humanize++;
530                         p++;
531                 }
532                 if (!*p)
533                         break;
534                 *c = '\0';
535                 n = NULL;
536
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). */
541                 switch (*p) {
542                 case 'h':
543                         if (am_daemon) {
544                                 n = lp_reverse_lookup(module_id)
545                                   ? client_name(0) : undetermined_hostname;
546                         }
547                         break;
548                 case 'a':
549                         if (am_daemon)
550                                 n = client_addr(0);
551                         break;
552                 case 'l':
553                         strlcat(fmt, "s", sizeof fmt);
554                         snprintf(buf2, sizeof buf2, fmt,
555                                  do_big_num(F_LENGTH(file), humanize, NULL));
556                         n = buf2;
557                         break;
558                 case 'U':
559                         strlcat(fmt, "u", sizeof fmt);
560                         snprintf(buf2, sizeof buf2, fmt,
561                                  uid_ndx ? F_OWNER(file) : 0);
562                         n = buf2;
563                         break;
564                 case 'G':
565                         if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
566                                 n = "DEFAULT";
567                         else {
568                                 strlcat(fmt, "u", sizeof fmt);
569                                 snprintf(buf2, sizeof buf2, fmt,
570                                          F_GROUP(file));
571                                 n = buf2;
572                         }
573                         break;
574                 case 'p':
575                         strlcat(fmt, "d", sizeof fmt);
576                         snprintf(buf2, sizeof buf2, fmt, (int)getpid());
577                         n = buf2;
578                         break;
579                 case 'M':
580                         n = c = timestring(file->modtime);
581                         while ((c = strchr(c, ' ')) != NULL)
582                                 *c = '-';
583                         break;
584                 case 'B':
585                         c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
586                         permstring(c, file->mode);
587                         n = c + 1; /* skip the type char */
588                         break;
589                 case 'o':
590                         n = op;
591                         break;
592                 case 'f':
593                         if (fname) {
594                                 c = f_name_buf();
595                                 strlcpy(c, fname, MAXPATHLEN);
596                         } else
597                                 c = f_name(file, NULL);
598                         if (am_sender && F_PATHNAME(file)) {
599                                 pathjoin(buf2, sizeof buf2,
600                                          F_PATHNAME(file), c);
601                                 clean_fname(buf2, 0);
602                                 if (fmt[1]) {
603                                         strlcpy(c, buf2, MAXPATHLEN);
604                                         n = c;
605                                 } else
606                                         n = buf2;
607                         } else if (am_daemon && *c != '/') {
608                                 pathjoin(buf2, sizeof buf2,
609                                          curr_dir + module_dirlen, c);
610                                 clean_fname(buf2, 0);
611                                 if (fmt[1]) {
612                                         strlcpy(c, buf2, MAXPATHLEN);
613                                         n = c;
614                                 } else
615                                         n = buf2;
616                         } else {
617                                 clean_fname(c, 0);
618                                 n = c;
619                         }
620                         if (*n == '/')
621                                 n++;
622                         break;
623                 case 'n':
624                         if (fname) {
625                                 c = f_name_buf();
626                                 strlcpy(c, fname, MAXPATHLEN);
627                         } else
628                                 c = f_name(file, NULL);
629                         if (S_ISDIR(file->mode))
630                                 strlcat(c, "/", MAXPATHLEN);
631                         n = c;
632                         break;
633                 case 'L':
634                         if (hlink && *hlink) {
635                                 n = hlink;
636                                 strlcpy(buf2, " => ", sizeof buf2);
637                         } else if (S_ISLNK(file->mode) && !fname) {
638                                 n = F_SYMLINK(file);
639                                 strlcpy(buf2, " -> ", sizeof buf2);
640                         } else {
641                                 n = "";
642                                 if (!fmt[1])
643                                         break;
644                                 strlcpy(buf2, "    ", sizeof buf2);
645                         }
646                         strlcat(fmt, "s", sizeof fmt);
647                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
648                         n = buf2;
649                         break;
650                 case 'm':
651                         n = lp_name(module_id);
652                         break;
653                 case 't':
654                         n = timestring(time(NULL));
655                         break;
656                 case 'P':
657                         n = full_module_path;
658                         break;
659                 case 'u':
660                         n = auth_user;
661                         break;
662                 case 'b':
663                 case 'c':
664                         if (!(iflags & ITEM_TRANSFER))
665                                 b = 0;
666                         else if ((!!am_sender) ^ (*p == 'c'))
667                                 b = total_data_written - initial_data_written;
668                         else
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));
673                         n = buf2;
674                         break;
675                 case 'C':
676                         n = NULL;
677                         if (S_ISREG(file->mode)) {
678                                 if (always_checksum && canonical_checksum(checksum_type))
679                                         n = sum_as_hex(checksum_type, F_SUM(file), 1);
680                                 else if (iflags & ITEM_TRANSFER && canonical_checksum(xfersum_type))
681                                         n = sum_as_hex(xfersum_type, sender_file_sum, 0);
682                         }
683                         if (!n) {
684                                 int sum_len = csum_len_for_type(always_checksum ? checksum_type : xfersum_type,
685                                                                 always_checksum);
686                                 memset(buf2, ' ', sum_len*2);
687                                 buf2[sum_len*2] = '\0';
688                                 n = buf2;
689                         }
690                         break;
691                 case 'i':
692                         if (iflags & ITEM_DELETED) {
693                                 n = "*deleting  ";
694                                 break;
695                         }
696                         n  = c = buf2 + MAXPATHLEN - 32;
697                         c[0] = iflags & ITEM_LOCAL_CHANGE
698                               ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
699                              : !(iflags & ITEM_TRANSFER) ? '.'
700                              : !local_server && *op == 's' ? '<' : '>';
701                         if (S_ISLNK(file->mode)) {
702                                 c[1] = 'L';
703                                 c[3] = '.';
704                                 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
705                                      : !preserve_times || !receiver_symlink_times
706                                     || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
707                         } else {
708                                 c[1] = S_ISDIR(file->mode) ? 'd'
709                                      : IS_SPECIAL(file->mode) ? 'S'
710                                      : IS_DEVICE(file->mode) ? 'D' : 'f';
711                                 c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
712                                 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
713                                      : !preserve_times ? 'T' : 't';
714                         }
715                         c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
716                         c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
717                         c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
718                         c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
719                         c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.'
720                              : S_ISLNK(file->mode) ? 'U' : 'u';
721                         c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
722                         c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
723                         c[11] = '\0';
724
725                         if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
726                                 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
727                                 int i;
728                                 for (i = 2; c[i]; i++)
729                                         c[i] = ch;
730                         } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
731                                 int i;
732                                 for (i = 2; c[i]; i++) {
733                                         if (c[i] != '.')
734                                                 break;
735                                 }
736                                 if (!c[i]) {
737                                         for (i = 2; c[i]; i++)
738                                                 c[i] = ' ';
739                                 }
740                         }
741                         break;
742                 }
743
744                 /* "n" is the string to be inserted in place of this % code. */
745                 if (!n)
746                         continue;
747                 if (n != buf2 && fmt[1]) {
748                         strlcat(fmt, "s", sizeof fmt);
749                         snprintf(buf2, sizeof buf2, fmt, n);
750                         n = buf2;
751                 }
752                 len = strlen(n);
753
754                 /* Subtract the length of the escape from the string's size. */
755                 total -= p - s + 1;
756
757                 if (len + total >= (size_t)sizeof buf) {
758                         rprintf(FERROR,
759                                 "buffer overflow expanding %%%c -- exiting\n",
760                                 p[0]);
761                         exit_cleanup(RERR_MESSAGEIO);
762                 }
763
764                 /* Shuffle the rest of the string along to make space for n */
765                 if (len != (size_t)(p - s + 1))
766                         memmove(s + len, p + 1, total - (s - buf) + 1);
767                 total += len;
768
769                 /* Insert the contents of string "n", but NOT its null. */
770                 if (len)
771                         memcpy(s, n, len);
772
773                 /* Skip over inserted string; continue looking */
774                 p = s + len;
775         }
776
777         rwrite(code, buf, total, 0);
778 }
779
780 /* Return 1 if the format escape is in the log-format string (e.g. look for
781  * the 'b' in the "%9b" format escape). */
782 int log_format_has(const char *format, char esc)
783 {
784         const char *p;
785
786         if (!format)
787                 return 0;
788
789         for (p = format; (p = strchr(p, '%')) != NULL; ) {
790                 for (p++; *p == '\''; p++) {} /*SHARED ITERATOR*/
791                 if (*p == '-')
792                         p++;
793                 while (isDigit(p))
794                         p++;
795                 while (*p == '\'') p++;
796                 if (!*p)
797                         break;
798                 if (*p == esc)
799                         return 1;
800         }
801         return 0;
802 }
803
804 /* Log the transfer of a file.  If the code is FCLIENT, the output just goes
805  * to stdout.  If it is FLOG, it just goes to the log file.  Otherwise we
806  * output to both. */
807 void log_item(enum logcode code, struct file_struct *file, int iflags, const char *hlink)
808 {
809         const char *s_or_r = am_sender ? "send" : "recv";
810
811         if (code != FLOG && stdout_format && !am_server)
812                 log_formatted(FCLIENT, stdout_format, s_or_r, file, NULL, iflags, hlink);
813         if (code != FCLIENT && logfile_format && *logfile_format)
814                 log_formatted(FLOG, logfile_format, s_or_r, file, NULL, iflags, hlink);
815 }
816
817 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
818                     const char *buf)
819 {
820         int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
821         int see_item = itemizing && (significant_flags || *buf
822                 || stdout_format_has_i > 1 || (INFO_GTE(NAME, 2) && stdout_format_has_i));
823         int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
824         if (am_server) {
825                 if (logfile_name && !dry_run && see_item
826                  && (significant_flags || logfile_format_has_i))
827                         log_item(FLOG, file, iflags, buf);
828         } else if (see_item || local_change || *buf
829             || (S_ISDIR(file->mode) && significant_flags)) {
830                 enum logcode code = significant_flags || logfile_format_has_i ? FINFO : FCLIENT;
831                 log_item(code, file, iflags, buf);
832         }
833 }
834
835 void log_delete(const char *fname, int mode)
836 {
837         static struct {
838                 union file_extras ex[4]; /* just in case... */
839                 struct file_struct file;
840         } x; /* Zero-initialized due to static declaration. */
841         int len = strlen(fname);
842         const char *fmt;
843
844         x.file.mode = mode;
845
846         if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
847                 if (S_ISDIR(mode))
848                         len++; /* directories include trailing null */
849                 send_msg(MSG_DELETED, fname, len, am_generator);
850         } else if (!INFO_GTE(DEL, 1) && !stdout_format)
851                 ;
852         else {
853                 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
854                 log_formatted(FCLIENT, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
855         }
856
857         if (!logfile_name || dry_run || !logfile_format)
858                 return;
859
860         fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
861         log_formatted(FLOG, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
862 }
863
864 /*
865  * Called when the transfer is interrupted for some reason.
866  *
867  * Code is one of the RERR_* codes from errcode.h, or terminating
868  * successfully.
869  */
870 void log_exit(int code, const char *file, int line)
871 {
872         if (code == 0) {
873                 rprintf(FLOG,"sent %s bytes  received %s bytes  total size %s\n",
874                         big_num(stats.total_written),
875                         big_num(stats.total_read),
876                         big_num(stats.total_size));
877         } else if (am_server != 2) {
878                 const char *name;
879
880                 name = rerr_name(code);
881                 if (!name)
882                         name = "unexplained error";
883
884                 /* VANISHED is not an error, only a warning */
885                 if (code == RERR_VANISHED) {
886                         rprintf(FWARNING, "rsync warning: %s (code %d) at %s(%d) [%s=%s]\n",
887                                 name, code, file, line, who_am_i(), RSYNC_VERSION);
888                 } else {
889                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
890                                 name, code, file, line, who_am_i(), RSYNC_VERSION);
891                 }
892         }
893 }