]> arthur.barton.de Git - netatalk.git/blob - libatalk/util/logger.c
remove 'ISO C90 forbids mixed declarations and code' warning
[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 *logtype, const char *loglevel, 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     len -= templen;
166     ptr += templen;
167
168     /* Process name */
169     strncpy(ptr, log_config.processname, len);
170     templen = strlen(ptr);
171     len -= templen;
172     ptr += templen;
173
174     /* PID */
175     pid = getpid();
176     templen = snprintf(ptr, len, "[%d]", pid);
177     len -= templen;
178     ptr += templen;
179
180     /* Source info ? */
181     if ( ! (display_options & logoption_nsrcinfo)) {
182         char *basename = strrchr(log_src_filename, '/');
183         if (basename)
184             templen = snprintf(ptr, len, " {%s:%d}", basename + 1, log_src_linenumber);
185         else
186             templen = snprintf(ptr, len, " {%s:%d}", log_src_filename, log_src_linenumber);
187         if (templen >= len)
188             return;
189         len -= templen;
190         ptr += templen;
191     }
192
193     /* Errorlevel */
194     if (loglevel >= (num_loglevel_chars - 1))
195         templen = snprintf(ptr, len,  " (D%d:", loglevel - 1);
196     else
197         templen = snprintf(ptr, len, " (%c:", arr_loglevel_chars[loglevel]);
198     len -= templen;
199     ptr += templen;
200
201     /* Errortype */
202     if (logtype<num_logtype_strings) {
203         templen = snprintf(ptr, len, "%s", arr_logtype_strings[logtype]);
204         len -= templen;
205         ptr += templen;
206     }
207
208     strncat(ptr, "): ", len);
209 }
210
211 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 /* =========================================================================
233    Global function definitions
234    ========================================================================= */
235
236 void log_init(void)
237 {
238     syslog_setup(log_note, 0,
239                  log_config.syslog_display_options,
240                  log_config.facility);
241 }
242
243 void log_setup(const char *filename, enum loglevels loglevel, enum logtypes logtype)
244 {
245     uid_t process_uid;
246
247     if (loglevel == 0) {
248         /* Disable */
249         if (file_configs[logtype].set) {
250             if (file_configs[logtype].filename) {
251                 free(file_configs[logtype].filename);
252                 file_configs[logtype].filename = NULL;
253             }
254             close(file_configs[logtype].fd);
255             file_configs[logtype].fd = -1;
256             file_configs[logtype].level = 0;
257             file_configs[logtype].set = 0;
258
259             /* if disabling default also set all "default using" levels to 0 */
260             if (logtype == logtype_default) {
261                 while (logtype != logtype_end_of_list_marker) {
262                     if ( ! (file_configs[logtype].set))
263                         file_configs[logtype].level = 0;
264                     logtype++;
265                 }
266             }
267         }
268
269         return;
270     }
271
272     /* Safety check */
273     if (NULL == filename)
274         return;
275
276     /* Resetting existing config ? */
277     if (file_configs[logtype].set && file_configs[logtype].filename) {
278         free(file_configs[logtype].filename);
279         file_configs[logtype].filename = NULL;
280         close(file_configs[logtype].fd);
281         file_configs[logtype].fd = -1;
282         file_configs[logtype].level = 0;
283         file_configs[logtype].set = 0;
284     }
285
286     /* Set new values */
287     file_configs[logtype].filename = strdup(filename);
288     file_configs[logtype].level = loglevel;
289
290
291     /* Open log file as OPEN_LOGS_AS_UID*/
292     process_uid = geteuid();
293     if (process_uid)
294         seteuid(OPEN_LOGS_AS_UID);
295     file_configs[logtype].fd = open( file_configs[logtype].filename,
296                                      O_CREAT | O_WRONLY | O_APPEND,
297                                      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
298     if (process_uid)
299         seteuid(process_uid);
300
301     /* Check for error opening/creating logfile */
302     if (-1 == file_configs[logtype].fd) {
303         free(file_configs[logtype].filename);
304         file_configs[logtype].filename = NULL;
305         file_configs[logtype].level = -1;
306         file_configs[logtype].set = 0;
307         return;
308     }
309
310     fcntl(file_configs[logtype].fd, F_SETFD, FD_CLOEXEC);
311     file_configs[logtype].set = 1;
312     log_config.filelogging = 1;
313     log_config.inited = 1;
314
315     /* Here's how we make it possible to LOG to a logtype like "logtype_afpd" */
316     /* which then uses the default logtype setup if it isn't setup itself: */
317     /* we just copy the loglevel from default to all logtypes that are not setup. */
318     /* In "make_log_entry" we then check for the logtypes if they arent setup */
319     /* and use default then. We must provide accessible values for all logtypes */
320     /* in order to make it easy and fast to check the loglevels in the LOG macro! */
321
322     if (logtype == logtype_default) {
323         while (logtype != logtype_end_of_list_marker) {
324             if ( ! (file_configs[logtype].set))
325                 file_configs[logtype].level = loglevel;
326             logtype++;
327         }
328         logtype = logtype_default;
329     }
330
331     LOG(log_debug, logtype_logger, "Setup file logging: type: %s, level: %s, file: %s",
332         arr_logtype_strings[logtype], arr_loglevel_strings[loglevel], file_configs[logtype].filename);
333 }
334
335 /* logtype is ignored, it's just one for all */
336 void syslog_setup(int loglevel, enum logtypes logtype _U_,
337                   int display_options, int facility)
338 {
339     log_config.syslog_level = loglevel;
340     log_config.syslog_display_options = display_options;
341     log_config.facility = facility;
342
343     log_config.inited = 1;
344
345     LOG(log_note, logtype_logger, "Set syslog logging to level: %s",
346         arr_loglevel_strings[loglevel]);
347 }
348
349 void log_close()
350 {
351 }
352
353 /* This function sets up the processname */
354 void set_processname(const char *processname)
355 {
356     strncpy(log_config.processname, processname, 15);
357     log_config.processname[15] = 0;
358 }
359
360 /* -------------------------------------------------------------------------
361    make_log_entry has 1 main flaws:
362    The message in its entirity, must fit into the tempbuffer.
363    So it must be shorter than MAXLOGSIZE
364    ------------------------------------------------------------------------- */
365 void make_log_entry(enum loglevels loglevel, enum logtypes logtype,
366                     char *message, ...)
367 {
368     /* fn is not reentrant but is used in signal handler
369      * with LOGGER it's a little late source name and line number
370      * are already changed. */
371     static int inlog = 0;
372     int fd, len;
373     char temp_buffer[MAXLOGSIZE];
374     char log_details_buffer[MAXLOGSIZE];
375     va_list args;
376     struct iovec iov[2];
377
378     if (inlog)
379         return;
380     inlog = 1;
381
382     /* Initialise the Messages */
383     va_start(args, message);
384     len = vsnprintf(temp_buffer, MAXLOGSIZE - 1, message, args);
385     va_end(args);
386
387     /* Append \n */
388     if (len >= MAXLOGSIZE)
389         /* vsnprintf hit the buffer size*/
390         temp_buffer[MAXLOGSIZE-2] = '\n';
391     else {
392         temp_buffer[len] = '\n';
393         temp_buffer[len+1] = 0;
394     }
395
396     generate_message_details(log_details_buffer, sizeof(log_details_buffer),
397                              file_configs[logtype].set ?
398                              file_configs[logtype].display_options :
399                              file_configs[logtype_default].display_options,
400                              loglevel, logtype);
401
402     /* Check if requested logtype is setup */
403     if (file_configs[logtype].set)
404         /* Yes */
405         fd = file_configs[logtype].fd;
406     else
407         /* No: use default */
408         fd = file_configs[logtype_default].fd;
409
410     /* If default wasnt setup its fd is -1 */
411     if (fd >= 0) {
412         iov[0].iov_base = log_details_buffer;
413         iov[0].iov_len = strlen(log_details_buffer);
414         iov[1].iov_base = temp_buffer;
415         iov[1].iov_len = strlen(temp_buffer);
416         writev( fd,  iov, 2);
417     }
418
419     inlog = 0;
420 }
421
422 /* Called by the LOG macro for syslog messages */
423 void make_syslog_entry(enum loglevels loglevel, enum logtypes logtype, char *message, ...)
424 {
425     va_list args;
426     char log_buffer[MAXLOGSIZE];
427     /* fn is not reentrant but is used in signal handler
428      * with LOGGER it's a little late source name and line number
429      * are already changed.
430      */
431     static int inlog = 0;
432
433     if (inlog)
434         return;
435     inlog = 1;
436
437     if ( ! (log_config.syslog_opened) ) {
438         openlog(log_config.processname, log_config.syslog_display_options,
439                 log_config.facility);
440         log_config.syslog_opened = 1;
441     }
442
443     /* Initialise the Messages */
444     va_start(args, message);
445     vsnprintf(log_buffer, sizeof(log_buffer), message, args);
446     va_end(args);
447
448     syslog(get_syslog_equivalent(loglevel), "%s", log_buffer);
449
450     inlog = 0;
451 }
452
453 void setuplog(const char *logstr)
454 {
455     char *ptr, *ptrbak, *logtype, *loglevel, *filename;
456     ptr = strdup(logstr);
457     ptrbak = ptr;
458
459     /* logtype */
460     logtype = ptr;
461
462     /* get loglevel */
463     ptr = strpbrk(ptr, " \t");
464     if (ptr) {
465         *ptr++ = 0;
466         while (*ptr && isspace(*ptr))
467             ptr++;
468         loglevel = ptr;
469
470         /* get filename */
471         ptr = strpbrk(ptr, " \t");
472         if (ptr) {
473             *ptr++ = 0;
474             while (*ptr && isspace(*ptr))
475                 ptr++;
476         }
477         filename = ptr;
478     }
479
480     /* finally call setuplog, filename can be NULL */
481     setuplog_internal(logtype, loglevel, filename);
482
483     free(ptrbak);
484 }
485
486 void unsetuplog(const char *logstr)
487 {
488     char *str, *logtype, *filename;
489
490     str = strdup(logstr);
491
492     /* logtype */
493     logtype = str;
494
495     /* get filename, can be NULL */
496     strtok(str, " \t");
497     filename = strtok(NULL, " \t");
498
499     /* finally call setuplog, filename can be NULL */
500     setuplog_internal(str, NULL, filename);
501
502     free(str);
503 }