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