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