1/* util.c ....... error message utilities. 2 * C. Scott Ananian <cananian@alumni.princeton.edu> 3 * 4 * $Id: util.c,v 1.1.1.1 2008/10/15 03:30:52 james26_jang Exp $ 5 */ 6 7#include <stdio.h> 8#include <stdarg.h> 9#include <syslog.h> 10#include <unistd.h> 11#include <stdlib.h> 12#include "util.h" 13 14#ifndef PROGRAM_NAME 15#define PROGRAM_NAME "pptp" 16#endif 17 18/* implementation of log_string, defined as extern in util.h */ 19char *log_string = "anon"; 20 21static void open_log(void) __attribute__ ((constructor)); 22static void close_log(void) __attribute__ ((destructor)); 23 24#define MAKE_STRING(label) \ 25va_list ap; \ 26char buf[256], string[256]; \ 27va_start(ap, format); \ 28vsnprintf(buf, sizeof(buf), format, ap); \ 29snprintf(string, sizeof(string), "%s", buf); \ 30va_end(ap) 31 32/*** open log *****************************************************************/ 33static void open_log(void) { 34 openlog(PROGRAM_NAME, LOG_PID, LOG_DAEMON); 35} 36 37/*** close log ****************************************************************/ 38static void close_log(void) 39{ 40 closelog(); 41} 42 43/*** print a message to syslog ************************************************/ 44void _log(const char *func, const char *file, int line, const char *format, ...) 45{ 46 if (log_level > 0) { 47 MAKE_STRING("log"); 48 syslog(LOG_NOTICE, "%s", string); 49 } 50} 51 52/*** print a warning to syslog ************************************************/ 53void _warn(const char *func, const char *file, int line, const char *format, ...) 54{ 55 MAKE_STRING("warn"); 56 fprintf(stderr, "%s\n", string); 57 syslog(LOG_WARNING, "%s", string); 58} 59 60/*** print a fatal warning to syslog and exit *********************************/ 61void _fatal(const char *func, const char *file, int line, const char *format, ...) 62{ 63 MAKE_STRING("fatal"); 64 fprintf(stderr, "%s\n", string); 65 syslog(LOG_CRIT, "%s", string); 66 exit(1); 67} 68 69/*** connect a file to a file descriptor **************************************/ 70int file2fd(const char *path, const char *mode, int fd) 71{ 72 int ok = 0; 73 FILE *file = NULL; 74 file = fopen(path, mode); 75 if (file != NULL && dup2(fileno(file), fd) != -1) 76 ok = 1; 77 if (file) fclose(file); 78 return ok; 79} 80