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