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