The deny-rsync script from bug 3945.
[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 && !am_server) {
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 #ifdef ICONV_CONST
333         if (ic != (iconv_t)-1) {
334                 xbuf outbuf, inbuf;
335                 char convbuf[1024];
336                 int ierrno;
337
338                 INIT_CONST_XBUF(outbuf, convbuf);
339                 INIT_XBUF(inbuf, (char*)buf, len, -1);
340
341                 while (inbuf.len) {
342                         iconvbufs(ic, &inbuf, &outbuf, 0);
343                         ierrno = errno;
344                         if (outbuf.len) {
345                                 filtered_fwrite(f, convbuf, outbuf.len, 0);
346                                 outbuf.len = 0;
347                         }
348                         if (!ierrno || ierrno == E2BIG)
349                                 continue;
350                         fprintf(f, "\\#%03o", CVAL(inbuf.buf, inbuf.pos++));
351                         inbuf.len--;
352                 }
353         } else
354 #endif
355                 filtered_fwrite(f, buf, len, !allow_8bit_chars);
356
357         if (trailing_CR_or_NL) {
358                 fputc(trailing_CR_or_NL, f);
359                 fflush(f);
360         }
361 }
362
363 /* This is the rsync debugging function. Call it with FINFO, FERROR_*,
364  * FWARNING, FLOG, or FCLIENT. */
365 void rprintf(enum logcode code, const char *format, ...)
366 {
367         va_list ap;
368         char buf[BIGPATHBUFLEN];
369         size_t len;
370
371         va_start(ap, format);
372         len = vsnprintf(buf, sizeof buf, format, ap);
373         va_end(ap);
374
375         /* Deal with buffer overruns.  Instead of panicking, just
376          * truncate the resulting string.  (Note that configure ensures
377          * that we have a vsnprintf() that doesn't ever return -1.) */
378         if (len > sizeof buf - 1) {
379                 static const char ellipsis[] = "[...]";
380
381                 /* Reset length, and zero-terminate the end of our buffer */
382                 len = sizeof buf - 1;
383                 buf[len] = '\0';
384
385                 /* Copy the ellipsis to the end of the string, but give
386                  * us one extra character:
387                  *
388                  *                  v--- null byte at buf[sizeof buf - 1]
389                  *        abcdefghij0
390                  *     -> abcd[...]00  <-- now two null bytes at end
391                  *
392                  * If the input format string has a trailing newline,
393                  * we copy it into that extra null; if it doesn't, well,
394                  * all we lose is one byte.  */
395                 memcpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
396                 if (format[strlen(format)-1] == '\n') {
397                         buf[len-1] = '\n';
398                 }
399         }
400
401         rwrite(code, buf, len, 0);
402 }
403
404 /* This is like rprintf, but it also tries to print some
405  * representation of the error code.  Normally errcode = errno.
406  *
407  * Unlike rprintf, this always adds a newline and there should not be
408  * one in the format string.
409  *
410  * Note that since strerror might involve dynamically loading a
411  * message catalog we need to call it once before chroot-ing. */
412 void rsyserr(enum logcode code, int errcode, const char *format, ...)
413 {
414         va_list ap;
415         char buf[BIGPATHBUFLEN];
416         size_t len;
417
418         strlcpy(buf, RSYNC_NAME ": ", sizeof buf);
419         len = (sizeof RSYNC_NAME ": ") - 1;
420
421         va_start(ap, format);
422         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
423         va_end(ap);
424
425         if (len < sizeof buf) {
426                 len += snprintf(buf + len, sizeof buf - len,
427                                 ": %s (%d)\n", strerror(errcode), errcode);
428         }
429         if (len >= sizeof buf)
430                 exit_cleanup(RERR_MESSAGEIO);
431
432         rwrite(code, buf, len, 0);
433 }
434
435 void rflush(enum logcode code)
436 {
437         FILE *f = NULL;
438
439         if (am_daemon || code == FLOG)
440                 return;
441
442         if (code == FINFO && !am_server)
443                 f = stdout;
444         else
445                 f = stderr;
446
447         fflush(f);
448 }
449
450 /* A generic logging routine for send/recv, with parameter substitiution. */
451 static void log_formatted(enum logcode code, const char *format, const char *op,
452                           struct file_struct *file, const char *fname,
453                           struct stats *initial_stats, int iflags,
454                           const char *hlink)
455 {
456         char buf[MAXPATHLEN+1024], buf2[MAXPATHLEN], fmt[32];
457         char *p, *s, *c;
458         const char *n;
459         size_t len, total;
460         int64 b;
461
462         *fmt = '%';
463
464         /* We expand % codes one by one in place in buf.  We don't
465          * copy in the terminating null of the inserted strings, but
466          * rather keep going until we reach the null of the format. */
467         total = strlcpy(buf, format, sizeof buf);
468         if (total > MAXPATHLEN) {
469                 rprintf(FERROR, "log-format string is WAY too long!\n");
470                 exit_cleanup(RERR_MESSAGEIO);
471         }
472         buf[total++] = '\n';
473         buf[total] = '\0';
474
475         for (p = buf; (p = strchr(p, '%')) != NULL; ) {
476                 s = p++;
477                 c = fmt + 1;
478                 if (*p == '-')
479                         *c++ = *p++;
480                 while (isDigit(p) && c - fmt < (int)(sizeof fmt) - 8)
481                         *c++ = *p++;
482                 if (!*p)
483                         break;
484                 *c = '\0';
485                 n = NULL;
486
487                 switch (*p) {
488                 case 'h':
489                         if (am_daemon)
490                                 n = client_name(0);
491                         break;
492                 case 'a':
493                         if (am_daemon)
494                                 n = client_addr(0);
495                         break;
496                 case 'l':
497                         strlcat(fmt, ".0f", sizeof fmt);
498                         snprintf(buf2, sizeof buf2, fmt,
499                                  (double)F_LENGTH(file));
500                         n = buf2;
501                         break;
502                 case 'U':
503                         strlcat(fmt, "u", sizeof fmt);
504                         snprintf(buf2, sizeof buf2, fmt,
505                                  uid_ndx ? F_OWNER(file) : 0);
506                         n = buf2;
507                         break;
508                 case 'G':
509                         if (!gid_ndx || file->flags & FLAG_SKIP_GROUP)
510                                 n = "DEFAULT";
511                         else {
512                                 strlcat(fmt, "u", sizeof fmt);
513                                 snprintf(buf2, sizeof buf2, fmt,
514                                          F_GROUP(file));
515                                 n = buf2;
516                         }
517                         break;
518                 case 'p':
519                         strlcat(fmt, "ld", sizeof fmt);
520                         snprintf(buf2, sizeof buf2, fmt,
521                                  (long)getpid());
522                         n = buf2;
523                         break;
524                 case 'M':
525                         n = c = timestring(file->modtime);
526                         while ((c = strchr(c, ' ')) != NULL)
527                                 *c = '-';
528                         break;
529                 case 'B':
530                         c = buf2 + MAXPATHLEN - PERMSTRING_SIZE - 1;
531                         permstring(c, file->mode);
532                         n = c + 1; /* skip the type char */
533                         break;
534                 case 'o':
535                         n = op;
536                         break;
537                 case 'f':
538                         if (fname) {
539                                 c = f_name_buf();
540                                 strlcpy(c, fname, MAXPATHLEN);
541                         } else
542                                 c = f_name(file, NULL);
543                         if (am_sender && F_PATHNAME(file)) {
544                                 pathjoin(buf2, sizeof buf2,
545                                          F_PATHNAME(file), c);
546                                 clean_fname(buf2, 0);
547                                 if (fmt[1]) {
548                                         strlcpy(c, buf2, MAXPATHLEN);
549                                         n = c;
550                                 } else
551                                         n = buf2;
552                         } else if (am_daemon && *c != '/') {
553                                 pathjoin(buf2, sizeof buf2,
554                                          curr_dir + module_dirlen, c);
555                                 clean_fname(buf2, 0);
556                                 if (fmt[1]) {
557                                         strlcpy(c, buf2, MAXPATHLEN);
558                                         n = c;
559                                 } else
560                                         n = buf2;
561                         } else {
562                                 clean_fname(c, 0);
563                                 n = c;
564                         }
565                         if (*n == '/')
566                                 n++;
567                         break;
568                 case 'n':
569                         if (fname) {
570                                 c = f_name_buf();
571                                 strlcpy(c, fname, MAXPATHLEN);
572                         } else
573                                 c = f_name(file, NULL);
574                         if (S_ISDIR(file->mode))
575                                 strlcat(c, "/", MAXPATHLEN);
576                         n = c;
577                         break;
578                 case 'L':
579                         if (hlink && *hlink) {
580                                 n = hlink;
581                                 strlcpy(buf2, " => ", sizeof buf2);
582                         } else if (S_ISLNK(file->mode) && !fname) {
583                                 n = F_SYMLINK(file);
584                                 strlcpy(buf2, " -> ", sizeof buf2);
585                         } else {
586                                 n = "";
587                                 if (!fmt[1])
588                                         break;
589                                 strlcpy(buf2, "    ", sizeof buf2);
590                         }
591                         strlcat(fmt, "s", sizeof fmt);
592                         snprintf(buf2 + 4, sizeof buf2 - 4, fmt, n);
593                         n = buf2;
594                         break;
595                 case 'm':
596                         n = lp_name(module_id);
597                         break;
598                 case 't':
599                         n = timestring(time(NULL));
600                         break;
601                 case 'P':
602                         n = module_dir;
603                         break;
604                 case 'u':
605                         n = auth_user;
606                         break;
607                 case 'b':
608                         if (am_sender) {
609                                 b = stats.total_written -
610                                         initial_stats->total_written;
611                         } else {
612                                 b = stats.total_read -
613                                         initial_stats->total_read;
614                         }
615                         strlcat(fmt, ".0f", sizeof fmt);
616                         snprintf(buf2, sizeof buf2, fmt, (double)b);
617                         n = buf2;
618                         break;
619                 case 'c':
620                         if (!am_sender) {
621                                 b = stats.total_written -
622                                         initial_stats->total_written;
623                         } else {
624                                 b = stats.total_read -
625                                         initial_stats->total_read;
626                         }
627                         strlcat(fmt, ".0f", sizeof fmt);
628                         snprintf(buf2, sizeof buf2, fmt, (double)b);
629                         n = buf2;
630                         break;
631                 case 'i':
632                         if (iflags & ITEM_DELETED) {
633                                 n = "*deleting  ";
634                                 break;
635                         }
636                         n  = c = buf2 + MAXPATHLEN - 32;
637                         c[0] = iflags & ITEM_LOCAL_CHANGE
638                               ? iflags & ITEM_XNAME_FOLLOWS ? 'h' : 'c'
639                              : !(iflags & ITEM_TRANSFER) ? '.'
640                              : !local_server && *op == 's' ? '<' : '>';
641                         if (S_ISLNK(file->mode)) {
642                                 c[1] = 'L';
643                                 c[3] = '.';
644                                 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
645                                      : !preserve_times || !receiver_symlink_times
646                                     || (iflags & ITEM_REPORT_TIMEFAIL) ? 'T' : 't';
647                         } else {
648                                 c[1] = S_ISDIR(file->mode) ? 'd'
649                                      : IS_SPECIAL(file->mode) ? 'S'
650                                      : IS_DEVICE(file->mode) ? 'D' : 'f';
651                                 c[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
652                                 c[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
653                                      : !preserve_times ? 'T' : 't';
654                         }
655                         c[2] = !(iflags & ITEM_REPORT_CHANGE) ? '.' : 'c';
656                         c[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
657                         c[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
658                         c[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
659                         c[8] = !(iflags & ITEM_REPORT_ATIME) ? '.' : 'u';
660                         c[9] = !(iflags & ITEM_REPORT_ACL) ? '.' : 'a';
661                         c[10] = !(iflags & ITEM_REPORT_XATTR) ? '.' : 'x';
662                         c[11] = '\0';
663
664                         if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
665                                 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
666                                 int i;
667                                 for (i = 2; c[i]; i++)
668                                         c[i] = ch;
669                         } else if (c[0] == '.' || c[0] == 'h' || c[0] == 'c') {
670                                 int i;
671                                 for (i = 2; c[i]; i++) {
672                                         if (c[i] != '.')
673                                                 break;
674                                 }
675                                 if (!c[i]) {
676                                         for (i = 2; c[i]; i++)
677                                                 c[i] = ' ';
678                                 }
679                         }
680                         break;
681                 }
682
683                 /* "n" is the string to be inserted in place of this % code. */
684                 if (!n)
685                         continue;
686                 if (n != buf2 && fmt[1]) {
687                         strlcat(fmt, "s", sizeof fmt);
688                         snprintf(buf2, sizeof buf2, fmt, n);
689                         n = buf2;
690                 }
691                 len = strlen(n);
692
693                 /* Subtract the length of the escape from the string's size. */
694                 total -= p - s + 1;
695
696                 if (len + total >= (size_t)sizeof buf) {
697                         rprintf(FERROR,
698                                 "buffer overflow expanding %%%c -- exiting\n",
699                                 p[0]);
700                         exit_cleanup(RERR_MESSAGEIO);
701                 }
702
703                 /* Shuffle the rest of the string along to make space for n */
704                 if (len != (size_t)(p - s + 1))
705                         memmove(s + len, p + 1, total - (s - buf) + 1);
706                 total += len;
707
708                 /* Insert the contents of string "n", but NOT its null. */
709                 if (len)
710                         memcpy(s, n, len);
711
712                 /* Skip over inserted string; continue looking */
713                 p = s + len;
714         }
715
716         rwrite(code, buf, total, 0);
717 }
718
719 /* Return 1 if the format escape is in the log-format string (e.g. look for
720  * the 'b' in the "%9b" format escape). */
721 int log_format_has(const char *format, char esc)
722 {
723         const char *p;
724
725         if (!format)
726                 return 0;
727
728         for (p = format; (p = strchr(p, '%')) != NULL; ) {
729                 if (*++p == '-')
730                         p++;
731                 while (isDigit(p))
732                         p++;
733                 if (!*p)
734                         break;
735                 if (*p == esc)
736                         return 1;
737         }
738         return 0;
739 }
740
741 /* Log the transfer of a file.  If the code is FCLIENT, the output just goes
742  * to stdout.  If it is FLOG, it just goes to the log file.  Otherwise we
743  * output to both. */
744 void log_item(enum logcode code, struct file_struct *file,
745               struct stats *initial_stats, int iflags, const char *hlink)
746 {
747         const char *s_or_r = am_sender ? "send" : "recv";
748
749         if (code != FLOG && stdout_format && !am_server) {
750                 log_formatted(FCLIENT, stdout_format, s_or_r,
751                               file, NULL, initial_stats, iflags, hlink);
752         }
753         if (code != FCLIENT && logfile_format && *logfile_format) {
754                 log_formatted(FLOG, logfile_format, s_or_r,
755                               file, NULL, initial_stats, iflags, hlink);
756         }
757 }
758
759 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
760                     const char *buf)
761 {
762         int significant_flags = iflags & SIGNIFICANT_ITEM_FLAGS;
763         int see_item = itemizing && (significant_flags || *buf
764                 || stdout_format_has_i > 1 || (verbose > 1 && stdout_format_has_i));
765         int local_change = iflags & ITEM_LOCAL_CHANGE && significant_flags;
766         if (am_server) {
767                 if (logfile_name && !dry_run && see_item
768                  && (significant_flags || logfile_format_has_i))
769                         log_item(FLOG, file, &stats, iflags, buf);
770         } else if (see_item || local_change || *buf
771             || (S_ISDIR(file->mode) && significant_flags)) {
772                 enum logcode code = significant_flags || logfile_format_has_i ? FINFO : FCLIENT;
773                 log_item(code, file, &stats, iflags, buf);
774         }
775 }
776
777 void log_delete(const char *fname, int mode)
778 {
779         static struct {
780                 union file_extras ex[4]; /* just in case... */
781                 struct file_struct file;
782         } x;
783         int len = strlen(fname);
784         const char *fmt;
785
786         x.file.mode = mode;
787
788         if (!verbose && !stdout_format)
789                 ;
790         else if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
791                 if (S_ISDIR(mode))
792                         len++; /* directories include trailing null */
793                 send_msg(MSG_DELETED, fname, len, am_generator);
794         } else {
795                 fmt = stdout_format_has_o_or_i ? stdout_format : "deleting %n";
796                 log_formatted(FCLIENT, fmt, "del.", &x.file, fname, &stats,
797                               ITEM_DELETED, NULL);
798         }
799
800         if (!logfile_name || dry_run || !logfile_format)
801                 return;
802
803         fmt = logfile_format_has_o_or_i ? logfile_format : "deleting %n";
804         log_formatted(FLOG, fmt, "del.", &x.file, fname, &stats, ITEM_DELETED, NULL);
805 }
806
807 /*
808  * Called when the transfer is interrupted for some reason.
809  *
810  * Code is one of the RERR_* codes from errcode.h, or terminating
811  * successfully.
812  */
813 void log_exit(int code, const char *file, int line)
814 {
815         if (code == 0) {
816                 rprintf(FLOG,"sent %.0f bytes  received %.0f bytes  total size %.0f\n",
817                         (double)stats.total_written,
818                         (double)stats.total_read,
819                         (double)stats.total_size);
820         } else if (am_server != 2) {
821                 const char *name;
822
823                 name = rerr_name(code);
824                 if (!name)
825                         name = "unexplained error";
826
827                 /* VANISHED is not an error, only a warning */
828                 if (code == RERR_VANISHED) {
829                         rprintf(FWARNING, "rsync warning: %s (code %d) at %s(%d) [%s=%s]\n",
830                                 name, code, file, line, who_am_i(), RSYNC_VERSION);
831                 } else {
832                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d) [%s=%s]\n",
833                                 name, code, file, line, who_am_i(), RSYNC_VERSION);
834                 }
835         }
836 }