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