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