]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/logger.c
logger, better buffer overrun tests
[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
30 #include <atalk/boolean.h>
31
32 #define LOGGER_C
33 #include <atalk/logger.h>
34 #undef LOGGER_C
35
36 #define OPEN_LOGS_AS_UID 0
37
38 #define COUNT_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
39
40 /* =========================================================================
41    Config
42    ========================================================================= */
43
44 /* Main log config container, must be globally visible */
45 log_config_t log_config = {
46     0,                  /* Initialized ? 0 = no */
47     0,                  /* No filelogging setup yet */
48     {0},                /* processname */
49     0,                  /* syslog opened ? */
50     logfacility_daemon,         /* syslog facility to use */
51     logoption_ndelay|logoption_pid, /* logging options for syslog */
52     0                               /* log level for syslog */
53 };
54
55 /* Default log config: log nothing to files.
56    0:    not set individually
57    NULL: Name of file
58    -1:   logfiles fd
59    0:   Log Level
60    0:    Display options */
61 #define DEFAULT_LOG_CONFIG {0, NULL, -1, 0, 0}
62
63 filelog_conf_t file_configs[logtype_end_of_list_marker] = {
64     DEFAULT_LOG_CONFIG, /* logtype_default */
65     DEFAULT_LOG_CONFIG, /* logtype_core */
66     DEFAULT_LOG_CONFIG, /* logtype_logger */
67     DEFAULT_LOG_CONFIG, /* logtype_cnid */
68     DEFAULT_LOG_CONFIG, /* logtype_afpd */
69     DEFAULT_LOG_CONFIG, /* logtype_atalkd */
70     DEFAULT_LOG_CONFIG, /* logtype_papd */
71     DEFAULT_LOG_CONFIG  /* logtype_uams */
72 };
73
74 /* These are used by the LOG macro to store __FILE__ and __LINE__ */
75 char *log_src_filename;
76 int  log_src_linenumber;
77
78 /* Array to store text to list given a log type */
79 static const char *arr_logtype_strings[] =  LOGTYPE_STRING_IDENTIFIERS;
80 static const int num_logtype_strings = COUNT_ARRAY(arr_logtype_strings);
81
82 /* Array for charachters representing log severity in the log file */
83 static const char arr_loglevel_chars[] = {'-','S', 'E', 'W', 'N', 'I', 'D'};
84 static const int num_loglevel_chars = COUNT_ARRAY(arr_loglevel_chars);
85
86 static const char *arr_loglevel_strings[] = LOGLEVEL_STRING_IDENTIFIERS;
87 static const int num_loglevel_strings = COUNT_ARRAY(arr_loglevel_strings);
88
89 /* =========================================================================
90    Internal function definitions
91    ========================================================================= */
92
93 /*
94  * If filename == NULL its for syslog logging, otherwise its for file-logging.
95  * "unsetuplog" calls with loglevel == NULL.
96  * loglevel == NULL means:
97  *    if logtype == default
98  *       disable logging
99  *    else
100  *       set to default logging
101  */
102
103 /* -[un]setuplog <logtype> <loglevel> [<filename>]*/
104 static void setuplog_internal(const char *loglevel, const char *logtype, const char *filename)
105 {
106     int typenum, levelnum;
107
108     /* Parse logtype */
109     for( typenum=0; typenum < num_logtype_strings; typenum++) {
110         if (strcasecmp(logtype, arr_logtype_strings[typenum]) == 0)
111             break;
112     }
113     if (typenum >= num_logtype_strings) {
114         return;
115     }
116
117     /* Parse loglevel */
118     if (loglevel == NULL) {
119         levelnum = 0;
120     } else {
121         for(levelnum=1; levelnum < num_loglevel_strings; levelnum++) {
122             if (strcasecmp(loglevel, arr_loglevel_strings[levelnum]) == 0)
123                 break;
124         }
125         if (levelnum >= num_loglevel_strings) {
126             return;
127         }
128     }
129
130     /* is this a syslog setup or a filelog setup ? */
131     if (filename == NULL) {
132         /* must be syslog */
133         syslog_setup(levelnum, 0,
134                      log_config.syslog_display_options,
135                      log_config.facility);
136     } else {
137         /* this must be a filelog */
138         log_setup(filename, levelnum, typenum);
139     }
140
141     return;
142 }
143
144 static void generate_message_details(char *message_details_buffer,
145                                      int message_details_buffer_length,
146                                      int display_options,
147                                      enum loglevels loglevel, enum logtypes logtype)
148 {
149     char   *ptr = message_details_buffer;
150     int    templen;
151     int    len = message_details_buffer_length;
152     struct timeval tv;
153     pid_t  pid;
154
155     *ptr = 0;
156
157     /* Print time */
158     gettimeofday(&tv, NULL);
159     strftime(ptr, len, "%b %d %H:%M:%S.", localtime(&tv.tv_sec));
160     templen = strlen(ptr);
161     len -= templen;
162     ptr += templen;
163
164     templen = snprintf(ptr, len, "%06u ", (int)tv.tv_usec);
165     if (templen == -1 || templen >= len)
166         return;
167         
168     len -= templen;
169     ptr += templen;
170
171     /* Process name &&  PID */
172     pid = getpid();
173     templen = snprintf(ptr, len, "%s[%d]", log_config.processname, pid);
174     if (templen == -1 || templen >= len)
175         return;
176     len -= templen;
177     ptr += templen;
178
179     /* Source info ? */
180     if ( ! (display_options & logoption_nsrcinfo)) {
181         char *basename = strrchr(log_src_filename, '/');
182         if (basename)
183             templen = snprintf(ptr, len, " {%s:%d}", basename + 1, log_src_linenumber);
184         else
185             templen = snprintf(ptr, len, " {%s:%d}", log_src_filename, log_src_linenumber);
186         if (templen == -1 || templen >= len)
187             return;
188         len -= templen;
189         ptr += templen;
190     }
191
192     /* Errorlevel */
193     if (loglevel >= (num_loglevel_chars - 1))
194         templen = snprintf(ptr, len,  " (D%d:", loglevel - 1);
195     else
196         templen = snprintf(ptr, len, " (%c:", arr_loglevel_chars[loglevel]);
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] = 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 /* =========================================================================
237    Global function definitions
238    ========================================================================= */
239
240 void log_init(void)
241 {
242     syslog_setup(log_note, 0,
243                  log_config.syslog_display_options,
244                  log_config.facility);
245 }
246
247 void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype)
248 {
249     uid_t process_uid;
250
251     if (loglevel == 0) {
252         /* Disable */
253         if (file_configs[logtype].set) {
254             if (file_configs[logtype].filename) {
255                 free(file_configs[logtype].filename);
256                 file_configs[logtype].filename = NULL;
257             }
258             close(file_configs[logtype].fd);
259             file_configs[logtype].fd = -1;
260             file_configs[logtype].level = 0;
261             file_configs[logtype].set = 0;
262
263             /* if disabling default also set all "default using" levels to 0 */
264             if (logtype == logtype_default) {
265                 while (logtype != logtype_end_of_list_marker) {
266                     if ( ! (file_configs[logtype].set))
267                         file_configs[logtype].level = 0;
268                     logtype++;
269                 }
270             }
271         }
272
273         return;
274     }
275
276     /* Safety check */
277     if (NULL == filename)
278         return;
279
280     /* Resetting existing config ? */
281     if (file_configs[logtype].set && file_configs[logtype].filename) {
282         free(file_configs[logtype].filename);
283         file_configs[logtype].filename = NULL;
284         close(file_configs[logtype].fd);
285         file_configs[logtype].fd = -1;
286         file_configs[logtype].level = 0;
287         file_configs[logtype].set = 0;
288     }
289
290     /* Set new values */
291     file_configs[logtype].filename = strdup(filename);
292     file_configs[logtype].level = loglevel;
293
294
295     /* Open log file as OPEN_LOGS_AS_UID*/
296     process_uid = geteuid();
297     if (process_uid)
298         seteuid(OPEN_LOGS_AS_UID);
299     file_configs[logtype].fd = open( file_configs[logtype].filename,
300                                      O_CREAT | O_WRONLY | O_APPEND,
301                                      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
302     if (process_uid)
303         seteuid(process_uid);
304
305     /* Check for error opening/creating logfile */
306     if (-1 == file_configs[logtype].fd) {
307         free(file_configs[logtype].filename);
308         file_configs[logtype].filename = NULL;
309         file_configs[logtype].level = -1;
310         file_configs[logtype].set = 0;
311         return;
312     }
313
314     fcntl(file_configs[logtype].fd, F_SETFD, FD_CLOEXEC);
315     file_configs[logtype].set = 1;
316     log_config.filelogging = 1;
317     log_config.inited = 1;
318
319     /* Here's how we make it possible to LOG to a logtype like "logtype_afpd" */
320     /* which then uses the default logtype setup if it isn't setup itself: */
321     /* we just copy the loglevel from default to all logtypes that are not setup. */
322     /* In "make_log_entry" we then check for the logtypes if they arent setup */
323     /* and use default then. We must provide accessible values for all logtypes */
324     /* in order to make it easy and fast to check the loglevels in the LOG macro! */
325
326     if (logtype == logtype_default) {
327         while (logtype != logtype_end_of_list_marker) {
328             if ( ! (file_configs[logtype].set))
329                 file_configs[logtype].level = loglevel;
330             logtype++;
331         }
332         logtype = logtype_default;
333     }
334
335     LOG(log_debug, logtype_logger, "Setup file logging: type: %s, level: %s, file: %s",
336         arr_logtype_strings[logtype], arr_loglevel_strings[loglevel], file_configs[logtype].filename);
337 }
338
339 /* logtype is ignored, it's just one for all */
340 void syslog_setup(int loglevel, enum logtypes logtype _U_,
341                   int display_options, int facility)
342 {
343     log_config.syslog_level = loglevel;
344     log_config.syslog_display_options = display_options;
345     log_config.facility = facility;
346
347     log_config.inited = 1;
348
349     LOG(log_note, logtype_logger, "Set syslog logging to level: %s",
350         arr_loglevel_strings[loglevel]);
351 }
352
353 void log_close(void)
354 {
355 }
356
357 /* This function sets up the processname */
358 void set_processname(const char *processname)
359 {
360     strncpy(log_config.processname, processname, 15);
361     log_config.processname[15] = 0;
362 }
363
364 /* -------------------------------------------------------------------------
365    make_log_entry has 1 main flaws:
366    The message in its entirity, must fit into the tempbuffer.
367    So it must be shorter than MAXLOGSIZE
368    ------------------------------------------------------------------------- */
369 void make_log_entry(enum loglevels loglevel, enum logtypes logtype,
370                     char *message, ...)
371 {
372     /* fn is not reentrant but is used in signal handler
373      * with LOGGER it's a little late source name and line number
374      * are already changed. */
375     static int inlog = 0;
376     int fd, len;
377     char temp_buffer[MAXLOGSIZE];
378     char log_details_buffer[MAXLOGSIZE];
379     va_list args;
380     struct iovec iov[2];
381
382     if (inlog)
383         return;
384
385     /* Check if requested logtype is setup */
386     if (file_configs[logtype].set)
387         /* Yes */
388         fd = file_configs[logtype].fd;
389     else
390         /* No: use default */
391         fd = file_configs[logtype_default].fd;
392
393     if (fd < 0) {
394         /* no where to send the output, give up */
395         return;
396     }
397
398     inlog = 1;
399     /* Initialise the Messages */
400     va_start(args, message);
401     len = vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
402     va_end(args);
403
404     /* Append \n */
405     if (len ==-1 || len >= MAXLOGSIZE -1) {
406         /* vsnprintf hit the buffer size*/
407         temp_buffer[MAXLOGSIZE-2] = '\n';
408         temp_buffer[MAXLOGSIZE-1] = 0;
409     }
410     else {
411         temp_buffer[len] = '\n';
412         temp_buffer[len+1] = 0;
413     }
414
415     generate_message_details(log_details_buffer, sizeof(log_details_buffer),
416                              file_configs[logtype].set ?
417                              file_configs[logtype].display_options :
418                              file_configs[logtype_default].display_options,
419                              loglevel, logtype);
420
421
422     /* If default wasnt setup its fd is -1 */
423     iov[0].iov_base = log_details_buffer;
424     iov[0].iov_len = strlen(log_details_buffer);
425     iov[1].iov_base = temp_buffer;
426     iov[1].iov_len = strlen(temp_buffer);
427     writev( fd,  iov, 2);
428
429     inlog = 0;
430 }
431
432 /* Called by the LOG macro for syslog messages */
433 void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype _U_, char *message, ...)
434 {
435     va_list args;
436     char log_buffer[MAXLOGSIZE];
437     /* fn is not reentrant but is used in signal handler
438      * with LOGGER it's a little late source name and line number
439      * are already changed.
440      */
441     static int inlog = 0;
442
443     if (inlog)
444         return;
445     inlog = 1;
446
447     if ( ! (log_config.syslog_opened) ) {
448         openlog(log_config.processname, log_config.syslog_display_options,
449                 log_config.facility);
450         log_config.syslog_opened = 1;
451     }
452
453     /* Initialise the Messages */
454     va_start(args, message);
455     vsnprintf(log_buffer, sizeof(log_buffer), message, args);
456     va_end(args);
457     log_buffer[MAXLOGSIZE -1] = 0;
458     syslog(get_syslog_equivalent(loglevel), "%s", log_buffer);
459
460     inlog = 0;
461 }
462
463 void setuplog(const char *logstr)
464 {
465     char *ptr, *ptrbak, *logtype, *loglevel, *filename;
466     ptr = strdup(logstr);
467     ptrbak = ptr;
468
469     /* logtype */
470     logtype = ptr;
471
472     /* get loglevel */
473     ptr = strpbrk(ptr, " \t");
474     if (ptr) {
475         *ptr++ = 0;
476         while (*ptr && isspace(*ptr))
477             ptr++;
478         loglevel = ptr;
479
480         /* get filename */
481         ptr = strpbrk(ptr, " \t");
482         if (ptr) {
483             *ptr++ = 0;
484             while (*ptr && isspace(*ptr))
485                 ptr++;
486         }
487         filename = ptr;
488     }
489
490     /* finally call setuplog, filename can be NULL */
491     setuplog_internal(loglevel, logtype, filename);
492
493     free(ptrbak);
494 }
495
496 void unsetuplog(const char *logstr)
497 {
498     char *str, *logtype, *filename;
499
500     str = strdup(logstr);
501
502     /* logtype */
503     logtype = str;
504
505     /* get filename, can be NULL */
506     strtok(str, " \t");
507     filename = strtok(NULL, " \t");
508
509     /* finally call setuplog, filename can be NULL */
510     setuplog_internal(NULL, str, filename);
511
512     free(str);
513 }