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