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