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