]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/logger.c
SIGINT enables max_debug logging to /tmp/afpd.PID.XXXXXX
[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_info, 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
362     /* Is it /dev/tty ? */
363     if (strcmp(file_configs[logtype].filename, "/dev/tty") == 0) {
364         file_configs[logtype].fd = 1; /* stdout */
365
366         /* Does it end in "XXXXXX" ? */
367     } else if (strcmp(file_configs[logtype].filename + strlen(file_configs[logtype].filename) - 6, "XXXXXX") == 0) {
368         /* debug reguest via SIGINT */
369         file_configs[logtype].fd = mkstemp(file_configs[logtype].filename);
370     } else {
371         process_uid = geteuid();
372         if (process_uid) {
373             if (seteuid(OPEN_LOGS_AS_UID) == -1) {
374                 /* XXX failing silently */
375                 return;
376             }
377         }
378         file_configs[logtype].fd = open( file_configs[logtype].filename,
379                                          O_CREAT | O_WRONLY | O_APPEND,
380                                          S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
381         if (process_uid) {
382             if (seteuid(process_uid) == -1) {
383                 LOG(log_error, logtype_logger, "can't seteuid back %s", strerror(errno));
384                 exit(EXITERR_SYS);
385             }
386         }
387     }
388
389     /* Check for error opening/creating logfile */
390     if (-1 == file_configs[logtype].fd) {
391         free(file_configs[logtype].filename);
392         file_configs[logtype].filename = NULL;
393         file_configs[logtype].level = -1;
394         file_configs[logtype].set = 0;
395         return;
396     }
397
398     fcntl(file_configs[logtype].fd, F_SETFD, FD_CLOEXEC);
399     file_configs[logtype].set = 1;
400     log_config.filelogging = 1;
401     log_config.inited = 1;
402
403     /* Here's how we make it possible to LOG to a logtype like "logtype_afpd" */
404     /* which then uses the default logtype setup if it isn't setup itself: */
405     /* we just copy the loglevel from default to all logtypes that are not setup. */
406     /* In "make_log_entry" we then check for the logtypes if they arent setup */
407     /* and use default then. We must provide accessible values for all logtypes */
408     /* in order to make it easy and fast to check the loglevels in the LOG macro! */
409
410     if (logtype == logtype_default) {
411         int typeiter = 0;
412         while (typeiter != logtype_end_of_list_marker) {
413             if ( ! (file_configs[typeiter].set))
414                 file_configs[typeiter].level = loglevel;
415             typeiter++;
416         }
417     }
418
419     LOG(log_debug, logtype_logger, "Setup file logging: type: %s, level: %s, file: %s",
420         arr_logtype_strings[logtype], arr_loglevel_strings[loglevel], file_configs[logtype].filename);
421 }
422
423 /* logtype is ignored, it's just one for all */
424 void syslog_setup(int loglevel, enum logtypes logtype _U_,
425                   int display_options, int facility)
426 {
427     log_config.syslog_level = loglevel;
428     log_config.syslog_display_options = display_options;
429     log_config.facility = facility;
430
431     log_config.inited = 1;
432
433     LOG(log_note, logtype_logger, "Set syslog logging to level: %s",
434         arr_loglevel_strings[loglevel]);
435 }
436
437 void log_close(void)
438 {
439 }
440
441 /* This function sets up the processname */
442 void set_processname(const char *processname)
443 {
444     strncpy(log_config.processname, processname, 15);
445     log_config.processname[15] = 0;
446 }
447
448 /* Called by the LOG macro for syslog messages */
449 static void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype _U_, char *message)
450 {
451     if ( !log_config.syslog_opened ) {
452         openlog(log_config.processname, log_config.syslog_display_options,
453                 log_config.facility);
454         log_config.syslog_opened = 1;
455     }
456
457     syslog(get_syslog_equivalent(loglevel), "%s", message);
458 }
459
460 /* -------------------------------------------------------------------------
461    make_log_entry has 1 main flaws:
462    The message in its entirity, must fit into the tempbuffer.
463    So it must be shorter than MAXLOGSIZE
464    ------------------------------------------------------------------------- */
465 void make_log_entry(enum loglevels loglevel, enum logtypes logtype,
466                     const char *file, int line, char *message, ...)
467 {
468     /* fn is not reentrant but is used in signal handler
469      * with LOGGER it's a little late source name and line number
470      * are already changed. */
471     static int inlog = 0;
472     int fd, len;
473     char temp_buffer[MAXLOGSIZE];
474     char log_details_buffer[MAXLOGSIZE];
475     va_list args;
476     struct iovec iov[2];
477
478     if (inlog)
479         return;
480
481     inlog = 1;
482
483     if (!log_config.inited) {
484       log_init();
485     }
486     
487     if (file_configs[logtype].level >= loglevel) {
488       log_src_filename = file;
489       log_src_linenumber = line;
490     }
491     else if (!log_config.filelogging && log_config.syslog_level >= loglevel) {
492        /* Initialise the Messages */
493        va_start(args, message);
494        vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
495        va_end(args);
496        temp_buffer[MAXLOGSIZE -1] = 0;
497        make_syslog_entry(loglevel, logtype, temp_buffer);
498        inlog = 0;
499        return;
500     }
501     else {
502        inlog = 0;
503        return;
504     }
505
506     /* Check if requested logtype is setup */
507     if (file_configs[logtype].set)
508         /* Yes */
509         fd = file_configs[logtype].fd;
510     else
511         /* No: use default */
512         fd = file_configs[logtype_default].fd;
513
514     if (fd < 0) {
515         /* no where to send the output, give up */
516         return;
517     }
518
519     /* Initialise the Messages */
520     va_start(args, message);
521     len = vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
522     va_end(args);
523
524     /* Append \n */
525     if (len ==-1 || len >= MAXLOGSIZE -1) {
526         /* vsnprintf hit the buffer size*/
527         temp_buffer[MAXLOGSIZE-2] = '\n';
528         temp_buffer[MAXLOGSIZE-1] = 0;
529     }
530     else {
531         temp_buffer[len] = '\n';
532         temp_buffer[len+1] = 0;
533     }
534
535     if ( ! log_config.console) {
536         generate_message_details(log_details_buffer, sizeof(log_details_buffer),
537                                  file_configs[logtype].set ?
538                                  file_configs[logtype].display_options :
539                                  file_configs[logtype_default].display_options,
540                                  loglevel, logtype);
541
542         /* If default wasnt setup its fd is -1 */
543         iov[0].iov_base = log_details_buffer;
544         iov[0].iov_len = strlen(log_details_buffer);
545         iov[1].iov_base = temp_buffer;
546         iov[1].iov_len = strlen(temp_buffer);
547         writev( fd,  iov, 2);
548     } else {
549         write(fd, temp_buffer, strlen(temp_buffer));
550     }
551
552     inlog = 0;
553 }
554
555
556 void setuplog(const char *logstr)
557 {
558     char *ptr, *ptrbak, *logtype, *loglevel = NULL, *filename = NULL;
559     ptr = strdup(logstr);
560     ptrbak = ptr;
561
562     /* logtype */
563     logtype = ptr;
564
565     /* get loglevel */
566     ptr = strpbrk(ptr, " \t");
567     if (ptr) {
568         *ptr++ = 0;
569         while (*ptr && isspace(*ptr))
570             ptr++;
571         loglevel = ptr;
572
573         /* get filename */
574         ptr = strpbrk(ptr, " \t");
575         if (ptr) {
576             *ptr++ = 0;
577             while (*ptr && isspace(*ptr))
578                 ptr++;
579         }
580         filename = ptr;
581         if (filename && *filename == 0)
582             filename = NULL;
583     }
584
585     /* finally call setuplog, filename can be NULL */
586     setuplog_internal(loglevel, logtype, filename);
587
588     free(ptrbak);
589 }
590
591 void unsetuplog(const char *logstr)
592 {
593     char *str, *logtype, *filename;
594
595     str = strdup(logstr);
596
597     /* logtype */
598     logtype = str;
599
600     /* get filename, can be NULL */
601     strtok(str, " \t");
602     filename = strtok(NULL, " \t");
603
604     /* finally call setuplog, filename can be NULL */
605     setuplog_internal(NULL, str, filename);
606
607     free(str);
608 }