Debian Codegraph @

src/log.c

raw
1 /*
2 * stunnel TLS offloading and load-balancing proxy
3 * Copyright (C) 1998-2026 Michal Trojnara <[email protected]>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * 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.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, see <http://www.gnu.org/licenses>.
17 *
18 * Linking stunnel statically or dynamically with other modules is making
19 * a combined work based on stunnel. Thus, the terms and conditions of
20 * the GNU General Public License cover the whole combination.
21 *
22 * In addition, as a special exception, the copyright holder of stunnel
23 * gives you permission to combine stunnel with free software programs or
24 * libraries that are released under the GNU LGPL and with code included
25 * in the standard release of OpenSSL under the OpenSSL License (or
26 * modified versions of such code, with unchanged license). You may copy
27 * and distribute such a system following the terms of the GNU GPL for
28 * stunnel and the licenses of the other code concerned.
29 *
30 * Note that people who make modified versions of stunnel are not obligated
31 * to grant this special exception for their modified versions; it is their
32 * choice whether to do so. The GNU General Public License gives permission
33 * to release a modified version without this exception; this exception
34 * also makes it possible to release a modified version which carries
35 * forward this exception.
36 */
37
38 #include "prototypes.h"
39
40 NOEXPORT void log_queue(SERVICE_OPTIONS *, int, char *, char *, char *);
41 NOEXPORT void log_raw(SERVICE_OPTIONS *, int, char *, char *, char *);
42 NOEXPORT void safestring(char *);
43
44 DISK_FILE *outfile=NULL;
45
46 static struct LIST { /* single-linked list of log lines */
47 struct LIST *next;
48 SERVICE_OPTIONS *opt;
49 int level;
50 char *stamp, *id, *text;
51 } *head=NULL, *tail=NULL;
52 static LOG_MODE log_mode=LOG_MODE_BUFFER;
53
54 #if !defined(USE_WIN32) && !defined(__vms)
55
56 static int syslog_opened=0;
57
58 NOEXPORT void syslog_open(void) {
59 if(global_options.option.log_syslog) {
60 static char *servname=NULL;
61 char *servname_old;
62
63 /* openlog(3) requires a persistent copy of the "ident" parameter */
64 servname_old=servname;
65 servname=str_dup(service_options.servname);
66 #ifdef __ultrix__
67 openlog(servname, 0);
68 #else
69 openlog(servname, LOG_CONS|LOG_NDELAY, global_options.log_facility);
70 #endif /* __ultrix__ */
71 str_free(servname_old);
72 }
73 syslog_opened=1;
74 }
75
76 NOEXPORT void syslog_close(void) {
77 if(syslog_opened) {
78 if(global_options.option.log_syslog)
79 closelog();
80 syslog_opened=0;
81 }
82 }
83
84 #endif /* !defined(USE_WIN32) && !defined(__vms) */
85
86 NOEXPORT int outfile_open(void) {
87 if(global_options.output_file) { /* 'output' option specified */
88 outfile=file_open(global_options.output_file,
89 global_options.log_file_mode);
90 #if defined(USE_WIN32) && !defined(_WIN32_WCE)
91 if(!outfile) {
92 char appdata[MAX_PATH], *path;
93 if(SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE,
94 NULL, 0, appdata)==S_OK) {
95 path=str_printf("%s\\%s", appdata, global_options.output_file);
96 outfile=file_open(path, global_options.log_file_mode);
97 if(outfile)
98 s_log(LOG_NOTICE, "Logging to %s", path);
99 str_free(path);
100 }
101 }
102 #endif
103 if(!outfile) {
104 s_log(LOG_ERR, "Cannot open log file: %s",
105 global_options.output_file);
106 return 1;
107 }
108 }
109 return 0;
110 }
111
112 NOEXPORT void outfile_close(void) {
113 if(outfile) {
114 file_close(outfile);
115 outfile=NULL;
116 }
117 }
118
119 int log_open(int sink) {
120 #if !defined(USE_WIN32) && !defined(__vms)
121 if(sink&SINK_SYSLOG)
122 syslog_open();
123 #endif
124 if(sink&SINK_OUTFILE && outfile_open())
125 return 1;
126 return 0;
127 }
128
129 void log_close(int sink) {
130 /* prevent changing the mode while logging */
131 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_LOG_MODE]);
132 #if !defined(USE_WIN32) && !defined(__vms)
133 if(sink&SINK_SYSLOG)
134 syslog_close();
135 #endif
136 if(sink&SINK_OUTFILE)
137 outfile_close();
138 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOG_MODE]);
139 }
140
141 void s_log(int level, const char *format, ...) {
142 va_list ap;
143
144 va_start(ap, format);
145 s_vlog(level, format, ap);
146 va_end(ap);
147 }
148
149 #ifdef __GNUC__
150 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
151 #pragma GCC diagnostic push
152 #endif /* __GNUC__>=4.6 */
153 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
154 #endif /* __GNUC__ */
155 void s_vlog(int level, const char *format, va_list ap) {
156 #ifdef USE_WIN32
157 DWORD libc_error;
158 #else
159 int libc_error;
160 #endif
161 int socket_error;
162 TLS_DATA *tls_data;
163
164 libc_error=get_last_error();
165 socket_error=get_last_socket_error();
166
167 tls_data=tls_get();
168 if(!tls_data) {
169 tls_data=tls_alloc(NULL, NULL, "log");
170 s_log(LOG_ERR, "INTERNAL ERROR: Uninitialized TLS at %s, line %d",
171 __FILE__, __LINE__);
172 }
173
174 /* performance optimization: skip the trivial case early */
175 if(log_mode!=LOG_MODE_CONFIGURED || level<=tls_data->opt->log_level) {
176 time_t gmt;
177 struct tm ts;
178 char stamp[72], id[72], *text;
179 va_list aq;
180 int len;
181
182 /* format the id to be logged */
183 time(&gmt);
184 safe_localtime(&ts, gmt);
185 snprintf(stamp, sizeof stamp, "%04d.%02d.%02d %02d:%02d:%02d",
186 ts.tm_year+1900, ts.tm_mon+1, ts.tm_mday,
187 ts.tm_hour, ts.tm_min, ts.tm_sec);
188 snprintf(id, sizeof id, "LOG%d[%s]", level, tls_data->id);
189
190 /* format the text to be logged */
191 /* cppcheck-suppress-begin va_list_usedBeforeStarted */
192 va_copy(aq, ap);
193 len=vsnprintf(NULL, 0, format, aq);
194 va_end(aq);
195 if(len>1024)
196 len=1024;
197 text=alloca((size_t)len+1);
198 va_copy(aq, ap);
199 len=vsnprintf(text, (size_t)len+1, format, aq);
200 va_end(aq);
201 /* cppcheck-suppress-end va_list_usedBeforeStarted */
202 while(len>0 && text[len-1]=='\n')
203 text[--len]='\0'; /* strip trailing newlines */
204 safestring(text);
205
206 /* either log or queue for logging */
207 CRYPTO_THREAD_read_lock(stunnel_locks[LOCK_LOG_MODE]);
208 if(log_mode==LOG_MODE_BUFFER)
209 log_queue(tls_data->opt, level, stamp, id, text);
210 else
211 log_raw(tls_data->opt, level, stamp, id, text);
212 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOG_MODE]);
213 }
214
215 set_last_error(libc_error);
216 set_last_socket_error(socket_error);
217 }
218 #ifdef __GNUC__
219 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
220 #pragma GCC diagnostic pop
221 #endif /* __GNUC__>=4.6 */
222 #endif /* __GNUC__ */
223
224 NOEXPORT void log_queue(SERVICE_OPTIONS *opt,
225 int level, char *stamp, char *id, char *text) {
226 struct LIST *tmp;
227
228 /* make a new element */
229 tmp=str_alloc_detached(sizeof(struct LIST));
230 tmp->next=NULL;
231 tmp->opt=opt;
232 tmp->level=level;
233 tmp->stamp=str_dup_detached(stamp);
234 tmp->id=str_dup_detached(id);
235 tmp->text=str_dup_detached(text);
236
237 /* append the new element to the list */
238 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_LOG_BUFFER]);
239 if(tail)
240 tail->next=tmp;
241 else
242 head=tmp;
243 tail=tmp;
244 if(stunnel_locks[LOCK_LOG_BUFFER])
245 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOG_BUFFER]);
246 }
247
248 void log_flush(LOG_MODE new_mode) {
249 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_LOG_MODE]);
250
251 log_mode=new_mode;
252
253 /* emit the buffered logs (unless we just started buffering) */
254 if(new_mode!=LOG_MODE_BUFFER) {
255 /* log_raw() will use the new value of log_mode */
256 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_LOG_BUFFER]);
257 while(head) {
258 struct LIST *tmp=head;
259 head=head->next;
260 log_raw(tmp->opt, tmp->level, tmp->stamp, tmp->id, tmp->text);
261 str_free(tmp->stamp);
262 str_free(tmp->id);
263 str_free(tmp->text);
264 str_free(tmp);
265 }
266 head=tail=NULL;
267 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOG_BUFFER]);
268 }
269
270 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOG_MODE]);
271 }
272
273 NOEXPORT void log_raw(SERVICE_OPTIONS *opt,
274 int level, char *stamp, char *id, char *text) {
275 char *line;
276 size_t size;
277
278 /* NOTE: opt->log_level may have changed since s_log().
279 * It is important to use the new value and not the old one. */
280
281 /* build the line and log it to syslog/file if configured */
282 switch(log_mode) {
283 case LOG_MODE_CONFIGURED:
284 size=strlen(stamp)+strlen(id)+strlen(text)+4;
285 line=alloca(size);
286 snprintf(line, size, "%s %s: %s", stamp, id, text);
287 if(level<=opt->log_level) {
288 #if !defined(USE_WIN32) && !defined(__vms)
289 if(global_options.option.log_syslog)
290 syslog(level, "%s: %s", id, text);
291 #endif /* USE_WIN32, __vms */
292 if(outfile) {
293 file_putline_newline(outfile, line);
294 #ifndef USE_OS_THREADS
295 file_flush(outfile);
296 #endif /* !USE_OS_THREADS */
297 }
298 }
299 break;
300 case LOG_MODE_ERROR:
301 if(level>=LOG_INFO && level<=LOG_DEBUG)
302 return;
303 /* don't log the id or the time stamp */
304 size=strlen(text)+5;
305 line=alloca(size);
306 if(level>=LOG_EMERG && level<=LOG_NOTICE)
307 snprintf(line, size, "[%c] %s", "***!:."[level], text);
308 else /* invalid level */
309 snprintf(line, size, "[?] %s", text);
310 break;
311 default: /* LOG_MODE_INFO */
312 /* don't log the level, the id or the time stamp */
313 line=text;
314 }
315
316 /* log the line to the UI (GUI, stderr, etc.) */
317 if(log_mode==LOG_MODE_ERROR ||
318 (log_mode==LOG_MODE_INFO && level<LOG_DEBUG) ||
319 #if defined(USE_WIN32) || defined(USE_JNI)
320 level<=opt->log_level
321 #else
322 (level<=opt->log_level &&
323 opt->option.log_stderr)
324 #endif
325 )
326 ui_new_log(line);
327 }
328
329 #ifdef __GNUC__
330 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
331 #pragma GCC diagnostic push
332 #endif /* __GNUC__>=4.6 */
333 #pragma GCC diagnostic ignored "-Wformat"
334 #pragma GCC diagnostic ignored "-Wformat-extra-args"
335 #endif /* __GNUC__ */
336 char *log_id(CLI *c) {
337 const char table[62]=
338 {'0', '1', '2', '3', '4', '5', '6', '7',
339 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
340 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
341 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
342 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
343 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
344 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
345 'U', 'V', 'W', 'X', 'Y', 'Z'};
346 unsigned char rnd[22];
347 char *uniq;
348 size_t i;
349 unsigned long tid;
350
351 switch(c->opt->log_id) {
352 case LOG_ID_SEQUENTIAL:
353 return str_printf("%llu", c->seq);
354 case LOG_ID_UNIQUE:
355 memset(rnd, 0, sizeof rnd);
356 if(RAND_bytes(rnd, sizeof rnd)<=0) /* log2(62^22)=130.99 */
357 return str_dup("error");
358 for(i=0; i<sizeof rnd; ++i) {
359 rnd[i]&=63;
360 while(rnd[i]>=62) {
361 if(RAND_bytes(rnd+i, 1)<=0)
362 return str_dup("error");
363 rnd[i]&=63;
364 }
365 }
366 uniq=str_alloc(sizeof rnd+1);
367 for(i=0; i<sizeof rnd; ++i)
368 uniq[i]=table[rnd[i]];
369 uniq[sizeof rnd]='\0';
370 return uniq;
371 case LOG_ID_THREAD:
372 tid=stunnel_thread_id();
373 if(!tid) /* currently USE_FORK */
374 tid=stunnel_process_id();
375 return str_printf("%lu", tid);
376 case LOG_ID_PROCESS:
377 return str_printf("%lu", stunnel_process_id());
378 }
379 return str_dup("error");
380 }
381 #ifdef __GNUC__
382 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
383 #pragma GCC diagnostic pop
384 #endif /* __GNUC__>=4.6 */
385 #endif /* __GNUC__ */
386
387 /* critical problem handling */
388 /* str.c functions are not safe to use here */
389 #ifdef __GNUC__
390 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || defined(__clang__)
391 #pragma GCC diagnostic push
392 #pragma GCC diagnostic ignored "-Wunused-result"
393 #endif /* __GNUC__>=4.6 */
394 #endif /* __GNUC__ */
395 void fatal_debug(const char *txt, const char *file, int line) {
396 char msg[80];
397 #ifdef USE_WIN32
398 #ifdef UNICODE
399 TCHAR tmsg[80];
400 #endif
401 #endif /* USE_WIN32 */
402
403 snprintf(msg, sizeof msg, /* with newline */
404 "INTERNAL ERROR: %s at %s, line %d\n", txt, file, line);
405
406 if(outfile) {
407 file_putline_nonewline(outfile, msg);
408 file_flush(outfile);
409 }
410
411 #ifndef USE_WIN32
412 if(log_mode!=LOG_MODE_CONFIGURED || global_options.option.log_stderr) {
413 fputs(msg, stderr);
414 fflush(stderr);
415 }
416 #endif /* !USE_WIN32 */
417
418 snprintf(msg, sizeof msg, /* without newline */
419 "INTERNAL ERROR: %s at %s, line %d", txt, file, line);
420
421 #if !defined(USE_WIN32) && !defined(__vms)
422 if(global_options.option.log_syslog)
423 syslog(LOG_CRIT, "%s", msg);
424 #endif /* USE_WIN32, __vms */
425
426 #ifdef USE_WIN32
427 #ifdef UNICODE
428 if(MultiByteToWideChar(CP_UTF8, 0, msg, -1, tmsg, 80))
429 message_box(tmsg, MB_ICONERROR);
430 #else
431 message_box(msg, MB_ICONERROR);
432 #endif
433 #endif /* USE_WIN32 */
434
435 abort();
436 }
437 #ifdef __GNUC__
438 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
439 #pragma GCC diagnostic pop
440 #endif /* __GNUC__>=4.6 */
441 #endif /* __GNUC__ */
442
443 void ioerror(const char *txt) { /* input/output error */
444 log_error(LOG_ERR, (int)get_last_error(), txt);
445 }
446
447 void sockerror(const char *txt) { /* socket error */
448 log_error(LOG_ERR, get_last_socket_error(), txt);
449 }
450
451 void log_error(int level, int error, const char *txt) { /* generic error */
452 s_log(level, "%s: %s (%d)", txt, s_strerror(error), error);
453 }
454
455 char *s_strerror(int errnum) {
456 switch(errnum) {
457 #ifdef USE_WIN32
458 case 10004:
459 return "Interrupted system call (WSAEINTR)";
460 case 10009:
461 return "Bad file number (WSAEBADF)";
462 case 10013:
463 return "Permission denied (WSAEACCES)";
464 case 10014:
465 return "Bad address (WSAEFAULT)";
466 case 10022:
467 return "Invalid argument (WSAEINVAL)";
468 case 10024:
469 return "Too many open files (WSAEMFILE)";
470 case 10035:
471 return "Operation would block (WSAEWOULDBLOCK)";
472 case 10036:
473 return "Operation now in progress (WSAEINPROGRESS)";
474 case 10037:
475 return "Operation already in progress (WSAEALREADY)";
476 case 10038:
477 return "Socket operation on non-socket (WSAENOTSOCK)";
478 case 10039:
479 return "Destination address required (WSAEDESTADDRREQ)";
480 case 10040:
481 return "Message too long (WSAEMSGSIZE)";
482 case 10041:
483 return "Protocol wrong type for socket (WSAEPROTOTYPE)";
484 case 10042:
485 return "Bad protocol option (WSAENOPROTOOPT)";
486 case 10043:
487 return "Protocol not supported (WSAEPROTONOSUPPORT)";
488 case 10044:
489 return "Socket type not supported (WSAESOCKTNOSUPPORT)";
490 case 10045:
491 return "Operation not supported on socket (WSAEOPNOTSUPP)";
492 case 10046:
493 return "Protocol family not supported (WSAEPFNOSUPPORT)";
494 case 10047:
495 return "Address family not supported by protocol family (WSAEAFNOSUPPORT)";
496 case 10048:
497 return "Address already in use (WSAEADDRINUSE)";
498 case 10049:
499 return "Can't assign requested address (WSAEADDRNOTAVAIL)";
500 case 10050:
501 return "Network is down (WSAENETDOWN)";
502 case 10051:
503 return "Network is unreachable (WSAENETUNREACH)";
504 case 10052:
505 return "Net dropped connection or reset (WSAENETRESET)";
506 case 10053:
507 return "Software caused connection abort (WSAECONNABORTED)";
508 case 10054:
509 return "Connection reset by peer (WSAECONNRESET)";
510 case 10055:
511 return "No buffer space available (WSAENOBUFS)";
512 case 10056:
513 return "Socket is already connected (WSAEISCONN)";
514 case 10057:
515 return "Socket is not connected (WSAENOTCONN)";
516 case 10058:
517 return "Can't send after socket shutdown (WSAESHUTDOWN)";
518 case 10059:
519 return "Too many references, can't splice (WSAETOOMANYREFS)";
520 case 10060:
521 return "Connection timed out (WSAETIMEDOUT)";
522 case 10061:
523 return "Connection refused (WSAECONNREFUSED)";
524 case 10062:
525 return "Too many levels of symbolic links (WSAELOOP)";
526 case 10063:
527 return "File name too long (WSAENAMETOOLONG)";
528 case 10064:
529 return "Host is down (WSAEHOSTDOWN)";
530 case 10065:
531 return "No Route to Host (WSAEHOSTUNREACH)";
532 case 10066:
533 return "Directory not empty (WSAENOTEMPTY)";
534 case 10067:
535 return "Too many processes (WSAEPROCLIM)";
536 case 10068:
537 return "Too many users (WSAEUSERS)";
538 case 10069:
539 return "Disc Quota Exceeded (WSAEDQUOT)";
540 case 10070:
541 return "Stale NFS file handle (WSAESTALE)";
542 case 10091:
543 return "Network SubSystem is unavailable (WSASYSNOTREADY)";
544 case 10092:
545 return "WINSOCK DLL Version out of range (WSAVERNOTSUPPORTED)";
546 case 10093:
547 return "Successful WSASTARTUP not yet performed (WSANOTINITIALISED)";
548 case 10071:
549 return "Too many levels of remote in path (WSAEREMOTE)";
550 case 11001:
551 return "Host not found (WSAHOST_NOT_FOUND)";
552 case 11002:
553 return "Non-Authoritative Host not found (WSATRY_AGAIN)";
554 case 11003:
555 return "Non-Recoverable errors: FORMERR, REFUSED, NOTIMP (WSANO_RECOVERY)";
556 case 11004:
557 return "Valid name, no data record of requested type (WSANO_DATA)";
558 #if 0
559 case 11004: /* typically, only WSANO_DATA is reported */
560 return "No address, look for MX record (WSANO_ADDRESS)";
561 #endif
562 #endif /* defined USE_WIN32 */
563 default:
564 return strerror(errnum);
565 }
566 }
567
568 /* replace non-UTF-8 and non-printable control characters with '.' */
569 NOEXPORT void safestring(char *c) {
570 for(; *c; ++c)
571 if(!(*c&0x80 || isprint((int)*c)))
572 *c='.';
573 }
574
575 /* provide hex string corresponding to the input string
576 * will be NULL terminated */
577 void bin2hexstring(const unsigned char *in_data, size_t in_size, char *out_data, size_t out_size) {
578 const char hex[16]=
579 {'0', '1', '2', '3', '4', '5', '6', '7',
580 '8', '9' ,'A', 'B', 'C', 'D', 'E', 'F'};
581 size_t i;
582
583 for(i=0; i<in_size && 2*i+2<out_size; ++i) {
584 out_data[2*i]=hex[in_data[i]>>4];
585 out_data[2*i+1]=hex[in_data[i]&0x0f];
586 }
587 out_data[2*i]='\0';
588 }
589
590 void safe_localtime(struct tm *ts, time_t unix_time) {
591 #if defined(HAVE_LOCALTIME_R) && defined(_REENTRANT)
592 if(!localtime_r(&unix_time, ts))
593 memset(ts, 0, sizeof *ts);
594 #else
595 CRYPTO_THREAD_write_lock(stunnel_locks[LOCK_LOCALTIME]);
596 {
597 struct tm *tp=localtime(&unix_time);
598
599 if(tp)
600 memcpy(ts, tp, sizeof *ts);
601 else
602 memset(ts, 0, sizeof *ts);
603 }
604 CRYPTO_THREAD_unlock(stunnel_locks[LOCK_LOCALTIME]);
605 #endif
606 }
607 /* end of log.c */