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