]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/logger.c
logger: write to fd 1 directly instead of /dev/tty. The latter cant be redirected
[netatalk.git] / libatalk / util / logger.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 /* =========================================================================
6
7 logger.c was written by Simon Bazley (sibaz@sibaz.com)
8
9 I believe libatalk is released under the L/GPL licence.
10 Just incase, it is, thats the licence I'm applying to this file.
11 Netatalk 2001 (c)
12
13 ========================================================================= */
14
15 #include <stdio.h>
16 #include <limits.h>
17 #include <stdarg.h>
18 #include <string.h>
19 #include <stdlib.h>
20 #include <syslog.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <sys/uio.h>
25 #include <unistd.h>
26 #include <sys/time.h>
27 #include <time.h>
28 #include <ctype.h>
29 #include <errno.h>
30
31 #include <atalk/boolean.h>
32 #include <atalk/util.h>
33
34 #include <atalk/logger.h>
35
36 #define OPEN_LOGS_AS_UID 0
37
38 #define COUNT_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
39
40 #define MAXLOGSIZE 512
41
42 #define LOGLEVEL_STRING_IDENTIFIERS { \
43   "LOG_NOTHING",                      \
44   "LOG_SEVERE",                       \
45   "LOG_ERROR",                        \
46   "LOG_WARN",                         \
47   "LOG_NOTE",                         \
48   "LOG_INFO",                         \
49   "LOG_DEBUG",                        \
50   "LOG_DEBUG6",                       \
51   "LOG_DEBUG7",                       \
52   "LOG_DEBUG8",                       \
53   "LOG_DEBUG9",                       \
54   "LOG_MAXDEBUG"}                        
55
56 /* these are the string identifiers corresponding to each logtype */
57 #define LOGTYPE_STRING_IDENTIFIERS { \
58   "Default",                         \
59   "Core",                            \
60   "Logger",                          \
61   "CNID",                            \
62   "AFPDaemon",                       \
63   "ATalkDaemon",                     \
64   "PAPDaemon",                       \
65   "UAMSDaemon",                      \
66   "Console",                         \
67   "end_of_list_marker"}              \
68
69 /* ========================================================================= 
70     Structure definitions
71    ========================================================================= */
72
73 /* Main log config */
74 typedef struct {
75     int            inited;                 /* file log config initialized ? */
76     int            filelogging;            /* Any level set to filelogging ? */
77                                            /* Deactivates syslog logging */
78     char           processname[16];
79     int            syslog_opened;          /* syslog opened ? */
80     int            facility;               /* syslog facility to use */
81     int            syslog_display_options;
82     enum loglevels syslog_level;           /* Log Level to send to syslog */
83     int            console;                /* if logging to console from a cli util */
84 } log_config_t;
85
86 /* This stores the config and options for one filelog type (e.g. logger, afpd etc.) */
87 typedef struct {
88     int            set;           /* set individually ? yes: changing default
89                                    * doesnt change it. no: it changes it.*/
90     char           *filename;     /* Name of file */
91     int            fd;            /* logfiles fd */
92     enum loglevels level;         /* Log Level to put in this file */
93     int            display_options;
94 } filelog_conf_t;
95
96 /* =========================================================================
97    Config
98    ========================================================================= */
99
100 /* Main log config container */
101 static log_config_t log_config = {
102     0,                  /* Initialized ? 0 = no */
103     0,                  /* No filelogging setup yet */
104     {0},                /* processname */
105     0,                  /* syslog opened ? */
106     logfacility_daemon,         /* syslog facility to use */
107     logoption_ndelay|logoption_pid, /* logging options for syslog */
108     0,                              /* log level for syslog */
109     0                               /* not logging to console */
110 };
111
112 /* Default log config: log nothing to files.
113    0:    not set individually
114    NULL: Name of file
115    -1:   logfiles fd
116    0:   Log Level
117    0:    Display options */
118 #define DEFAULT_LOG_CONFIG {0, NULL, -1, 0, 0}
119
120 static filelog_conf_t file_configs[logtype_end_of_list_marker] = {
121     DEFAULT_LOG_CONFIG, /* logtype_default */
122     DEFAULT_LOG_CONFIG, /* logtype_core */
123     DEFAULT_LOG_CONFIG, /* logtype_logger */
124     DEFAULT_LOG_CONFIG, /* logtype_cnid */
125     DEFAULT_LOG_CONFIG, /* logtype_afpd */
126     DEFAULT_LOG_CONFIG, /* logtype_atalkd */
127     DEFAULT_LOG_CONFIG, /* logtype_papd */
128     DEFAULT_LOG_CONFIG, /* logtype_uams */
129     DEFAULT_LOG_CONFIG  /* logtype_console */
130 };
131
132 /* These are used by the LOG macro to store __FILE__ and __LINE__ */
133 static const char *log_src_filename;
134 static int  log_src_linenumber;
135
136 /* Array to store text to list given a log type */
137 static const char *arr_logtype_strings[] =  LOGTYPE_STRING_IDENTIFIERS;
138 static const unsigned int num_logtype_strings = COUNT_ARRAY(arr_logtype_strings);
139
140 /* Array for charachters representing log severity in the log file */
141 static const char arr_loglevel_chars[] = {'-','S', 'E', 'W', 'N', 'I', 'D'};
142 static const unsigned int num_loglevel_chars = COUNT_ARRAY(arr_loglevel_chars);
143
144 static const char *arr_loglevel_strings[] = LOGLEVEL_STRING_IDENTIFIERS;
145 static const unsigned int num_loglevel_strings = COUNT_ARRAY(arr_loglevel_strings);
146
147 /* =========================================================================
148    Internal function definitions
149    ========================================================================= */
150
151 /*
152  * If filename == NULL its for syslog logging, otherwise its for file-logging.
153  * "unsetuplog" calls with loglevel == NULL.
154  * loglevel == NULL means:
155  *    if logtype == default
156  *       disable logging
157  *    else
158  *       set to default logging
159  */
160
161 /* -[un]setuplog <logtype> <loglevel> [<filename>]*/
162 static void setuplog_internal(const char *loglevel, const char *logtype, const char *filename)
163 {
164     unsigned int typenum, levelnum;
165
166     /* Parse logtype */
167     for( typenum=0; typenum < num_logtype_strings; typenum++) {
168         if (strcasecmp(logtype, arr_logtype_strings[typenum]) == 0)
169             break;
170     }
171     if (typenum >= num_logtype_strings) {
172         return;
173     }
174
175     /* Parse loglevel */
176     if (loglevel == NULL) {
177         levelnum = 0;
178     } else {
179         for(levelnum=1; levelnum < num_loglevel_strings; levelnum++) {
180             if (strcasecmp(loglevel, arr_loglevel_strings[levelnum]) == 0)
181                 break;
182         }
183         if (levelnum >= num_loglevel_strings) {
184             return;
185         }
186     }
187
188     /* is this a syslog setup or a filelog setup ? */
189     if (filename == NULL) {
190         /* must be syslog */
191         syslog_setup(levelnum, 0,
192                      log_config.syslog_display_options,
193                      log_config.facility);
194     } else {
195         /* this must be a filelog */
196         log_setup(filename, levelnum, typenum);
197     }
198
199     return;
200 }
201
202 static void generate_message_details(char *message_details_buffer,
203                                      int message_details_buffer_length,
204                                      int display_options,
205                                      enum loglevels loglevel, enum logtypes logtype)
206 {
207     char   *ptr = message_details_buffer;
208     int    templen;
209     int    len = message_details_buffer_length;
210     struct timeval tv;
211     pid_t  pid;
212
213     *ptr = 0;
214
215     /* Print time */
216     gettimeofday(&tv, NULL);
217     strftime(ptr, len, "%b %d %H:%M:%S.", localtime(&tv.tv_sec));
218     templen = strlen(ptr);
219     len -= templen;
220     ptr += templen;
221
222     templen = snprintf(ptr, len, "%06u ", (int)tv.tv_usec);
223     if (templen == -1 || templen >= len)
224         return;
225         
226     len -= templen;
227     ptr += templen;
228
229     /* Process name &&  PID */
230     pid = getpid();
231     templen = snprintf(ptr, len, "%s[%d]", log_config.processname, pid);
232     if (templen == -1 || templen >= len)
233         return;
234     len -= templen;
235     ptr += templen;
236
237     /* Source info ? */
238     if ( ! (display_options & logoption_nsrcinfo)) {
239         char *basename = strrchr(log_src_filename, '/');
240         if (basename)
241             templen = snprintf(ptr, len, " {%s:%d}", basename + 1, log_src_linenumber);
242         else
243             templen = snprintf(ptr, len, " {%s:%d}", log_src_filename, log_src_linenumber);
244         if (templen == -1 || templen >= len)
245             return;
246         len -= templen;
247         ptr += templen;
248     }
249
250     /* Errorlevel */
251     if (loglevel >= (num_loglevel_chars - 1))
252         templen = snprintf(ptr, len,  " (D%d:", loglevel - 1);
253     else
254         templen = snprintf(ptr, len, " (%c:", arr_loglevel_chars[loglevel]);
255
256     if (templen == -1 || templen >= len)
257         return;
258     len -= templen;
259     ptr += templen;
260
261     /* Errortype */
262     if (logtype<num_logtype_strings) {
263         templen = snprintf(ptr, len, "%s", arr_logtype_strings[logtype]);
264         if (templen == -1 || templen >= len)
265             return;
266         len -= templen;
267         ptr += templen;
268     }
269     
270     strncat(ptr, "): ", len);
271     ptr[len -1] = 0;
272 }
273
274 static int get_syslog_equivalent(enum loglevels loglevel)
275 {
276     switch (loglevel)
277     {
278         /* The question is we know how bad it is for us,
279            but how should that translate in the syslogs?  */
280     case 1: /* severe */
281         return LOG_ERR;
282     case 2: /* error */
283         return LOG_ERR;
284     case 3: /* warning */
285         return LOG_WARNING;
286     case 4: /* note */
287         return LOG_NOTICE;
288     case 5: /* information */
289         return LOG_INFO;
290     default: /* debug */
291         return LOG_DEBUG;
292     }
293 }
294
295 /* =========================================================================
296    Global function definitions
297    ========================================================================= */
298
299 void log_init(void)
300 {
301     syslog_setup(log_note, 0,
302                  log_config.syslog_display_options,
303                  log_config.facility);
304 }
305
306 void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype)
307 {
308     uid_t process_uid;
309
310     if (loglevel == 0) {
311         /* Disable */
312         if (file_configs[logtype].set) {
313             if (file_configs[logtype].filename) {
314                 free(file_configs[logtype].filename);
315                 file_configs[logtype].filename = NULL;
316             }
317             close(file_configs[logtype].fd);
318             file_configs[logtype].fd = -1;
319             file_configs[logtype].level = 0;
320             file_configs[logtype].set = 0;
321
322             /* if disabling default also set all "default using" levels to 0 */
323             if (logtype == logtype_default) {
324                 while (logtype != logtype_end_of_list_marker) {
325                     if ( ! (file_configs[logtype].set))
326                         file_configs[logtype].level = 0;
327                     logtype++;
328                 }
329             }
330         }
331
332         return;
333     }
334
335     /* Safety check */
336     if (NULL == filename)
337         return;
338
339     /* Resetting existing config ? */
340     if (file_configs[logtype].set && file_configs[logtype].filename) {
341         free(file_configs[logtype].filename);
342         file_configs[logtype].filename = NULL;
343         close(file_configs[logtype].fd);
344         file_configs[logtype].fd = -1;
345         file_configs[logtype].level = 0;
346         file_configs[logtype].set = 0;
347     }
348
349     /* Check if logging to a console */
350     if (logtype == logtype_console) {
351         log_config.console = 1;
352         logtype = logtype_default;
353     }
354
355     /* Set new values */
356     file_configs[logtype].filename = strdup(filename);
357     file_configs[logtype].level = loglevel;
358
359
360     /* Open log file as OPEN_LOGS_AS_UID*/
361     /* Is it /dev/tty ? */
362     if (strcmp(file_configs[logtype].filename, "/dev/tty") == 0) {
363         file_configs[logtype].fd = 1; /* stdout */
364     } else {
365         process_uid = geteuid();
366         if (process_uid) {
367             if (seteuid(OPEN_LOGS_AS_UID) == -1) {
368                 /* XXX failing silently */
369                 return;
370             }
371         }
372         file_configs[logtype].fd = open( file_configs[logtype].filename,
373                                          O_CREAT | O_WRONLY | O_APPEND,
374                                          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
375         if (process_uid) {
376             if (seteuid(process_uid) == -1) {
377                 LOG(log_error, logtype_logger, "can't seteuid back %s", strerror(errno));
378                 exit(EXITERR_SYS);
379             }
380         }
381     }
382
383     /* Check for error opening/creating logfile */
384     if (-1 == file_configs[logtype].fd) {
385         free(file_configs[logtype].filename);
386         file_configs[logtype].filename = NULL;
387         file_configs[logtype].level = -1;
388         file_configs[logtype].set = 0;
389         return;
390     }
391
392     fcntl(file_configs[logtype].fd, F_SETFD, FD_CLOEXEC);
393     file_configs[logtype].set = 1;
394     log_config.filelogging = 1;
395     log_config.inited = 1;
396
397     /* Here's how we make it possible to LOG to a logtype like "logtype_afpd" */
398     /* which then uses the default logtype setup if it isn't setup itself: */
399     /* we just copy the loglevel from default to all logtypes that are not setup. */
400     /* In "make_log_entry" we then check for the logtypes if they arent setup */
401     /* and use default then. We must provide accessible values for all logtypes */
402     /* in order to make it easy and fast to check the loglevels in the LOG macro! */
403
404     if (logtype == logtype_default) {
405         int typeiter = 0;
406         while (typeiter != logtype_end_of_list_marker) {
407             if ( ! (file_configs[typeiter].set))
408                 file_configs[typeiter].level = loglevel;
409             typeiter++;
410         }
411     }
412
413     LOG(log_debug, logtype_logger, "Setup file logging: type: %s, level: %s, file: %s",
414         arr_logtype_strings[logtype], arr_loglevel_strings[loglevel], file_configs[logtype].filename);
415 }
416
417 /* logtype is ignored, it's just one for all */
418 void syslog_setup(int loglevel, enum logtypes logtype _U_,
419                   int display_options, int facility)
420 {
421     log_config.syslog_level = loglevel;
422     log_config.syslog_display_options = display_options;
423     log_config.facility = facility;
424
425     log_config.inited = 1;
426
427     LOG(log_note, logtype_logger, "Set syslog logging to level: %s",
428         arr_loglevel_strings[loglevel]);
429 }
430
431 void log_close(void)
432 {
433 }
434
435 /* This function sets up the processname */
436 void set_processname(const char *processname)
437 {
438     strncpy(log_config.processname, processname, 15);
439     log_config.processname[15] = 0;
440 }
441
442 /* Called by the LOG macro for syslog messages */
443 static void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype _U_, char *message)
444 {
445     if ( !log_config.syslog_opened ) {
446         openlog(log_config.processname, log_config.syslog_display_options,
447                 log_config.facility);
448         log_config.syslog_opened = 1;
449     }
450
451     syslog(get_syslog_equivalent(loglevel), "%s", message);
452 }
453
454 /* -------------------------------------------------------------------------
455    make_log_entry has 1 main flaws:
456    The message in its entirity, must fit into the tempbuffer.
457    So it must be shorter than MAXLOGSIZE
458    ------------------------------------------------------------------------- */
459 void make_log_entry(enum loglevels loglevel, enum logtypes logtype,
460                     const char *file, int line, char *message, ...)
461 {
462     /* fn is not reentrant but is used in signal handler
463      * with LOGGER it's a little late source name and line number
464      * are already changed. */
465     static int inlog = 0;
466     int fd, len;
467     char temp_buffer[MAXLOGSIZE];
468     char log_details_buffer[MAXLOGSIZE];
469     va_list args;
470     struct iovec iov[2];
471
472     if (inlog)
473         return;
474
475     inlog = 1;
476
477     if (!log_config.inited) {
478       log_init();
479     }
480     
481     if (file_configs[logtype].level >= loglevel) {
482       log_src_filename = file;
483       log_src_linenumber = line;
484     }
485     else if (!log_config.filelogging && log_config.syslog_level >= loglevel) {
486        /* Initialise the Messages */
487        va_start(args, message);
488        vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
489        va_end(args);
490        temp_buffer[MAXLOGSIZE -1] = 0;
491        make_syslog_entry(loglevel, logtype, temp_buffer);
492        inlog = 0;
493        return;
494     }
495     else {
496        inlog = 0;
497        return;
498     }
499
500     /* Check if requested logtype is setup */
501     if (file_configs[logtype].set)
502         /* Yes */
503         fd = file_configs[logtype].fd;
504     else
505         /* No: use default */
506         fd = file_configs[logtype_default].fd;
507
508     if (fd < 0) {
509         /* no where to send the output, give up */
510         return;
511     }
512
513     /* Initialise the Messages */
514     va_start(args, message);
515     len = vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
516     va_end(args);
517
518     /* Append \n */
519     if (len ==-1 || len >= MAXLOGSIZE -1) {
520         /* vsnprintf hit the buffer size*/
521         temp_buffer[MAXLOGSIZE-2] = '\n';
522         temp_buffer[MAXLOGSIZE-1] = 0;
523     }
524     else {
525         temp_buffer[len] = '\n';
526         temp_buffer[len+1] = 0;
527     }
528
529     if ( ! log_config.console) {
530         generate_message_details(log_details_buffer, sizeof(log_details_buffer),
531                                  file_configs[logtype].set ?
532                                  file_configs[logtype].display_options :
533                                  file_configs[logtype_default].display_options,
534                                  loglevel, logtype);
535
536         /* If default wasnt setup its fd is -1 */
537         iov[0].iov_base = log_details_buffer;
538         iov[0].iov_len = strlen(log_details_buffer);
539         iov[1].iov_base = temp_buffer;
540         iov[1].iov_len = strlen(temp_buffer);
541         writev( fd,  iov, 2);
542     } else {
543         write(fd, temp_buffer, strlen(temp_buffer));
544     }
545
546     inlog = 0;
547 }
548
549
550 void setuplog(const char *logstr)
551 {
552     char *ptr, *ptrbak, *logtype, *loglevel = NULL, *filename = NULL;
553     ptr = strdup(logstr);
554     ptrbak = ptr;
555
556     /* logtype */
557     logtype = ptr;
558
559     /* get loglevel */
560     ptr = strpbrk(ptr, " \t");
561     if (ptr) {
562         *ptr++ = 0;
563         while (*ptr && isspace(*ptr))
564             ptr++;
565         loglevel = ptr;
566
567         /* get filename */
568         ptr = strpbrk(ptr, " \t");
569         if (ptr) {
570             *ptr++ = 0;
571             while (*ptr && isspace(*ptr))
572                 ptr++;
573         }
574         filename = ptr;
575         if (filename && *filename == 0)
576             filename = NULL;
577     }
578
579     /* finally call setuplog, filename can be NULL */
580     setuplog_internal(loglevel, logtype, filename);
581
582     free(ptrbak);
583 }
584
585 void unsetuplog(const char *logstr)
586 {
587     char *str, *logtype, *filename;
588
589     str = strdup(logstr);
590
591     /* logtype */
592     logtype = str;
593
594     /* get filename, can be NULL */
595     strtok(str, " \t");
596     filename = strtok(NULL, " \t");
597
598     /* finally call setuplog, filename can be NULL */
599     setuplog_internal(NULL, str, filename);
600
601     free(str);
602 }