Ignore --protect-args when already sent by client
[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         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                         if (!ierrno || ierrno == E2BIG)
382                                 continue;
383                         fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
384                         inbuf.len--;
385                 }
386         } else
387 #endif
388                 filtered_fwrite(f, buf, len, !allow_8bit_chars);
389
390         if (trailing_CR_or_NL) {
391                 fputc(trailing_CR_or_NL, f);
392                 fflush(f);
393         }
394 }
395
396 /* This is the rsync debugging function. Call it with FINFO, FERROR_*,
397  * FWARNING, FLOG, or FCLIENT. */
398 void rprintf(enum logcode code, const char *format, ...)
399 {
400         va_list ap;
401         char buf[BIGPATHBUFLEN];
402         size_t len;
403
404         va_start(ap, format);
405         len = vsnprintf(buf, sizeof buf, format, ap);
406         va_end(ap);
407
408         /* Deal with buffer overruns.  Instead of panicking, just
409          * truncate the resulting string.  (Note that configure ensures
410          * that we have a vsnprintf() that doesn't ever return -1.) */
411         if (len > sizeof buf - 1) {
412                 static const char ellipsis[] = "[...]";
413
414                 /* Reset length, and zero-terminate the end of our buffer */
415                 len = sizeof buf - 1;
416                 buf[len] = '\0';
417
418                 /* Copy the ellipsis to the end of the string, but give
419                  * us one extra character:
420                  *
421                  *                  v--- null byte at buf[sizeof buf - 1]
422                  *        abcdefghij0
423                  *     -> abcd[...]00  <-- now two null bytes at end
424                  *
425                  * If the input format string has a trailing newline,
426                  * we copy it into that extra null; if it doesn't, well,
427                  * all we lose is one byte.  */
428                 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
429                 if (format[strlen(format)-1] == '\n') {
430                         buf[len-1] = '\n';
431                 }
432         }
433
434         rwrite(code, buf, len, 0);
435 }
436
437 /* This is like rprintf, but it also tries to print some
438  * representation of the error code.  Normally errcode = errno.
439  *
440  * Unlike rprintf, this always adds a newline and there should not be
441  * one in the format string.
442  *
443  * Note that since strerror might involve dynamically loading a
444  * message catalog we need to call it once before chroot-ing. */
445 void rsyserr(enum logcode code, int errcode, const char *format, ...)
446 {
447         va_list ap;
448         char buf[BIGPATHBUFLEN];
449         size_t len;
450
451         strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
452         len = (sizeof RSYNC_NAME ": ") - 1;
453
454         va_start(ap, format);
455         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
456         va_end(ap);
457
458         if (len < sizeof buf) {
459                 len += snprintf(buf + len, sizeof buf - len,
460                                 ": %s (%d)\n", strerror(errcode), errcode);
461         }
462         if (len >= sizeof buf)
463                 exit_cleanup(RERR_MESSAGEIO);
464
465         rwrite(code, buf, len, 0);
466 }
467
468 void rflush(enum logcode code)
469 {
470         FILE *f;
471
472         if (am_daemon || code == FLOG)
473                 return;
474
475         if (!am_server && (code == FINFO || code == FCLIENT))
476                 f = stdout;
477         else
478                 f = stderr;
479
480         fflush(f);
481 }
482
483 void remember_initial_stats(void)
484 {
485         initial_data_read = total_data_read;
486         initial_data_written = total_data_written;
487 }
488
489 /* A generic logging routine for send/recv, with parameter substitiution. */
490 static void log_formatted(enum logcode code, const char *format, const char *op,
491                           struct file_struct *file, const char *fname, int iflags,
492                           const char *hlink)
493 {
494         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
495         char *p, *s, *c;
496         const char *n;
497         size_t len, total;
498         int64 b;
499
500         *fmt = '%';
501
502         /* We expand % codes one by one in place in buf.  We don't
503          * copy in the terminating null of the inserted strings, but
504          * rather keep going until we reach the null of the format. */
505         total = strlcpy(buf, format, sizeof buf);
506         if (total > MAXPATHLEN) {
507                 rprintf(FERROR, "log-format string is WAY too long!\n");
508                 exit_cleanup(RERR_MESSAGEIO);
509         }
510         buf[total++] = '\n';
511         buf[total] = '\0';
512
513         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
514                 int humanize = 0;
515                 s = p++;
516                 c = fmt + 1;
517                 while (*p == '\'') {
518                         humanize++;
519                         p++;
520                 }
521                 if (*p == '-')
522                         *c++ = *p++;
523                 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
524                         *c++ = *p++;
525                 while (*p == '\'') {
526                         humanize++;
527                         p++;
528                 }
529                 if (!*p)
530                         break;
531                 *c = '\0';
532                 n = NULL;
533
534                 /* Note for %h and %a: it doesn't matter what fd we pass to
535                  * client_{name,addr} because rsync_module will already have
536                  * forced the answer to be cached (assuming, of course, for %h
537                  * that lp_reverse_lookup(module_id) is true). */
538                 switch (*p) {
539                 case 'h':
540                         if (am_daemon) {
541                                 n = lp_reverse_lookup(module_id)
542                                   ? client_name(0) : undetermined_hostname;
543                         }
544                         break;
545                 case 'a':
546                         if (am_daemon)
547                                 n = client_addr(0);
548                         break;
549                 case 'l':
550                         strlcat(fmt, "s", sizeof fmt);
551                         snprintf(buf2, sizeof buf2, fmt,
552                                  do_big_num(F_LENGTH(file), humanize, NULL));
553                         n = buf2;
554                         break;
555                 case 'U':
556                         strlcat(fmt, "u", sizeof fmt);
557                         snprintf(buf2, sizeof buf2, fmt,
558                                  uid_ndx ? F_OWNER(file) : 0);
559                         n = buf2;
560                         break;
561                 case 'G':
562                         if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
563                                 n = "DEFAULT";
564                         else {
565                                 strlcat(fmt, "u", sizeof fmt);
566                                 snprintf(buf2, sizeof buf2, fmt,
567                                          F_GROUP(file));
568                                 n = buf2;
569                         }
570                         break;
571                 case 'p':
572                         strlcat(fmt, "d", sizeof fmt);
573                         snprintf(buf2, sizeof buf2, fmt, (int)getpid());
574                         n = buf2;
575                         break;
576                 case 'M':
577                         n = c = timestring(file->modtime);
578                         while ((c = strchr(c, ' ')) != NULL)
579                                 *c = '-';
580                         break;
581                 case 'B':
582                         c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
583                         permstring(c, file->mode);
584                         n = c + 1; /* skip the type char */
585                         break;
586                 case 'o':
587                         n = op;
588                         break;
589                 case 'f':
590                         if (fname) {
591                                 c = f_name_buf();
592                                 strlcpy(c, fname, MAXPATHLEN);
593                         } else
594                                 c = f_name(file, NULL);
595                         if (am_sender && F_PATHNAME(file)) {
596                                 pathjoin(buf2, sizeof buf2,
597                                          F_PATHNAME(file), c);
598                                 clean_fname(buf2, 0);
599                                 if (fmt[1]) {
600                                         strlcpy(c, buf2, MAXPATHLEN);
601                                         n = c;
602                                 } else
603                                         n = buf2;
604                         } else if (am_daemon && *c != '/') {
605                                 pathjoin(buf2, sizeof buf2,
606                                          curr_dir + module_dirlen, c);
607                                 clean_fname(buf2, 0);
608                                 if (fmt[1]) {
609                                         strlcpy(c, buf2, MAXPATHLEN);
610                                         n = c;
611                                 } else
612                                         n = buf2;
613                         } else {
614                                 clean_fname(c, 0);
615                                 n = c;
616                         }
617                         if (*n == '/')
618                                 n++;
619                         break;
620                 case 'n':
621                         if (fname) {
622                                 c = f_name_buf();
623                                 strlcpy(c, fname, MAXPATHLEN);
624                         } else
625                                 c = f_name(file, NULL);
626                         if (S_ISDIR(file->mode))
627                                 strlcat(c, "/", MAXPATHLEN);
628                         n = c;
629                         break;
630                 case 'L':
631                         if (hlink && *hlink) {
632                                 n = hlink;
633                                 strlcpy(buf2, " => ", sizeof buf2);
634                         } else if (S_ISLNK(file->mode) && !fname) {
635                                 n = F_SYMLINK(file);
636                                 strlcpy(buf2, " -> ", sizeof buf2);
637                         } else {
638                                 n = "";
639                                 if (!fmt[1])
640                                         break;
641                                 strlcpy(buf2, "    ", sizeof buf2);
642                         }
643                         strlcat(fmt, "s", sizeof fmt);
644                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
645                         n = buf2;
646                         break;
647                 case 'm':
648                         n = lp_name(module_id);
649                         break;
650                 case 't':
651                         n = timestring(time(NULL));
652                         break;
653                 case 'P':
654                         n = full_module_path;
655                         break;
656                 case 'u':
657                         n = auth_user;
658                         break;
659                 case 'b':
660                 case 'c':
661                         if (!(iflags & ITEM_TRANSFER))
662                                 b = 0;
663                         else if ((!!am_sender) ^ (*p == 'c'))
664                                 b = total_data_written - initial_data_written;
665                         else
666                                 b = total_data_read - initial_data_read;
667                         strlcat(fmt, "s", sizeof fmt);
668                         snprintf(buf2, sizeof buf2, fmt,
669                                  do_big_num(b, humanize, NULL));
670                         n = buf2;
671                         break;
672                 case 'C':
673                         n = NULL;
674                         if (S_ISREG(file->mode)) {
675                                 if (always_checksum && canonical_checksum(checksum_type))
676                                         n = sum_as_hex(checksum_type, F_SUM(file), 1);
677                                 else if (iflags & ITEM_TRANSFER && canonical_checksum(xfersum_type))
678                                         n = sum_as_hex(xfersum_type, sender_file_sum, 0);
679                         }
680                         if (!n) {
681                                 int sum_len = csum_len_for_type(always_checksum ? checksum_type : xfersum_type,
682                                                                 always_checksum);
683                                 memset(buf2, ' ', sum_len*2);
684                                 buf2[sum_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 }