Add --checksum-choice option to choose the checksum algorithms.
[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-2015 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         static int been_here = 0;
138         int options = LOG_PID;
139
140         if (been_here)
141                 return;
142         been_here = 1;
143
144 #ifdef LOG_NDELAY
145         options |= LOG_NDELAY;
146 #endif
147
148 #ifdef LOG_DAEMON
149         openlog("rsyncd", options, lp_syslog_facility(module_id));
150 #else
151         openlog("rsyncd", options);
152 #endif
153
154 #ifndef LOG_NDELAY
155         logit(LOG_INFO, "rsyncd started\n");
156 #endif
157 }
158
159 static void logfile_open(void)
160 {
161         mode_t old_umask = umask(022 | orig_umask);
162         logfile_fp = fopen(logfile_name, "a");
163         umask(old_umask);
164         if (!logfile_fp) {
165                 int fopen_errno = errno;
166                 /* Rsync falls back to using syslog on failure. */
167                 syslog_init();
168                 rsyserr(FERROR, fopen_errno,
169                         "failed to open log-file %s", logfile_name);
170                 rprintf(FINFO, "Ignoring \"log file\" setting.\n");
171         }
172 }
173
174 void log_init(int restart)
175 {
176         if (log_initialised) {
177                 if (!restart)
178                         return;
179                 if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
180                         if (logfile_fp) {
181                                 fclose(logfile_fp);
182                                 logfile_fp = NULL;
183                         } else
184                                 closelog();
185                         logfile_name = NULL;
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))
189                         closelog();
190                 else
191                         return; /* unchanged syslog settings */
192         } else
193                 log_initialised = 1;
194
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));
199
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)
205                 logfile_open();
206         else
207                 syslog_init();
208 }
209
210 void logfile_close(void)
211 {
212         if (logfile_fp) {
213                 logfile_was_closed = 1;
214                 fclose(logfile_fp);
215                 logfile_fp = NULL;
216         }
217 }
218
219 void logfile_reopen(void)
220 {
221         if (logfile_was_closed) {
222                 logfile_was_closed = 0;
223                 logfile_open();
224         }
225 }
226
227 static void filtered_fwrite(FILE *f, const char *buf, int len, int use_isprint)
228 {
229         const char *s, *end = buf + len;
230         for (s = buf; s < end; s++) {
231                 if ((s < end - 4
232                   && *s == '\\' && s[1] == '#'
233                   && isDigit(s + 2)
234                   && isDigit(s + 3)
235                   && isDigit(s + 4))
236                  || (*s != '\t'
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);
242                         buf = s + 1;
243                 }
244         }
245         if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
246                 exit_cleanup(RERR_MESSAGEIO);
247 }
248
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)
253 {
254         int trailing_CR_or_NL;
255         FILE *f = msgs2stderr ? stderr : stdout;
256 #ifdef ICONV_OPTION
257         iconv_t ic = is_utf8 && ic_recv != (iconv_t)-1 ? ic_recv : ic_chck;
258 #else
259 #ifdef ICONV_CONST
260         iconv_t ic = ic_chck;
261 #endif
262 #endif
263
264         if (len < 0)
265                 exit_cleanup(RERR_MESSAGEIO);
266
267         if (msgs2stderr) {
268                 if (!am_daemon) {
269                         if (code == FLOG)
270                                 return;
271                         goto output_msg;
272                 }
273                 if (code == FCLIENT)
274                         return;
275                 code = FLOG;
276         } else if (send_msgs_to_gen) {
277                 assert(!is_utf8);
278                 /* Pass the message to our sibling in native charset. */
279                 send_msg((enum msgcode)code, buf, len, 0);
280                 return;
281         }
282
283         if (code == FERROR_SOCKET) /* This gets simplified for a non-sibling. */
284                 code = FERROR;
285         else if (code == FERROR_UTF8) {
286                 is_utf8 = 1;
287                 code = FERROR;
288         }
289
290         if (code == FCLIENT)
291                 code = FINFO;
292         else if (am_daemon || logfile_name) {
293                 static int in_block;
294                 char msg[2048];
295                 int priority = code == FINFO || code == FLOG ? LOG_INFO :  LOG_WARNING;
296
297                 if (in_block)
298                         return;
299                 in_block = 1;
300                 if (!log_initialised)
301                         log_init(0);
302                 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
303                 logit(priority, msg);
304                 in_block = 0;
305
306                 if (code == FLOG || (am_daemon && !am_server))
307                         return;
308         } else if (code == FLOG)
309                 return;
310
311         if (quiet && code == FINFO)
312                 return;
313
314         if (am_server) {
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)
320                                 msg = MSG_INFO;
321                 }
322                 /* Pass the message to the non-server side. */
323                 if (send_msg(msg, buf, len, !is_utf8))
324                         return;
325                 if (am_daemon) {
326                         /* TODO: can we send the error to the user somehow? */
327                         return;
328                 }
329                 f = stderr;
330         }
331
332 output_msg:
333         switch (code) {
334         case FERROR_XFER:
335                 got_xfer_error = 1;
336                 /* FALL THROUGH */
337         case FERROR:
338         case FERROR_UTF8:
339         case FERROR_SOCKET:
340         case FWARNING:
341                 f = stderr;
342                 break;
343         case FLOG:
344         case FINFO:
345         case FCLIENT:
346                 break;
347         default:
348                 fprintf(stderr, "Unknown logcode in rwrite(): %d [%s]\n", (int)code, who_am_i());
349                 exit_cleanup(RERR_MESSAGEIO);
350         }
351
352         if (output_needs_newline) {
353                 fputc('\n', f);
354                 output_needs_newline = 0;
355         }
356
357         trailing_CR_or_NL = len && (buf[len-1] == '\n' || buf[len-1] == '\r')
358                           ? buf[--len] : 0;
359
360         if (len && buf[0] == '\r') {
361                 fputc('\r', f);
362                 buf++;
363                 len--;
364         }
365
366 #ifdef ICONV_CONST
367         if (ic != (iconv_t)-1) {
368                 xbuf outbuf, inbuf;
369                 char convbuf[1024];
370                 int ierrno;
371
372                 INIT_CONST_XBUF(outbuf, convbuf);
373                 INIT_XBUF(inbuf, (char*)buf, len, (size_t)-1);
374
375                 while (inbuf.len) {
376                         iconvbufs(ic, &inbuf, &outbuf, inbuf.pos ? 0 : ICB_INIT);
377                         ierrno = errno;
378                         if (outbuf.len) {
379                                 filtered_fwrite(f, convbuf, outbuf.len, 0);
380                                 outbuf.len = 0;
381                         }
382                         if (!ierrno || ierrno == E2BIG)
383                                 continue;
384                         fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
385                         inbuf.len--;
386                 }
387         } else
388 #endif
389                 filtered_fwrite(f, buf, len, !allow_8bit_chars);
390
391         if (trailing_CR_or_NL) {
392                 fputc(trailing_CR_or_NL, f);
393                 fflush(f);
394         }
395 }
396
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, ...)
400 {
401         va_list ap;
402         char buf[BIGPATHBUFLEN];
403         size_t len;
404
405         va_start(ap, format);
406         len = vsnprintf(buf, sizeof buf, format, ap);
407         va_end(ap);
408
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[] = "[...]";
414
415                 /* Reset length, and zero-terminate the end of our buffer */
416                 len = sizeof buf - 1;
417                 buf[len] = '\0';
418
419                 /* Copy the ellipsis to the end of the string, but give
420                  * us one extra character:
421                  *
422                  *                  v--- null byte at buf[sizeof buf - 1]
423                  *        abcdefghij0
424                  *     -> abcd[...]00  <-- now two null bytes at end
425                  *
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') {
431                         buf[len-1] = '\n';
432                 }
433         }
434
435         rwrite(code, buf, len, 0);
436 }
437
438 /* This is like rprintf, but it also tries to print some
439  * representation of the error code.  Normally errcode = errno.
440  *
441  * Unlike rprintf, this always adds a newline and there should not be
442  * one in the format string.
443  *
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, ...)
447 {
448         va_list ap;
449         char buf[BIGPATHBUFLEN];
450         size_t len;
451
452         strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
453         len = (sizeof RSYNC_NAME ": ") - 1;
454
455         va_start(ap, format);
456         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
457         va_end(ap);
458
459         if (len < sizeof buf) {
460                 len += snprintf(buf + len, sizeof buf - len,
461                                 ": %s (%d)\n", strerror(errcode), errcode);
462         }
463         if (len >= sizeof buf)
464                 exit_cleanup(RERR_MESSAGEIO);
465
466         rwrite(code, buf, len, 0);
467 }
468
469 void rflush(enum logcode code)
470 {
471         FILE *f;
472
473         if (am_daemon || code == FLOG)
474                 return;
475
476         if (!am_server && (code == FINFO || code == FCLIENT))
477                 f = stdout;
478         else
479                 f = stderr;
480
481         fflush(f);
482 }
483
484 void remember_initial_stats(void)
485 {
486         initial_data_read = total_data_read;
487         initial_data_written = total_data_written;
488 }
489
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,
493                           const char *hlink)
494 {
495         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
496         char *p, *s, *c;
497         const char *n;
498         size_t len, total;
499         int64 b;
500
501         *fmt = '%';
502
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);
510         }
511         buf[total++] = '\n';
512         buf[total] = '\0';
513
514         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
515                 int humanize = 0;
516                 s = p++;
517                 c = fmt + 1;
518                 while (*p == '\'') {
519                         humanize++;
520                         p++;
521                 }
522                 if (*p == '-')
523                         *c++ = *p++;
524                 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
525                         *c++ = *p++;
526                 while (*p == '\'') {
527                         humanize++;
528                         p++;
529                 }
530                 if (!*p)
531                         break;
532                 *c = '\0';
533                 n = NULL;
534
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). */
539                 switch (*p) {
540                 case 'h':
541                         if (am_daemon) {
542                                 n = lp_reverse_lookup(module_id)
543                                   ? client_name(0) : undetermined_hostname;
544                         }
545                         break;
546                 case 'a':
547                         if (am_daemon)
548                                 n = client_addr(0);
549                         break;
550                 case 'l':
551                         strlcat(fmt, "s", sizeof fmt);
552                         snprintf(buf2, sizeof buf2, fmt,
553                                  do_big_num(F_LENGTH(file), humanize, NULL));
554                         n = buf2;
555                         break;
556                 case 'U':
557                         strlcat(fmt, "u", sizeof fmt);
558                         snprintf(buf2, sizeof buf2, fmt,
559                                  uid_ndx ? F_OWNER(file) : 0);
560                         n = buf2;
561                         break;
562                 case 'G':
563                         if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
564                                 n = "DEFAULT";
565                         else {
566                                 strlcat(fmt, "u", sizeof fmt);
567                                 snprintf(buf2, sizeof buf2, fmt,
568                                          F_GROUP(file));
569                                 n = buf2;
570                         }
571                         break;
572                 case 'p':
573                         strlcat(fmt, "d", sizeof fmt);
574                         snprintf(buf2, sizeof buf2, fmt, (int)getpid());
575                         n = buf2;
576                         break;
577                 case 'M':
578                         n = c = timestring(file->modtime);
579                         while ((c = strchr(c, ' ')) != NULL)
580                                 *c = '-';
581                         break;
582                 case 'B':
583                         c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
584                         permstring(c, file->mode);
585                         n = c + 1; /* skip the type char */
586                         break;
587                 case 'o':
588                         n = op;
589                         break;
590                 case 'f':
591                         if (fname) {
592                                 c = f_name_buf();
593                                 strlcpy(c, fname, MAXPATHLEN);
594                         } else
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);
600                                 if (fmt[1]) {
601                                         strlcpy(c, buf2, MAXPATHLEN);
602                                         n = c;
603                                 } else
604                                         n = buf2;
605                         } else if (am_daemon && *c != '/') {
606                                 pathjoin(buf2, sizeof buf2,
607                                          curr_dir + module_dirlen, c);
608                                 clean_fname(buf2, 0);
609                                 if (fmt[1]) {
610                                         strlcpy(c, buf2, MAXPATHLEN);
611                                         n = c;
612                                 } else
613                                         n = buf2;
614                         } else {
615                                 clean_fname(c, 0);
616                                 n = c;
617                         }
618                         if (*n == '/')
619                                 n++;
620                         break;
621                 case 'n':
622                         if (fname) {
623                                 c = f_name_buf();
624                                 strlcpy(c, fname, MAXPATHLEN);
625                         } else
626                                 c = f_name(file, NULL);
627                         if (S_ISDIR(file->mode))
628                                 strlcat(c, "/", MAXPATHLEN);
629                         n = c;
630                         break;
631                 case 'L':
632                         if (hlink && *hlink) {
633                                 n = hlink;
634                                 strlcpy(buf2, " => ", sizeof buf2);
635                         } else if (S_ISLNK(file->mode) && !fname) {
636                                 n = F_SYMLINK(file);
637                                 strlcpy(buf2, " -> ", sizeof buf2);
638                         } else {
639                                 n = "";
640                                 if (!fmt[1])
641                                         break;
642                                 strlcpy(buf2, "    ", sizeof buf2);
643                         }
644                         strlcat(fmt, "s", sizeof fmt);
645                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
646                         n = buf2;
647                         break;
648                 case 'm':
649                         n = lp_name(module_id);
650                         break;
651                 case 't':
652                         n = timestring(time(NULL));
653                         break;
654                 case 'P':
655                         n = full_module_path;
656                         break;
657                 case 'u':
658                         n = auth_user;
659                         break;
660                 case 'b':
661                 case 'c':
662                         if (!(iflags & ITEM_TRANSFER))
663                                 b = 0;
664                         else if ((!!am_sender) ^ (*p == 'c'))
665                                 b = total_data_written - initial_data_written;
666                         else
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));
671                         n = buf2;
672                         break;
673                 case 'C':
674                         n = 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);
680                         }
681                         if (!n) {
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';
685                                 n = buf2;
686                         }
687                         break;
688                 case 'i':
689                         if (iflags & ITEM_DELETED) {
690                                 n = "*deleting  ";
691                                 break;
692                         }
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)) {
699                                 c[1] = 'L';
700                                 c[3] = '.';
701                                 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
702                                      : !preserve_times || !receiver_symlink_times
703                                     || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
704                         } else {
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';
711                         }
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';
719                         c[11] = '\0';
720
721                         if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
722                                 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
723                                 int i;
724                                 for (i = 2; c[i]; i++)
725                                         c[i] = ch;
726                         } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
727                                 int i;
728                                 for (i = 2; c[i]; i++) {
729                                         if (c[i] != '.')
730                                                 break;
731                                 }
732                                 if (!c[i]) {
733                                         for (i = 2; c[i]; i++)
734                                                 c[i] = ' ';
735                                 }
736                         }
737                         break;
738                 }
739
740                 /* "n" is the string to be inserted in place of this % code. */
741                 if (!n)
742                         continue;
743                 if (n != buf2 && fmt[1]) {
744                         strlcat(fmt, "s", sizeof fmt);
745                         snprintf(buf2, sizeof buf2, fmt, n);
746                         n = buf2;
747                 }
748                 len = strlen(n);
749
750                 /* Subtract the length of the escape from the string's size. */
751                 total -= p - s + 1;
752
753                 if (len + total >= (size_t)sizeof buf) {
754                         rprintf(FERROR,
755                                 "buffer overflow expanding %%%c -- exiting\n",
756                                 p[0]);
757                         exit_cleanup(RERR_MESSAGEIO);
758                 }
759
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);
763                 total += len;
764
765                 /* Insert the contents of string "n", but NOT its null. */
766                 if (len)
767                         memcpy(s, n, len);
768
769                 /* Skip over inserted string; continue looking */
770                 p = s + len;
771         }
772
773         rwrite(code, buf, total, 0);
774 }
775
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)
779 {
780         const char *p;
781
782         if (!format)
783                 return 0;
784
785         for (p = format; (p = strchr(p, '%')) != NULL; ) {
786                 for (p++; *p == '\''; p++) {} /*SHARED ITERATOR*/
787                 if (*p == '-')
788                         p++;
789                 while (isDigit(p))
790                         p++;
791                 while (*p == '\'') p++;
792                 if (!*p)
793                         break;
794                 if (*p == esc)
795                         return 1;
796         }
797         return 0;
798 }
799
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
802  * output to both. */
803 void log_item(enum logcode code, struct file_struct *file, int iflags, const char *hlink)
804 {
805         const char *s_or_r = am_sender ? "send" : "recv";
806
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);
811 }
812
813 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
814                     const char *buf)
815 {
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;
820         if (am_server) {
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);
828         }
829 }
830
831 void log_delete(const char *fname, int mode)
832 {
833         static struct {
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);
838         const char *fmt;
839
840         x.file.mode = mode;
841
842         if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
843                 if (S_ISDIR(mode))
844                         len++; /* directories include trailing null */
845                 send_msg(MSG_DELETED, fname, len, am_generator);
846         } else if (!INFO_GTE(DEL, 1) && !stdout_format)
847                 ;
848         else {
849                 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
850                 log_formatted(FCLIENT, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
851         }
852
853         if (!logfile_name || dry_run || !logfile_format)
854                 return;
855
856         fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
857         log_formatted(FLOG, fmt, "del.", &x.file, fname, ITEM_DELETED, NULL);
858 }
859
860 /*
861  * Called when the transfer is interrupted for some reason.
862  *
863  * Code is one of the RERR_* codes from errcode.h, or terminating
864  * successfully.
865  */
866 void log_exit(int code, const char *file, int line)
867 {
868         if (code == 0) {
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) {
874                 const char *name;
875
876                 name = rerr_name(code);
877                 if (!name)
878                         name = "unexplained error";
879
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);
884                 } else {
885                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
886                                 name, code, file, line, who_am_i(), RSYNC_VERSION);
887                 }
888         }
889 }