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