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