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