- Make use of the new ITEM_* flags to mention when things were
[rsync/rsync.git] / log.c
1 /* -*- c-file-style: "linux"; -*-
2
3    Copyright (C) 1998-2001 by Andrew Tridgell <tridge@samba.org>
4    Copyright (C) 2000-2001 by Martin Pool <mbp@samba.org>
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 /*
22   Logging and utility functions.
23   tridge, May 1998
24
25   Mapping to human-readable messages added by Martin Pool
26   <mbp@samba.org>, Oct 2000.
27   */
28 #include "rsync.h"
29
30 extern int verbose;
31 extern int dry_run;
32 extern int am_daemon;
33 extern int am_server;
34 extern int am_sender;
35 extern int quiet;
36 extern int module_id;
37 extern int msg_fd_out;
38 extern int protocol_version;
39 extern int preserve_times;
40 extern int log_format_has_o_or_i;
41 extern int daemon_log_format_has_o_or_i;
42 extern char *auth_user;
43 extern char *log_format;
44
45 static int log_initialised;
46 static char *logfname;
47 static FILE *logfile;
48 struct stats stats;
49
50 int log_got_error = 0;
51
52 struct {
53         int code;
54         char const *name;
55 } const rerr_names[] = {
56         { RERR_SYNTAX     , "syntax or usage error" },
57         { RERR_PROTOCOL   , "protocol incompatibility" },
58         { RERR_FILESELECT , "errors selecting input/output files, dirs" },
59         { RERR_UNSUPPORTED, "requested action not supported" },
60         { RERR_STARTCLIENT, "error starting client-server protocol" },
61         { RERR_SOCKETIO   , "error in socket IO" },
62         { RERR_FILEIO     , "error in file IO" },
63         { RERR_STREAMIO   , "error in rsync protocol data stream" },
64         { RERR_MESSAGEIO  , "errors with program diagnostics" },
65         { RERR_IPC        , "error in IPC code" },
66         { RERR_SIGNAL     , "received SIGUSR1 or SIGINT" },
67         { RERR_WAITCHILD  , "some error returned by waitpid()" },
68         { RERR_MALLOC     , "error allocating core memory buffers" },
69         { RERR_PARTIAL    , "some files could not be transferred" },
70         { RERR_VANISHED   , "some files vanished before they could be transferred" },
71         { RERR_TIMEOUT    , "timeout in data send/receive" },
72         { RERR_CMD_FAILED , "remote shell failed" },
73         { RERR_CMD_KILLED , "remote shell killed" },
74         { RERR_CMD_RUN,     "remote command could not be run" },
75         { RERR_CMD_NOTFOUND, "remote command not found" },
76         { 0, NULL }
77 };
78
79
80
81 /*
82  * Map from rsync error code to name, or return NULL.
83  */
84 static char const *rerr_name(int code)
85 {
86         int i;
87         for (i = 0; rerr_names[i].name; i++) {
88                 if (rerr_names[i].code == code)
89                         return rerr_names[i].name;
90         }
91         return NULL;
92 }
93
94
95 static void logit(int priority, char *buf)
96 {
97         if (logfname) {
98                 if (!logfile)
99                         log_open();
100                 fprintf(logfile,"%s [%d] %s",
101                         timestring(time(NULL)), (int)getpid(), buf);
102                 fflush(logfile);
103         } else {
104                 syslog(priority, "%s", buf);
105         }
106 }
107
108 void log_init(void)
109 {
110         int options = LOG_PID;
111         time_t t;
112
113         if (log_initialised)
114                 return;
115         log_initialised = 1;
116
117         /* this looks pointless, but it is needed in order for the
118          * C library on some systems to fetch the timezone info
119          * before the chroot */
120         t = time(NULL);
121         localtime(&t);
122
123         /* optionally use a log file instead of syslog */
124         logfname = lp_log_file();
125         if (logfname) {
126                 if (*logfname) {
127                         log_open();
128                         return;
129                 }
130                 logfname = NULL;
131         }
132
133 #ifdef LOG_NDELAY
134         options |= LOG_NDELAY;
135 #endif
136
137 #ifdef LOG_DAEMON
138         openlog("rsyncd", options, lp_syslog_facility());
139 #else
140         openlog("rsyncd", options);
141 #endif
142
143 #ifndef LOG_NDELAY
144         logit(LOG_INFO,"rsyncd started\n");
145 #endif
146 }
147
148 void log_open(void)
149 {
150         if (logfname && !logfile) {
151                 extern int orig_umask;
152                 int old_umask = umask(022 | orig_umask);
153                 logfile = fopen(logfname, "a");
154                 umask(old_umask);
155                 if (!logfile) {
156                         am_daemon = 0; /* avoid trying to log again */
157                         rsyserr(FERROR, errno, "fopen() of log-file failed");
158                         exit_cleanup(RERR_FILESELECT);
159                 }
160         }
161 }
162
163 void log_close(void)
164 {
165         if (logfile) {
166                 fclose(logfile);
167                 logfile = NULL;
168         }
169 }
170
171 /* this is the underlying (unformatted) rsync debugging function. Call
172  * it with FINFO, FERROR or FLOG */
173 void rwrite(enum logcode code, char *buf, int len)
174 {
175         FILE *f = NULL;
176         /* recursion can happen with certain fatal conditions */
177
178         if (quiet && code == FINFO)
179                 return;
180
181         if (len < 0)
182                 exit_cleanup(RERR_MESSAGEIO);
183
184         buf[len] = 0;
185
186         if (am_server && msg_fd_out >= 0) {
187                 /* Pass the message to our sibling. */
188                 send_msg((enum msgcode)code, buf, len);
189                 return;
190         }
191
192         if (code == FCLIENT)
193                 code = FINFO;
194         else if (am_daemon) {
195                 static int in_block;
196                 char msg[2048];
197                 int priority = code == FERROR ? LOG_WARNING : LOG_INFO;
198
199                 if (in_block)
200                         return;
201                 in_block = 1;
202                 if (!log_initialised)
203                         log_init();
204                 strlcpy(msg, buf, MIN((int)sizeof msg, len + 1));
205                 logit(priority, msg);
206                 in_block = 0;
207
208                 if (code == FLOG || !am_server)
209                         return;
210         } else if (code == FLOG)
211                 return;
212
213         if (am_server) {
214                 /* Pass the message to the non-server side. */
215                 if (io_multiplex_write((enum msgcode)code, buf, len))
216                         return;
217                 if (am_daemon) {
218                         /* TODO: can we send the error to the user somehow? */
219                         return;
220                 }
221         }
222
223         if (code == FERROR) {
224                 log_got_error = 1;
225                 f = stderr;
226         }
227
228         if (code == FINFO)
229                 f = am_server ? stderr : stdout;
230
231         if (!f)
232                 exit_cleanup(RERR_MESSAGEIO);
233
234         if (fwrite(buf, len, 1, f) != 1)
235                 exit_cleanup(RERR_MESSAGEIO);
236
237         if (buf[len-1] == '\r' || buf[len-1] == '\n')
238                 fflush(f);
239 }
240                 
241
242 /* This is the rsync debugging function. Call it with FINFO, FERROR or
243  * FLOG. */
244 void rprintf(enum logcode code, const char *format, ...)
245 {
246         va_list ap;
247         char buf[MAXPATHLEN+512];
248         size_t len;
249
250         va_start(ap, format);
251         len = vsnprintf(buf, sizeof buf, format, ap);
252         va_end(ap);
253
254         /* Deal with buffer overruns.  Instead of panicking, just
255          * truncate the resulting string.  (Note that configure ensures
256          * that we have a vsnprintf() that doesn't ever return -1.) */
257         if (len > sizeof buf - 1) {
258                 const char ellipsis[] = "[...]";
259
260                 /* Reset length, and zero-terminate the end of our buffer */
261                 len = sizeof buf - 1;
262                 buf[len] = '\0';
263
264                 /* Copy the ellipsis to the end of the string, but give
265                  * us one extra character:
266                  *
267                  *                  v--- null byte at buf[sizeof buf - 1]
268                  *        abcdefghij0
269                  *     -> abcd[...]00  <-- now two null bytes at end
270                  *
271                  * If the input format string has a trailing newline,
272                  * we copy it into that extra null; if it doesn't, well,
273                  * all we lose is one byte.  */
274                 strncpy(buf+len-sizeof ellipsis, ellipsis, sizeof ellipsis);
275                 if (format[strlen(format)-1] == '\n') {
276                         buf[len-1] = '\n';
277                 }
278         }
279
280         rwrite(code, buf, len);
281 }
282
283
284 /* This is like rprintf, but it also tries to print some
285  * representation of the error code.  Normally errcode = errno.
286  *
287  * Unlike rprintf, this always adds a newline and there should not be
288  * one in the format string.
289  *
290  * Note that since strerror might involve dynamically loading a
291  * message catalog we need to call it once before chroot-ing. */
292 void rsyserr(enum logcode code, int errcode, const char *format, ...)
293 {
294         va_list ap;
295         char buf[MAXPATHLEN+512];
296         size_t len;
297
298         strcpy(buf, RSYNC_NAME ": ");
299         len = (sizeof RSYNC_NAME ": ") - 1;
300
301         va_start(ap, format);
302         len += vsnprintf(buf + len, sizeof buf - len, format, ap);
303         va_end(ap);
304
305         if (len < sizeof buf) {
306                 len += snprintf(buf + len, sizeof buf - len,
307                                 ": %s (%d)\n", strerror(errcode), errcode);
308         }
309         if (len >= sizeof buf)
310                 exit_cleanup(RERR_MESSAGEIO);
311
312         rwrite(code, buf, len);
313 }
314
315
316
317 void rflush(enum logcode code)
318 {
319         FILE *f = NULL;
320         
321         if (am_daemon) {
322                 return;
323         }
324
325         if (code == FLOG) {
326                 return;
327         }
328
329         if (code == FERROR) {
330                 f = stderr;
331         }
332
333         if (code == FINFO) {
334                 if (am_server)
335                         f = stderr;
336                 else
337                         f = stdout;
338         }
339
340         if (!f) exit_cleanup(RERR_MESSAGEIO);
341         fflush(f);
342 }
343
344
345
346 /* a generic logging routine for send/recv, with parameter
347  * substitiution */
348 static void log_formatted(enum logcode code, char *format, char *op,
349                           struct file_struct *file, struct stats *initial_stats,
350                           int iflags, char *hlink)
351 {
352         char buf[MAXPATHLEN+1024];
353         char buf2[MAXPATHLEN];
354         char *p, *n;
355         size_t len, total;
356         int64 b;
357
358         /* We expand % codes one by one in place in buf.  We don't
359          * copy in the terminating nul of the inserted strings, but
360          * rather keep going until we reach the nul of the format. */
361         total = strlcpy(buf, format, sizeof buf);
362         
363         for (p = buf; (p = strchr(p, '%')) != NULL && p[1]; ) {
364                 n = NULL;
365
366                 switch (p[1]) {
367                 case 'h': if (am_daemon) n = client_name(0); break;
368                 case 'a': if (am_daemon) n = client_addr(0); break;
369                 case 'l':
370                         snprintf(buf2, sizeof buf2, "%.0f",
371                                  (double)file->length);
372                         n = buf2;
373                         break;
374                 case 'p':
375                         snprintf(buf2, sizeof buf2, "%d",
376                                  (int)getpid());
377                         n = buf2;
378                         break;
379                 case 'o': n = op; break;
380                 case 'f':
381                         pathjoin(buf2, sizeof buf2,
382                             am_sender && file->dir.root ? file->dir.root : "",
383                             safe_fname(f_name(file)));
384                         clean_fname(buf2, 0);
385                         n = buf2;
386                         if (*n == '/') n++;
387                         break;
388                 case 'n':
389                         n = (char*)safe_fname(f_name(file));
390                         if (S_ISDIR(file->mode)) {
391                                 /* The buffer from safe_fname() has more
392                                  * room than MAXPATHLEN, so this is safe. */
393                                 strcat(n, "/");
394                         }
395                         break;
396                 case 'L':
397                         if (hlink && *hlink) {
398                                 snprintf(buf2, sizeof buf2, " => %s",
399                                          safe_fname(hlink));
400                                 n = buf2;
401                         } else if (S_ISLNK(file->mode) && file->u.link) {
402                                 snprintf(buf2, sizeof buf2, " -> %s",
403                                          safe_fname(file->u.link));
404                                 n = buf2;
405                         } else
406                                 n = "";
407                         break;
408                 case 'm': n = lp_name(module_id); break;
409                 case 't': n = timestring(time(NULL)); break;
410                 case 'P': n = lp_path(module_id); break;
411                 case 'u': n = auth_user; break;
412                 case 'b':
413                         if (am_sender) {
414                                 b = stats.total_written -
415                                         initial_stats->total_written;
416                         } else {
417                                 b = stats.total_read -
418                                         initial_stats->total_read;
419                         }
420                         snprintf(buf2, sizeof buf2, "%.0f", (double)b);
421                         n = buf2;
422                         break;
423                 case 'c':
424                         if (!am_sender) {
425                                 b = stats.total_written -
426                                         initial_stats->total_written;
427                         } else {
428                                 b = stats.total_read -
429                                         initial_stats->total_read;
430                         }
431                         snprintf(buf2, sizeof buf2, "%.0f", (double)b);
432                         n = buf2;
433                         break;
434                 case 'i':
435                         if (iflags & ITEM_DELETED) {
436                                 n = "deleting";
437                                 break;
438                         }
439                         n = buf2;
440                         n[0] = iflags & ITEM_HARD_LINKED ? 'h'
441                              : iflags & ITEM_LOCAL_CHANGE ? 'c'
442                              : !(iflags & ITEM_TRANSFER) ? '.'
443                              : *op == 's' ? '>' : '<';
444                         n[1] = S_ISDIR(file->mode) ? 'd'
445                              : IS_DEVICE(file->mode) ? 'D'
446                              : S_ISLNK(file->mode) ? 'L' : 'f';
447                         n[2] = !(iflags & ITEM_REPORT_CHECKSUM) ? '.' : 'c';
448                         n[3] = !(iflags & ITEM_REPORT_SIZE) ? '.' : 's';
449                         n[4] = !(iflags & ITEM_REPORT_TIME) ? '.'
450                              : !preserve_times || IS_DEVICE(file->mode)
451                                                || S_ISLNK(file->mode) ? 'T' : 't';
452                         n[5] = !(iflags & ITEM_REPORT_PERMS) ? '.' : 'p';
453                         n[6] = !(iflags & ITEM_REPORT_OWNER) ? '.' : 'o';
454                         n[7] = !(iflags & ITEM_REPORT_GROUP) ? '.' : 'g';
455                         n[8] = !(iflags & ITEM_REPORT_XATTRS) ? '.' : 'a';
456                         n[9] = '\0';
457
458                         if (iflags & (ITEM_IS_NEW|ITEM_MISSING_DATA)) {
459                                 char ch = iflags & ITEM_IS_NEW ? '+' : '?';
460                                 int i;
461                                 for (i = 2; n[i]; i++)
462                                         n[i] = ch;
463                         } else if (!(iflags & (ITEM_TRANSFER|ITEM_LOCAL_CHANGE))) {
464                                 int i;
465                                 for (i = 2; n[i]; i++) {
466                                         if (n[i] != '.')
467                                                 break;
468                                 }
469                                 if (!n[i]) {
470                                         for (i = 2; n[i]; i++)
471                                                 n[i] = ' ';
472                                         if (n[0] == '.')
473                                                 n[0] = '=';
474                                 }
475                         }
476                         break;
477                 }
478
479                 /* n is the string to be inserted in place of this %
480                  * code; len is its length not including the trailing
481                  * NUL */
482                 if (!n) {
483                         p += 2;
484                         continue;
485                 }
486
487                 len = strlen(n);
488
489                 if (len + total - 2 >= sizeof buf) {
490                         rprintf(FERROR,
491                                 "buffer overflow expanding %%%c -- exiting\n",
492                                 p[0]);
493                         exit_cleanup(RERR_MESSAGEIO);
494                 }
495
496                 /* Shuffle the rest of the string along to make space for n */
497                 if (len != 2)
498                         memmove(p + len, p + 2, total - (p + 2 - buf) + 1);
499                 total += len - 2;
500
501                 /* Insert the contents of string "n", but NOT its nul. */
502                 if (len)
503                         memcpy(p, n, len);
504
505                 /* Skip over inserted string; continue looking */
506                 p += len;
507         }
508
509         rprintf(code, "%s\n", buf);
510 }
511
512 /* log the transfer of a file */
513 void log_item(struct file_struct *file, struct stats *initial_stats,
514               int iflags, char *hlink)
515 {
516         char *s_or_r = am_sender ? "send" : "recv";
517
518         if (lp_transfer_logging(module_id)) {
519                 log_formatted(FLOG, lp_log_format(module_id), s_or_r,
520                               file, initial_stats, iflags, hlink);
521         } else if (log_format && !am_server) {
522                 log_formatted(FINFO, log_format, s_or_r,
523                               file, initial_stats, iflags, hlink);
524         }
525 }
526
527 void maybe_log_item(struct file_struct *file, int iflags, int itemizing,
528                     char *buf)
529 {
530         int see_item = itemizing && (iflags || verbose > 1);
531         if (am_server) {
532                 if (am_daemon && !dry_run && see_item)
533                         log_item(file, &stats, iflags, buf);
534         } else if (see_item || iflags & ITEM_LOCAL_CHANGE || *buf
535             || (S_ISDIR(file->mode) && iflags & ITEM_REPORT_TIME))
536                 log_item(file, &stats, iflags, buf);
537 }
538
539 void log_delete(char *fname, int mode)
540 {
541         static struct file_struct file;
542         int len = strlen(fname);
543         char *fmt;
544
545         file.mode = mode;
546         file.basename = fname;
547
548         if (!verbose && !log_format)
549                 ;
550         else if (am_server && protocol_version >= 29 && len < MAXPATHLEN) {
551                 if (S_ISDIR(mode))
552                         len++; /* directories include trailing null */
553                 send_msg(MSG_DELETED, fname, len);
554         } else {
555                 fmt = log_format_has_o_or_i ? log_format : "%i %n";
556                 log_formatted(FCLIENT, fmt, "del.", &file, &stats,
557                               ITEM_DELETED, NULL);
558         }
559
560         if (!am_daemon || dry_run || !lp_transfer_logging(module_id))
561                 return;
562
563         fmt = daemon_log_format_has_o_or_i ? lp_log_format(module_id) : "%i %n";
564         log_formatted(FLOG, fmt, "del.", &file, &stats, ITEM_DELETED, NULL);
565 }
566
567
568 /*
569  * Called when the transfer is interrupted for some reason.
570  *
571  * Code is one of the RERR_* codes from errcode.h, or terminating
572  * successfully.
573  */
574 void log_exit(int code, const char *file, int line)
575 {
576         if (code == 0) {
577                 rprintf(FLOG,"sent %.0f bytes  received %.0f bytes  total size %.0f\n",
578                         (double)stats.total_written,
579                         (double)stats.total_read,
580                         (double)stats.total_size);
581         } else {
582                 const char *name;
583
584                 name = rerr_name(code);
585                 if (!name)
586                         name = "unexplained error";
587
588                 /* VANISHED is not an error, only a warning */
589                 if (code == RERR_VANISHED) {
590                         rprintf(FINFO, "rsync warning: %s (code %d) at %s(%d)\n", 
591                                 name, code, file, line);
592                 } else {
593                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d)\n",
594                                 name, code, file, line);
595                 }
596         }
597 }