- Improved rsyserr() to prefix RSYNC_NAME (as the TODO requested),
[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 am_daemon;
31 extern int am_server;
32 extern int am_sender;
33 extern int quiet;
34 extern int module_id;
35 extern int msg_fd_out;
36 extern char *auth_user;
37 extern char *log_format;
38
39 static int log_initialised;
40 static char *logfname;
41 static FILE *logfile;
42 struct stats stats;
43
44 int log_got_error = 0;
45
46 struct {
47         int code;
48         char const *name;
49 } const rerr_names[] = {
50         { RERR_SYNTAX     , "syntax or usage error" },
51         { RERR_PROTOCOL   , "protocol incompatibility" },
52         { RERR_FILESELECT , "errors selecting input/output files, dirs" },
53         { RERR_UNSUPPORTED, "requested action not supported" },
54         { RERR_STARTCLIENT, "error starting client-server protocol" },
55         { RERR_SOCKETIO   , "error in socket IO" },
56         { RERR_FILEIO     , "error in file IO" },
57         { RERR_STREAMIO   , "error in rsync protocol data stream" },
58         { RERR_MESSAGEIO  , "errors with program diagnostics" },
59         { RERR_IPC        , "error in IPC code" },
60         { RERR_SIGNAL     , "received SIGUSR1 or SIGINT" },
61         { RERR_WAITCHILD  , "some error returned by waitpid()" },
62         { RERR_MALLOC     , "error allocating core memory buffers" },
63         { RERR_PARTIAL    , "some files could not be transferred" },
64         { RERR_VANISHED   , "some files vanished before they could be transfered" },
65         { RERR_TIMEOUT    , "timeout in data send/receive" },
66         { RERR_CMD_FAILED , "remote shell failed" },
67         { RERR_CMD_KILLED , "remote shell killed" },
68         { RERR_CMD_RUN,     "remote command could not be run" },
69         { RERR_CMD_NOTFOUND, "remote command not found" },
70         { 0, NULL }
71 };
72
73
74
75 /*
76  * Map from rsync error code to name, or return NULL.
77  */
78 static char const *rerr_name(int code)
79 {
80         int i;
81         for (i = 0; rerr_names[i].name; i++) {
82                 if (rerr_names[i].code == code)
83                         return rerr_names[i].name;
84         }
85         return NULL;
86 }
87
88
89 static void logit(int priority, char *buf)
90 {
91         if (logfname) {
92                 if (!logfile)
93                         log_open();
94                 fprintf(logfile,"%s [%d] %s",
95                         timestring(time(NULL)), (int)getpid(), buf);
96                 fflush(logfile);
97         } else {
98                 syslog(priority, "%s", buf);
99         }
100 }
101
102 void log_init(void)
103 {
104         int options = LOG_PID;
105         time_t t;
106
107         if (log_initialised) return;
108         log_initialised = 1;
109
110         /* this looks pointless, but it is needed in order for the
111          * C library on some systems to fetch the timezone info
112          * before the chroot */
113         t = time(NULL);
114         localtime(&t);
115
116         /* optionally use a log file instead of syslog */
117         logfname = lp_log_file();
118         if (logfname) {
119                 if (*logfname) {
120                         log_open();
121                         return;
122                 }
123                 logfname = NULL;
124         }
125
126 #ifdef LOG_NDELAY
127         options |= LOG_NDELAY;
128 #endif
129
130 #ifdef LOG_DAEMON
131         openlog("rsyncd", options, lp_syslog_facility());
132 #else
133         openlog("rsyncd", options);
134 #endif
135
136 #ifndef LOG_NDELAY
137         logit(LOG_INFO,"rsyncd started\n");
138 #endif
139 }
140
141 void log_open(void)
142 {
143         if (logfname && !logfile) {
144                 extern int orig_umask;
145                 int old_umask = umask(022 | orig_umask);
146                 logfile = fopen(logfname, "a");
147                 umask(old_umask);
148         }
149 }
150
151 void log_close(void)
152 {
153         if (logfile) {
154                 fclose(logfile);
155                 logfile = NULL;
156         }
157 }
158
159 /* this is the underlying (unformatted) rsync debugging function. Call
160  * it with FINFO, FERROR or FLOG */
161 void rwrite(enum logcode code, char *buf, int len)
162 {
163         FILE *f = NULL;
164         /* recursion can happen with certain fatal conditions */
165
166         if (quiet && code == FINFO)
167                 return;
168
169         if (len < 0)
170                 exit_cleanup(RERR_MESSAGEIO);
171
172         buf[len] = 0;
173
174         if (code == FLOG) {
175                 if (am_daemon) logit(LOG_INFO, buf);
176                 return;
177         }
178
179         if (am_server) {
180                 /* Pass it to non-server side, perhaps through our sibling. */
181                 if (msg_fd_out >= 0) {
182                         send_msg((enum msgcode)code, buf, len);
183                         return;
184                 }
185                 if (!am_daemon
186                     && io_multiplex_write((enum msgcode)code, buf, len))
187                         return;
188         }
189
190         /* otherwise, if in daemon mode and either we are not a server
191          *  (that is, we are not running --daemon over a remote shell) or
192          *  the log has already been initialised, log the message on this
193          *  side because we don't want the client to see most errors for
194          *  security reasons.  We do want early messages when running daemon
195          *  mode over a remote shell to go to the remote side; those will
196          *  fall through to the next case.
197          * Note that this is only for the time before multiplexing is enabled.
198          */
199         if (am_daemon && (!am_server || log_initialised)) {
200                 static int depth;
201                 int priority = LOG_INFO;
202                 if (code == FERROR) priority = LOG_WARNING;
203
204                 if (depth) return;
205
206                 depth++;
207
208                 log_init();
209                 logit(priority, buf);
210
211                 depth--;
212                 return;
213         }
214
215         if (code == FERROR) {
216                 log_got_error = 1;
217                 f = stderr;
218         }
219
220         if (code == FINFO) {
221                 if (am_server)
222                         f = stderr;
223                 else
224                         f = stdout;
225         }
226
227         if (!f) exit_cleanup(RERR_MESSAGEIO);
228
229         if (fwrite(buf, len, 1, f) != 1) exit_cleanup(RERR_MESSAGEIO);
230
231         if (buf[len-1] == '\r' || buf[len-1] == '\n') 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)
344 {
345         char buf[1024];
346         char buf2[1024];
347         char *p, *s, *n;
348         size_t l;
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          * Just to make sure we don't clobber that nul and therefore
355          * accidentally keep going, we zero the buffer now. */
356         l = strlcpy(buf, format, sizeof buf);
357         if (l < sizeof buf)
358                 memset(buf + l, 0, sizeof buf - l);
359         
360         for (s = &buf[0]; s && (p = strchr(s,'%')); ) {
361                 n = NULL;
362                 s = p + 1;
363
364                 switch (p[1]) {
365                 case 'h': if (am_daemon) n = client_name(0); break;
366                 case 'a': if (am_daemon) n = client_addr(0); break;
367                 case 'l':
368                         snprintf(buf2,sizeof(buf2),"%.0f",
369                                  (double)file->length);
370                         n = buf2;
371                         break;
372                 case 'p':
373                         snprintf(buf2,sizeof(buf2),"%d",
374                                  (int)getpid());
375                         n = buf2;
376                         break;
377                 case 'o': n = op; break;
378                 case 'f':
379                         pathjoin(buf2, sizeof buf2,
380                                  file->basedir ? file->basedir : "",
381                                  f_name(file));
382                         clean_fname(buf2);
383                         n = buf2;
384                         if (*n == '/') n++;
385                         break;
386                 case 'm': n = lp_name(module_id); break;
387                 case 't': n = timestring(time(NULL)); break;
388                 case 'P': n = lp_path(module_id); break;
389                 case 'u': n = auth_user; break;
390                 case 'b':
391                         if (am_sender) {
392                                 b = stats.total_written -
393                                         initial_stats->total_written;
394                         } else {
395                                 b = stats.total_read -
396                                         initial_stats->total_read;
397                         }
398                         snprintf(buf2,sizeof(buf2),"%.0f", (double)b);
399                         n = buf2;
400                         break;
401                 case 'c':
402                         if (!am_sender) {
403                                 b = stats.total_written -
404                                         initial_stats->total_written;
405                         } else {
406                                 b = stats.total_read -
407                                         initial_stats->total_read;
408                         }
409                         snprintf(buf2,sizeof(buf2),"%.0f", (double)b);
410                         n = buf2;
411                         break;
412                 }
413
414                 /* n is the string to be inserted in place of this %
415                  * code; l is its length not including the trailing
416                  * NUL */
417                 if (!n)
418                         continue;
419
420                 l = strlen(n);
421
422                 if (l + ((int)(s - &buf[0])) >= sizeof(buf)) {
423                         rprintf(FERROR,"buffer overflow expanding %%%c - exiting\n",
424                                 p[0]);
425                         exit_cleanup(RERR_MESSAGEIO);
426                 }
427
428                 /* Shuffle the rest of the string along to make space for n */
429                 if (l != 2) {
430                         memmove(s+(l-1), s+1, strlen(s+1)+1);
431                 }
432
433                 /* Copy in n but NOT its nul, because the format sting
434                  * probably continues after this. */
435                 memcpy(p, n, l);
436
437                 /* Skip over inserted string; continue looking */
438                 s = p+l;
439         }
440
441         rprintf(code,"%s\n", buf);
442 }
443
444 /* log the outgoing transfer of a file */
445 void log_send(struct file_struct *file, struct stats *initial_stats)
446 {
447         if (lp_transfer_logging(module_id)) {
448                 log_formatted(FLOG, lp_log_format(module_id), "send", file, initial_stats);
449         } else if (log_format && !am_server) {
450                 log_formatted(FINFO, log_format, "send", file, initial_stats);
451         }
452 }
453
454 /* log the incoming transfer of a file */
455 void log_recv(struct file_struct *file, struct stats *initial_stats)
456 {
457         if (lp_transfer_logging(module_id)) {
458                 log_formatted(FLOG, lp_log_format(module_id), "recv", file, initial_stats);
459         } else if (log_format && !am_server) {
460                 log_formatted(FINFO, log_format, "recv", file, initial_stats);
461         }
462 }
463
464
465
466
467 /*
468  * Called when the transfer is interrupted for some reason.
469  *
470  * Code is one of the RERR_* codes from errcode.h, or terminating
471  * successfully.
472  */
473 void log_exit(int code, const char *file, int line)
474 {
475         if (code == 0) {
476                 rprintf(FLOG,"wrote %.0f bytes  read %.0f bytes  total size %.0f\n",
477                         (double)stats.total_written,
478                         (double)stats.total_read,
479                         (double)stats.total_size);
480         } else {
481                 const char *name;
482
483                 name = rerr_name(code);
484                 if (!name)
485                         name = "unexplained error";
486
487                 /* VANISHED is not an error, only a warning */
488                 if (code == RERR_VANISHED) {
489                         rprintf(FINFO, "rsync warning: %s (code %d) at %s(%d)\n", 
490                                 name, code, file, line);
491                 } else {
492                         rprintf(FERROR, "rsync error: %s (code %d) at %s(%d)\n",
493                                 name, code, file, line);
494                 }
495         }
496 }