1 /*
2 * fiked - a fake IKE PSK+XAUTH daemon based on vpnc
3 * Copyright (C) 2005, Daniel Roethlisberger <daniel@roe.ch>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see http://www.gnu.org/copyleft/
17 *
18 * $Id: log.c 114 2005-12-24 12:00:33Z roe $
19 */
20
21 #include "log.h"
22
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <errno.h>
34
35 static FILE* file = NULL;
36 static int quiet = 0;
37
log_init(char * filename,int q)38 void log_init(char *filename, int q)
39 {
40 log_cleanup();
41 if(filename) {
42 file = fopen(filename, "a");
43 if(!file) {
44 fprintf(stderr, "FATAL: cannot open file %s: %s\n", filename,
45 strerror(errno));
46 exit(-1);
47 }
48 }
49 quiet = q;
50 }
51
log_do_printf(const char * fmt,...)52 void log_do_printf(const char *fmt, ...)
53 {
54 va_list ap;
55
56 char *buf;
57 va_start(ap, fmt);
58 vasprintf(&buf, fmt, ap);
59 va_end(ap);
60
61 if(file) {
62 fprintf(file, "%s", buf);
63 }
64 if(!quiet) {
65 fprintf(stdout, "%s", buf);
66 }
67 free(buf);
68 }
69
log_do_flush()70 void log_do_flush()
71 {
72 if(file) {
73 fflush(file);
74 }
75 if(!quiet) {
76 fflush(stdout);
77 }
78 }
79
log_printf(peer_ctx * ctx,const char * fmt,...)80 void log_printf(peer_ctx *ctx, const char *fmt, ...)
81 {
82 va_list ap;
83 char timestamp[1024];
84 time_t epoch = time(0);
85 strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S %z",
86 localtime(&epoch));
87
88 char *buf;
89 va_start(ap, fmt);
90 vasprintf(&buf, fmt, ap);
91 va_end(ap);
92
93 log_do_printf("[%s] [%d] ", timestamp, getpid());
94 if(ctx) {
95 log_do_printf("[%s:%d] ",
96 inet_ntoa(ctx->peer_addr.sin_addr),
97 ntohs(ctx->peer_addr.sin_port));
98 }
99 log_do_printf("%s\n", buf);
100 log_do_flush();
101 free(buf);
102 }
103
log_cleanup()104 void log_cleanup()
105 {
106 if(file) {
107 if(file != stdout)
108 fclose(file);
109 file = NULL;
110 }
111 }
112