File: log.c

package info (click to toggle)
brltty 6.7-3.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 31,240 kB
  • sloc: ansic: 148,859; java: 13,418; sh: 9,623; xml: 5,699; tcl: 2,634; makefile: 2,333; awk: 713; lisp: 366; python: 321; ml: 301
file content (717 lines) | stat: -rw-r--r-- 16,012 bytes parent folder | download | duplicates (3)
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/*
 * BRLTTY - A background process providing access to the console screen (when in
 *          text mode) for a blind person using a refreshable braille display.
 *
 * Copyright (C) 1995-2024 by The BRLTTY Developers.
 *
 * BRLTTY comes with ABSOLUTELY NO WARRANTY.
 *
 * This is free software, placed under the terms of the
 * GNU Lesser General Public License, as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any
 * later version. Please see the file LICENSE-LGPL for details.
 *
 * Web Page: http://brltty.app/
 *
 * This software is maintained by Dave Mielke <dave@mielke.cc>.
 */

#include "prologue.h"

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>

#ifdef __ANDROID__
#include <android/log.h>
#endif /* __ANDROID__ */

#include "log.h"
#include "log_history.h"
#include "strfmt.h"
#include "file.h"
#include "unicode.h"
#include "utf8.h"
#include "timing.h"
#include "addresses.h"
#include "stdiox.h"
#include "io_misc.h"
#include "thread.h"

const char logCategoryName_all[] = "all";
const char logCategoryPrefix_disable = '-';

const char *const logLevelNames[] = {
  "emergency", "alert", "critical", "error",
  "warning", "notice", "information", "debug"
};
const unsigned int logLevelCount = ARRAY_COUNT(logLevelNames);

unsigned char systemLogLevel = LOG_NOTICE;
unsigned char stderrLogLevel = LOG_NOTICE;

typedef struct {
  const char *name;
  const char *title;
  const char *prefix;
} LogCategoryEntry;

static const LogCategoryEntry logCategoryTable[LOG_CATEGORY_COUNT] = {
  [LOG_CATEGORY_INDEX(INPUT_PACKETS)] = {
    .name = "inpkts",
    .title = strtext("Input Packets"),
    .prefix = "input packet"
  },

  [LOG_CATEGORY_INDEX(OUTPUT_PACKETS)] = {
    .name = "outpkts",
    .title = strtext("Output Packets"),
    .prefix = "output packet"
  },

  [LOG_CATEGORY_INDEX(BRAILLE_KEYS)] = {
    .name = "brlkeys",
    .title = strtext("Braille Key Events"),
    .prefix = "braille key"
  },

  [LOG_CATEGORY_INDEX(KEYBOARD_KEYS)] = {
    .name = "kbdkeys",
    .title = strtext("Keyboard Key Events"),
    .prefix = "keyboard key"
  },

  [LOG_CATEGORY_INDEX(CURSOR_TRACKING)] = {
    .name = "csrtrk",
    .title = strtext("Cursor Tracking"),
    .prefix = "cursor tracking"
  },

  [LOG_CATEGORY_INDEX(CURSOR_ROUTING)] = {
    .name = "csrrtg",
    .title = strtext("Cursor Routing"),
    .prefix = "cursor routing"
  },

  [LOG_CATEGORY_INDEX(UPDATE_EVENTS)] = {
    .name = "update",
    .title = strtext("Update Events"),
    .prefix = "update"
  },

  [LOG_CATEGORY_INDEX(SPEECH_EVENTS)] = {
    .name = "speech",
    .title = strtext("Speech Events"),
    .prefix = "speech"
  },

  [LOG_CATEGORY_INDEX(ASYNC_EVENTS)] = {
    .name = "async",
    .title = strtext("Async Events"),
    .prefix = "async"
  },

  [LOG_CATEGORY_INDEX(SERVER_EVENTS)] = {
    .name = "server",
    .title = strtext("Server Events"),
    .prefix = "server"
  },

  [LOG_CATEGORY_INDEX(GENERIC_IO)] = {
    .name = "gio",
    .title = strtext("generic I/O"),
    .prefix = "GIO"
  },

  [LOG_CATEGORY_INDEX(SERIAL_IO)] = {
    .name = "serial",
    .title = strtext("Serial I/O"),
    .prefix = "serial"
  },

  [LOG_CATEGORY_INDEX(USB_IO)] = {
    .name = "usb",
    .title = strtext("USB I/O"),
    .prefix = "USB"
  },

  [LOG_CATEGORY_INDEX(BLUETOOTH_IO)] = {
    .name = "bt",
    .title = strtext("Bluetooth I/O"),
    .prefix = "Bluetooth"
  },

  [LOG_CATEGORY_INDEX(HID_IO)] = {
    .name = "hid",
    .title = strtext("Human Interface I/O"),
    .prefix = "HID"
  },

  [LOG_CATEGORY_INDEX(BRAILLE_DRIVER)] = {
    .name = "brldrv",
    .title = strtext("Braille Driver Events"),
    .prefix = "braille driver"
  },

  [LOG_CATEGORY_INDEX(SPEECH_DRIVER)] = {
    .name = "spkdrv",
    .title = strtext("Speech Driver Events"),
    .prefix = "speech driver"
  },

  [LOG_CATEGORY_INDEX(SCREEN_DRIVER)] = {
    .name = "scrdrv",
    .title = strtext("Screen Driver Events"),
    .prefix = "screen driver"
  },
};

unsigned char categoryLogLevel = LOG_WARNING;
unsigned char logCategoryFlags[LOG_CATEGORY_COUNT];

#if defined(WINDOWS)
static HANDLE windowsEventLog = INVALID_HANDLE_VALUE;

static WORD
toWindowsEventType (int level) {
  if (level <= LOG_ERR) return EVENTLOG_ERROR_TYPE;
  if (level <= LOG_WARNING) return EVENTLOG_WARNING_TYPE;
  return EVENTLOG_INFORMATION_TYPE;
}

#elif defined(__MSDOS__)

#elif defined(__ANDROID__)
static int
toAndroidLogPriority (int level) {
  switch (level) {
    case LOG_EMERG:   return ANDROID_LOG_FATAL;
    case LOG_ALERT:   return ANDROID_LOG_FATAL;
    case LOG_CRIT:    return ANDROID_LOG_FATAL;
    case LOG_ERR:     return ANDROID_LOG_ERROR;
    case LOG_WARNING: return ANDROID_LOG_WARN;
    case LOG_NOTICE:  return ANDROID_LOG_INFO;
    case LOG_INFO:    return ANDROID_LOG_INFO;
    case LOG_DEBUG:   return ANDROID_LOG_DEBUG;
    default:          return ANDROID_LOG_UNKNOWN;
  }
}

#elif defined(HAVE_SYSLOG_H)
static int syslogOpened = 0;
#endif /* system log internal definitions */

static LogEntry *logPrefixStack = NULL;
static FILE *logFile = NULL;

static inline const LogCategoryEntry *
getLogCategoryEntry (LogCategoryIndex index) {
  return (index < LOG_CATEGORY_COUNT)? &logCategoryTable[index]: NULL;
}

const char *
getLogCategoryName (LogCategoryIndex index) {
  const LogCategoryEntry *ctg = getLogCategoryEntry(index);

  return (ctg && ctg->name)? ctg->name: "";
}

const char *
getLogCategoryTitle (LogCategoryIndex index) {
  const LogCategoryEntry *ctg = getLogCategoryEntry(index);

  return (ctg && ctg->title)? ctg->title: "";
}

static inline void
setLogCategoryFlag (const LogCategoryEntry *ctg, unsigned char state) {
  logCategoryFlags[ctg - logCategoryTable] = state;
}

void
disableAllLogCategories (void) {
  const LogCategoryEntry *ctg = logCategoryTable;
  const LogCategoryEntry *end = ctg + LOG_CATEGORY_COUNT;

  while (ctg < end) setLogCategoryFlag(ctg++, 0);
}

int
setLogCategory (const char *name) {
  const LogCategoryEntry *ctg = logCategoryTable;
  const LogCategoryEntry *end = ctg + LOG_CATEGORY_COUNT;

  int on = 1;
  int all;

  if (*name == logCategoryPrefix_disable) {
    on = 0;
    name += 1;
  }

  all = strcasecmp(name, logCategoryName_all) == 0;

  while (ctg < end) {
    if (all || (ctg->name && (strcasecmp(name, ctg->name) == 0))) {
      setLogCategoryFlag(ctg, on);
      if (!all) return 1;
    }

    ctg += 1;
  }

  return all;
}

int
pushLogPrefix (const char *prefix) {
  if (!prefix) prefix = "";
  return pushLogEntry(&logPrefixStack, prefix, 0);
}

int
popLogPrefix (void) {
  return popLogEntry(&logPrefixStack);
}

void
closeLogFile (void) {
  if (logFile) {
    fclose(logFile);
    logFile = NULL;
  }
}

void
openLogFile (const char *path) {
  closeLogFile();
  FILE *stream = fopen(path, "w");

  if (stream) {
  //setCloseOnExec(fileno(stream), 1);
    writeUtf8ByteOrderMark(stream);
    logFile = stream;
  }
}

static void
writeLogRecord (const char *record) {
  if (logFile) {
    lockStream(logFile);

    {
      TimeValue now;
      char buffer[0X20];
      size_t length;
      unsigned int milliseconds;

      getCurrentTime(&now);
      length = formatSeconds(buffer, sizeof(buffer), "%Y-%m-%d@%H:%M:%S", now.seconds);
      milliseconds = now.nanoseconds / NSECS_PER_MSEC;

      fprintf(logFile, "%.*s.%03u ", (int)length, buffer, milliseconds);
    }

    {
      char name[0X40];
      size_t length = formatThreadName(name, sizeof(name));

      if (length) fprintf(logFile, "[%s] ", name);
    }

    fputs(record, logFile);
    fputc('\n', logFile);
    flushStream(logFile);
    unlockStream(logFile);
  }
}

void
openSystemLog (void) {
#if defined(WINDOWS)
  if (windowsEventLog == INVALID_HANDLE_VALUE) {
    windowsEventLog = RegisterEventSource(NULL, PACKAGE_TARNAME);
  }

#elif defined(__MSDOS__)
  if (!logFile) {
    char *path = makeWritablePath(PACKAGE_TARNAME ".log");

    if (path) {
      openLogFile(path);
      free(path);
    }
  }

#elif defined(__ANDROID__)

#elif defined(HAVE_SYSLOG_H)
  if (!syslogOpened) {
    openlog(PACKAGE_TARNAME, LOG_PID, LOG_DAEMON);
    syslogOpened = 1;
  }
#endif /* open system log */
}

void
closeSystemLog (void) {
#if defined(WINDOWS)
  if (windowsEventLog != INVALID_HANDLE_VALUE) {
    DeregisterEventSource(windowsEventLog);
    windowsEventLog = INVALID_HANDLE_VALUE;
  }

#elif defined(__MSDOS__)
  closeLogFile();

#elif defined(__ANDROID__)

#elif defined(HAVE_SYSLOG_H)
  if (syslogOpened) {
    closelog();
    syslogOpened = 0;
  }
#endif /* close system log */
}

int
logData (int level, LogDataFormatter *formatLogData, const void *data) {
  LogCategoryIndex category = level >> LOG_LEVEL_WIDTH;
  level &= LOG_LEVEL_MASK;

  const char *prefix;
  int push;

  if (category) {
    category -= 1;

    if (!logCategoryFlags[category]) return 0;
    if (!level) level = categoryLogLevel;

    const LogCategoryEntry *ctg = &logCategoryTable[category];
    prefix = ctg->prefix;
    push = 0;
  } else {
    prefix = NULL;
    push = level <= LOG_WARNING;
  }

  int write = level <= systemLogLevel;
  int print = level <= stderrLogLevel;
  if (!(write || print || push)) return 0;

  int oldErrno = errno;

  char record[0X1000];
  STR_BEGIN(record, sizeof(record));
  if (prefix) STR_PRINTF("%s: ", prefix);
  STR_FORMAT(formatLogData, data);
  STR_END;

  if (write) {
    writeLogRecord(record);

#if defined(WINDOWS)
    if (windowsEventLog != INVALID_HANDLE_VALUE) {
      const char *strings[] = {record};

      ReportEvent(
        windowsEventLog, toWindowsEventType(level), 0, 0, NULL,
        ARRAY_COUNT(strings), 0, strings, NULL
      );
    }

#elif defined(__MSDOS__)

#elif defined(__ANDROID__)
    __android_log_write(
      toAndroidLogPriority(level), PACKAGE_TARNAME, record
    );

#elif defined(HAVE_SYSLOG_H)
    if (syslogOpened) syslog(level, "%s", record);
#endif /* write system log */
  }

  if (print) {
    FILE *stream = stderr;
    lockStream(stream);

    if (logPrefixStack) {
      const char *prefix = getLogEntryText(logPrefixStack);

      if (*prefix) {
        fputs(prefix, stream);
        fputs(": ", stream);
      }
    }

    writeWithConsoleEncoding(stream, record, strlen(record));
    fputc('\n', stream);

    flushStream(stream);
    unlockStream(stream);
  }

  if (push) pushLogMessage(record);
  errno = oldErrno;
  return 1;
}

static size_t
formatLogArguments (char *buffer, size_t size, const char *format, va_list *arguments) {
  int length = vsnprintf(buffer, size, format, *arguments);
  if (length < 0) return 0;
  if (length < size) return length;
  return size;
}

typedef struct {
  const char *format;
  va_list *arguments;
} LogMessageData;

static size_t
formatLogMessageData (char *buffer, size_t size, const void *data) {
  const LogMessageData *msg = data;
  return formatLogArguments(buffer, size, msg->format, msg->arguments);
}

int
vlogMessage (int level, const char *format, va_list *arguments) {
  const LogMessageData msg = {
    .format = format,
    .arguments = arguments
  };

  return logData(level, formatLogMessageData, &msg);
}

int
logMessage (int level, const char *format, ...) {
  int wasLogged;
  va_list arguments;

  va_start(arguments, format);
  wasLogged = vlogMessage(level, format, &arguments);
  va_end(arguments);

  return wasLogged;
}

typedef struct {
  const char *label;
  va_list *arguments;
  const void *data;
  size_t length;
} LogBytesData;

static
STR_BEGIN_FORMATTER(formatLogBytesData, const void *data)
  const LogBytesData *bytes = data;
  const unsigned char *byte = bytes->data;
  const unsigned char *end = byte + bytes->length;

  if (bytes->label) {
    STR_FORMAT(formatLogArguments, bytes->label, bytes->arguments);
    STR_PRINTF(": ");
  }

  while (byte < end) {
    if (byte != bytes->data) STR_PRINTF(" ");
    STR_PRINTF("%2.2X", *byte++);
  }
STR_END_FORMATTER

int
logBytes (int level, const char *label, const void *data, size_t length, ...) {
  int wasLogged;
  va_list arguments;

  va_start(arguments, length);
  {
    const LogBytesData bytes = {
      .label = label,
      .arguments = &arguments,
      .data = data,
      .length = length
    };

    wasLogged = logData(level, formatLogBytesData, &bytes);
  }
  va_end(arguments);

  return wasLogged;
}

typedef struct {
  void *address;
  const char *format;
  va_list *arguments;
} LogSymbolData;

static
STR_BEGIN_FORMATTER(formatLogSymbolData, const void *data)
  const LogSymbolData *symbol = data;
  ptrdiff_t offset = 0;
  const char *name = getAddressName(symbol->address, &offset);

  STR_FORMAT(formatLogArguments, symbol->format, symbol->arguments);
  STR_PRINTF(": ");

  if (name && *name) {
    STR_PRINTF("%s", name);
    if (offset) STR_PRINTF("+%"PRIXPTR, (uintptr_t)offset);
  } else {
    STR_PRINTF("%p", symbol->address);
  }
STR_END_FORMATTER

int
logSymbol (int level, void *address, const char *format, ...) {
  int wasLogged;
  va_list arguments;

  va_start(arguments, format);
  {
    const LogSymbolData symbol = {
      .address = address,
      .format = format,
      .arguments = &arguments
    };

    wasLogged = logData(level, formatLogSymbolData, &symbol);
  }
  va_end(arguments);

  return wasLogged;
}

int
logActionProblem (int level, int error, const char *action) {
  return logMessage(level, "%s error %d: %s", action, error, strerror(error));
}

int
logActionError (int error, const char *action) {
  return logActionProblem(LOG_ERR, error, action);
}

int
logSystemProblem (int level, const char *action) {
  return logActionProblem(level, errno, action);
}

int
logSystemError (const char *action) {
  return logSystemProblem(LOG_ERR, action);
}

int
logMallocError (void) {
  return logSystemError("malloc");
}

int
logUnsupportedFeature (const char *name) {
  return logMessage(LOG_WARNING, "feature not supported: %s", name);
}

int
logUnsupportedOperation (const char *name) {
  errno = ENOSYS;
  return logSystemError(name);
}

int
logPossibleCause (const char *cause) {
  return logMessage(LOG_WARNING, "possible cause: %s", cause);
}

#ifdef WINDOWS
int
logWindowsError (DWORD error, const char *action) {
  char *message;
  DWORD count = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                              NULL, error,
                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                              (char *)&message, 0, NULL);

  if (count) {
    char *end = strpbrk(message, "\r\n");

    if (end) *end = 0;
  } else {
    message = "unknown";
  }

  int wasLogged = logMessage(LOG_ERR, "%s error %d: %s", action, (int)error, message);
  if (count) LocalFree(message);
  return wasLogged;
}

int
logWindowsSystemError (const char *action) {
  DWORD error = GetLastError();
  return logWindowsError(error, action);
}

#ifdef __MINGW32__
int
logWindowsSocketError (const char *action) {
  DWORD error = WSAGetLastError();
  return logWindowsError(error, action);
}
#endif /* __MINGW32__ */
#endif /* WINDOWS */

static int
logBacktraceString (const char *string) {
  return logMessage(LOG_DEBUG, "backtrace: %s", string);
}

#if defined(HAVE_EXECINFO_H)
#include <execinfo.h>

int
logBacktrace (void) {
  const int limit = 30;
  void *frames[limit];
  int count = backtrace(frames, limit);

  if (count > 0) {
    char **strings;

    if ((strings = backtrace_symbols(frames, count))) {
      char **string = strings;
      char **end = string + count;

      while (string < end) {
        if (!logBacktraceString(*string)) return 0;
        string += 1;
      }

      if (count == limit) {
        if (!logBacktraceString("...")) return 0;
      }

      free(strings);
    } else {
      logSystemError("backtrace_symbols");
    }
  } else {
    if (!logBacktraceString("no frames")) return 0;
  }

  return 1;
}

#else /* log backtrace */
int
logBacktrace (void) {
  return logBacktraceString("not supported");
}
#endif /* log backtrace */