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