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