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