aboutsummaryrefslogtreecommitdiffstats
path: root/wsutil/wslog.c
blob: 98baeb699224db06cbe3649a14ac6250946a462e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
/*
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 2021 Gerald Combs
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

#include "config.h"
#include "wslog.h"

#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _WIN32
#include <process.h>
#endif
#include <ws_attributes.h>

#include <wsutil/ws_assert.h>
#include <wsutil/file_util.h>


/* Runtime log level. */
#define ENV_VAR_LEVEL       "WIRESHARK_LOG_LEVEL"

/* Log domains enabled/disabled. */
#define ENV_VAR_DOMAINS     "WIRESHARK_LOG_DOMAINS"

/* Log level that generates a trap and aborts. Can be "critical"
 * or "warning". */
#define ENV_VAR_FATAL       "WIRESHARK_LOG_FATAL"

/* Domains that will produce debug output, regardless of log level or
 * domain filter. */
#define ENV_VAR_DEBUG       "WIRESHARK_LOG_DEBUG"

/* Domains that will produce noisy output, regardless of log level or
 * domain filter. */
#define ENV_VAR_NOISY       "WIRESHARK_LOG_NOISY"


#define DEFAULT_LOG_LEVEL   LOG_LEVEL_MESSAGE


static enum ws_log_level current_log_level = LOG_LEVEL_NONE;

static gboolean color_enabled = FALSE;

static const char *registered_appname = NULL;

/* List of domains to filter. */
static GPtrArray *domain_filter = NULL;

/* List of domains to output debug level unconditionally. */
static GPtrArray *debug_filter = NULL;

/* List of domains to output noisy level unconditionally. */
static GPtrArray *noisy_filter = NULL;

/* True if active domains should match, false if actice domains should not
 * match. */
static gboolean domain_filter_positive = TRUE;

static ws_log_writer_cb *registered_log_writer = NULL;

static void *registered_log_writer_data = NULL;

static ws_log_writer_free_data_cb *registered_log_writer_data_free = NULL;

static FILE *custom_log = NULL;

static enum ws_log_level fatal_log_level = LOG_LEVEL_ERROR;


static void ws_log_cleanup(void);


const char *ws_log_level_to_string(enum ws_log_level level)
{
    switch (level) {
        case LOG_LEVEL_NONE:
            return "(none)";
        case LOG_LEVEL_ERROR:
            return "ERROR";
        case LOG_LEVEL_CRITICAL:
            return "CRITICAL";
        case LOG_LEVEL_WARNING:
            return "WARNING";
        case LOG_LEVEL_MESSAGE:
            return "MESSAGE";
        case LOG_LEVEL_INFO:
            return "INFO";
        case LOG_LEVEL_DEBUG:
            return "DEBUG";
        case LOG_LEVEL_NOISY:
            return "NOISY";
        default:
            return "(BOGUS LOG LEVEL)";
    }
}


static enum ws_log_level string_to_log_level(const char *str_level)
{
    if (!str_level)
        return LOG_LEVEL_NONE;

    if (g_ascii_strcasecmp(str_level, "noisy") == 0)
        return LOG_LEVEL_NOISY;
    else if (g_ascii_strcasecmp(str_level, "debug") == 0)
        return LOG_LEVEL_DEBUG;
    else if (g_ascii_strcasecmp(str_level, "info") == 0)
        return LOG_LEVEL_INFO;
    else if (g_ascii_strcasecmp(str_level, "message") == 0)
        return LOG_LEVEL_MESSAGE;
    else if (g_ascii_strcasecmp(str_level, "warning") == 0)
        return LOG_LEVEL_WARNING;
    else if (g_ascii_strcasecmp(str_level, "critical") == 0)
        return LOG_LEVEL_CRITICAL;
    else if (g_ascii_strcasecmp(str_level, "error") == 0)
        return LOG_LEVEL_ERROR;
    else
        return LOG_LEVEL_NONE;
}


gboolean ws_log_level_is_active(enum ws_log_level level)
{
    /*
     * Lower numerical levels have higher priority. Critical and above
     * are always enabled.
     */
    if (level <= LOG_LEVEL_CRITICAL)
        return TRUE;

    return level <= current_log_level;
}


static inline gboolean filter_contains(GPtrArray *filter, const char *domain)
{
    for (guint i = 0; i < filter->len; i++) {
        if (g_ascii_strcasecmp(filter->pdata[i], domain) == 0) {
            return TRUE;
        }
    }
    return FALSE;
}


gboolean ws_log_domain_is_active(const char *domain)
{
    if (domain_filter == NULL)
        return TRUE;

    /* We don't filter the default domain. Default means undefined, pretty much
     * every permanent call to ws_log should be using a chosen domain. */
    if (strcmp(domain, LOG_DOMAIN_DEFAULT) == 0)
        return TRUE;

    if (filter_contains(domain_filter, domain))
        return domain_filter_positive;

    return !domain_filter_positive;
}


static gboolean log_drop_message(const char *domain, enum ws_log_level level)
{
    if (noisy_filter != NULL && filter_contains(noisy_filter, domain)) {
        return FALSE;
    }

    if (debug_filter != NULL && level <= LOG_LEVEL_DEBUG &&
                                filter_contains(debug_filter, domain)) {
        return FALSE;
    }

    return !ws_log_level_is_active(level) || !ws_log_domain_is_active(domain);
}


enum ws_log_level ws_log_get_level(void)
{
    return current_log_level;
}


enum ws_log_level ws_log_set_level(enum ws_log_level log_level)
{
    ws_assert(log_level > LOG_LEVEL_NONE && log_level < _LOG_LEVEL_LAST);

    current_log_level = log_level;
    return current_log_level;
}


enum ws_log_level ws_log_set_level_str(const char *str_level)
{
    enum ws_log_level level;

    level = string_to_log_level(str_level);
    if (level == LOG_LEVEL_NONE)
        return LOG_LEVEL_NONE;

    current_log_level = level;
    return current_log_level;
}


static const char *opt_level   = "--log-level";
static const char *opt_domains = "--log-domains";
static const char *opt_file    = "--log-file";
static const char *opt_fatal   = "--log-fatal";
static const char *opt_debug   = "--log-debug";
static const char *opt_noisy   = "--log-noisy";


int ws_log_parse_args(int *argc_ptr, char *argv[], void (*print_err)(const char *, ...))
{
    char **ptr = argv;
    int count = *argc_ptr;
    int ret = 0;
    size_t optlen;
    const char *option, *value;
    int prune_extra;

    while (*ptr != NULL) {
        if (g_str_has_prefix(*ptr, opt_level)) {
            option = opt_level;
            optlen = strlen(opt_level);
        }
        else if (g_str_has_prefix(*ptr, opt_domains)) {
            option = opt_domains;
            optlen = strlen(opt_domains);
        }
        else if (g_str_has_prefix(*ptr, opt_file)) {
            option = opt_file;
            optlen = strlen(opt_file);
        }
        else if (g_str_has_prefix(*ptr, opt_fatal)) {
            option = opt_fatal;
            optlen = strlen(opt_fatal);
        }
        else if (g_str_has_prefix(*ptr, opt_debug)) {
            option = opt_debug;
            optlen = strlen(opt_debug);
        }
        else if (g_str_has_prefix(*ptr, opt_noisy)) {
            option = opt_noisy;
            optlen = strlen(opt_noisy);
        }
        else {
            ptr += 1;
            count -= 1;
            continue;
        }

        value = *ptr + optlen;
        /* Two possibilities:
         *      --<option> <value>
         * or
         *      --<option>=<value>
         */
        if (value[0] == '\0') {
            /* value is separated with blank space */
            value = *(ptr + 1);
            prune_extra = 1;

            if (value == NULL || !*value || *value == '-') {
                /* If the option value after the blank starts with '-' assume
                 * it is another option. */
                print_err("Option \"%s\" requires a value.\n", *ptr);
                option = NULL;
                prune_extra = 0;
                ret += 1;
            }
        }
        else if (value[0] == '=') {
            /* value is after equals */
            value += 1;
            prune_extra = 0;
        }
        else {
            /* Option isn't known. */
            ptr += 1;
            count -= 1;
            continue;
        }

        if (option == opt_level) {
            if (ws_log_set_level_str(value) == LOG_LEVEL_NONE) {
                print_err("Invalid log level \"%s\"\n", value);
                ret += 1;
            }
        }
        else if (option == opt_domains) {
            ws_log_set_domain_filter(value);
        }
        else if (option == opt_file) {
            FILE *fp = ws_fopen(value, "w");
            if (fp == NULL) {
                print_err("Error opening file '%s' for writing: %s\n", value, g_strerror(errno));
                ret += 1;
            }
            else {
                ws_log_add_custom_file(fp);
            }
        }
        else if (option == opt_fatal) {
            if (ws_log_set_fatal_str(value) == LOG_LEVEL_NONE) {
                print_err("Fatal log level must be \"critical\" or \"warning\", "
                          "not \"%s\".\n", value);
                ret += 1;
            }
        }
        else if (option == opt_debug) {
            ws_log_set_debug_filter(value);
        }
        else if (option == opt_noisy) {
            ws_log_set_noisy_filter(value);
        }
        else {
            /* Option value missing or invalid, do nothing. */
        }

        /*
         * We found a log option. We will remove it from
         * the argv by moving up the other strings in the array. This is
         * so that it doesn't generate an unrecognized option
         * error further along in the initialization process.
         */
        /* Include the terminating NULL in the memmove. */
        memmove(ptr, ptr + 1 + prune_extra, (count - prune_extra) * sizeof(*ptr));
        /* No need to increment ptr here. */
        count -= (1 + prune_extra);
        *argc_ptr -= (1 + prune_extra);
    }

    return ret;
}


static GPtrArray *tokenize_filter_str(const char *str_filter,
                                        gboolean *ret_positive)
{
    char *tok;
    const char *sep = ",;";
    char *list, *str;
    GPtrArray *domains;
    gboolean positive;

    ws_assert(str_filter);

    domains = g_ptr_array_new_with_free_func(g_free);

    list = str = g_strdup(str_filter);

    if (str[0] == '!') {
        positive = FALSE;
        str += 1;
    }
    else {
        positive = TRUE;
    }

    for (tok = strtok(str, sep); tok != NULL; tok = strtok(NULL, sep)) {
        g_ptr_array_add(domains, g_strdup(tok));
    }

    g_free(list);

    if (ret_positive)
        *ret_positive = positive;
    return domains;
}


void ws_log_set_domain_filter(const char *str_filter)
{
    if (domain_filter != NULL)
        g_ptr_array_free(domain_filter, TRUE);

    domain_filter = tokenize_filter_str(str_filter, &domain_filter_positive);
}


void ws_log_set_debug_filter(const char *str_filter)
{
    if (debug_filter != NULL)
        g_ptr_array_free(debug_filter, TRUE);

    debug_filter = tokenize_filter_str(str_filter, NULL);
}


void ws_log_set_noisy_filter(const char *str_filter)
{
    if (noisy_filter != NULL)
        g_ptr_array_free(noisy_filter, TRUE);

    noisy_filter = tokenize_filter_str(str_filter, NULL);
}


enum ws_log_level ws_log_set_fatal(enum ws_log_level log_level)
{
    ws_assert(log_level > LOG_LEVEL_NONE);

    /* Not possible to set lower level than "critical" to fatal. */
    if (log_level > LOG_LEVEL_CRITICAL)
        return LOG_LEVEL_NONE;

    fatal_log_level = log_level;
    return fatal_log_level;
}


enum ws_log_level ws_log_set_fatal_str(const char *str_level)
{
    enum ws_log_level level = string_to_log_level(str_level);
    return ws_log_set_fatal(level);
}


void ws_log_init(ws_log_writer_cb *writer)
{
    const char *env;

    registered_appname = g_get_prgname();

    if (writer)
        registered_log_writer = writer;

#if GLIB_CHECK_VERSION(2,50,0)
    color_enabled = g_log_writer_supports_color(ws_fileno(stderr));
#elif !defined(_WIN32)
    /* We assume every non-Windows console supports color. */
    color_enabled = (ws_isatty(ws_fileno(stderr)) == 1);
#else
     /* Our Windows build version of GLib is pretty recent, we are probably
      * fine here, unless we want to do better than GLib. */
    color_enabled = FALSE;
#endif

    current_log_level = DEFAULT_LOG_LEVEL;

    env = g_getenv(ENV_VAR_LEVEL);
    if (env != NULL && ws_log_set_level_str(env) == LOG_LEVEL_NONE)
        fprintf(stderr, "Ignoring invalid environment value %s=\"%s\".\n", ENV_VAR_LEVEL, env);

    env = g_getenv(ENV_VAR_DOMAINS);
    if (env != NULL)
        ws_log_set_domain_filter(env);

    env = g_getenv(ENV_VAR_FATAL);
    if (env != NULL && ws_log_set_fatal_str(env) == LOG_LEVEL_NONE)
        fprintf(stderr, "Ignoring invalid environment value %s=\"%s\".\n", ENV_VAR_FATAL, env);

    env = g_getenv(ENV_VAR_DEBUG);
    if (env != NULL)
        ws_log_set_debug_filter(env);

    env = g_getenv(ENV_VAR_NOISY);
    if (env != NULL)
        ws_log_set_noisy_filter(env);

    atexit(ws_log_cleanup);
}


void ws_log_init_with_data(ws_log_writer_cb *writer, void *user_data,
                              ws_log_writer_free_data_cb *free_user_data)
{
    registered_log_writer_data = user_data;
    registered_log_writer_data_free = free_user_data;
    ws_log_init(writer);
}


static inline const char *color_on(gboolean enable)
{
    return enable ? "\033[34m" : ""; /* blue */
}

static inline const char *color_off(gboolean enable)
{
    return enable ? "\033[0m" : "";
}

static void log_write_do_work(FILE *fp, gboolean use_color, const char *timestamp,
                                const char *domain,  enum ws_log_level level,
                                const char *file, int line, const char *func,
                                const char *user_format, va_list user_ap)
{
    const char *level_str = ws_log_level_to_string(level);
    gboolean doextra = (level != LOG_LEVEL_MESSAGE);

    if (doextra) {
        fprintf(fp, " ** (%s:%ld) ", registered_appname ?
                        registered_appname : "PID", (long)getpid());
    }
    else {
        fputs(" ** ", fp);
    }

    if (timestamp) {
        fputs(timestamp, fp);
        fputc(' ', fp);
    }

    if (strcmp(domain, LOG_DOMAIN_DEFAULT) != 0) {
        fprintf(fp, "[%s-%s] ", domain, level_str);
    }
    else {
        fprintf(fp, "[%s] ", level_str);
    }

    if (doextra) {
        if (file && line >= 0) {
            fprintf(fp, "%s:%d ", file, line);
        }
        else if (file) {
            fprintf(fp, "%s ", file);
        }
        fputs("-- ", fp);
        if (func) {
            fprintf(fp, "%s%s()%s: " , color_on(use_color), func, color_off(use_color));
        }
    }

    vfprintf(fp, user_format, user_ap);
    fputc('\n', fp);
    fflush(fp);
}


static void log_write_dispatch(const char *domain, enum ws_log_level level,
                            const char *file, int line, const char *func,
                            const char *user_format, va_list user_ap)
{
    GDateTime *now;
    char *tstamp = NULL;

    now = g_date_time_new_now_local();
    if (now) {
        tstamp = g_date_time_format(now, "%H:%M:%S.%f");
        g_date_time_unref(now);
    }

    if (registered_log_writer) {
        registered_log_writer(domain, level, tstamp, file, line, func,
                        user_format, user_ap, registered_log_writer_data);
    }
    else {
        log_write_do_work(stderr, color_enabled, tstamp, domain, level, file, line, func,
                        user_format, user_ap);
    }

    if (custom_log) {
        log_write_do_work(custom_log, FALSE, tstamp, domain, level, file, line, func,
                        user_format, user_ap);
    }

    g_free(tstamp);

    ws_assert(level != LOG_LEVEL_NONE);
    if (level <= fatal_log_level) {
        G_BREAKPOINT();
        ws_assert_not_reached();
    }
}


void ws_logv(const char *domain, enum ws_log_level level,
                    const char *format, va_list ap)
{
    if (domain == NULL || domain[0] == '\0')
        domain = LOG_DOMAIN_DEFAULT;

    if (log_drop_message(domain, level))
        return;

    log_write_dispatch(domain, level, NULL, -1, NULL, format, ap);
}


void ws_logv_full(const char *domain, enum ws_log_level level,
                    const char *file, int line, const char *func,
                    const char *format, va_list ap)
{
    if (domain == NULL || domain[0] == '\0')
        domain = LOG_DOMAIN_DEFAULT;

    if (log_drop_message(domain, level))
        return;

    log_write_dispatch(domain, level, file, line, func, format, ap);
}


void ws_log(const char *domain, enum ws_log_level level,
                    const char *format, ...)
{
    va_list ap;

    if (domain == NULL || domain[0] == '\0')
        domain = LOG_DOMAIN_DEFAULT;

    if (log_drop_message(domain, level))
        return;

    va_start(ap, format);
    log_write_dispatch(domain, level, NULL, -1, NULL, format, ap);
    va_end(ap);
}


void ws_log_full(const char *domain, enum ws_log_level level,
                    const char *file, int line, const char *func,
                    const char *format, ...)
{
    va_list ap;

    if (domain == NULL || domain[0] == '\0')
        domain = LOG_DOMAIN_DEFAULT;

    if (log_drop_message(domain, level))
        return;

    va_start(ap, format);
    log_write_dispatch(domain, level, file, line, func, format, ap);
    va_end(ap);
}


void ws_log_default_writer(const char *domain, enum ws_log_level level,
                            const char *timestamp,
                            const char *file, int line, const char *func,
                            const char *user_format, va_list user_ap,
                            void *user_data _U_)
{
    log_write_do_work(stderr, color_enabled, timestamp, domain, level, file, line, func, user_format, user_ap);
}


static void ws_log_cleanup(void)
{
    if (registered_log_writer_data_free) {
        registered_log_writer_data_free(registered_log_writer_data);
        registered_log_writer_data = NULL;
    }
    if (custom_log) {
        fclose(custom_log);
        custom_log = NULL;
    }
    if (domain_filter) {
        g_ptr_array_free(domain_filter, TRUE);
        domain_filter = NULL;
    }
    if (debug_filter) {
        g_ptr_array_free(debug_filter, TRUE);
        debug_filter = NULL;
    }
    if (noisy_filter) {
        g_ptr_array_free(noisy_filter, TRUE);
        noisy_filter = NULL;
    }
}


void ws_log_add_custom_file(FILE *fp)
{
        if (custom_log != NULL) {
            fclose(custom_log);
        }
        custom_log = fp;
}