-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlogging.sh
More file actions
1964 lines (1738 loc) · 70.7 KB
/
logging.sh
File metadata and controls
1964 lines (1738 loc) · 70.7 KB
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# logging.sh - Reusable Bash Logging Module
#
# Repository: https://github.com/GingerGraham/bash-logger
#
# License: MIT License
#
# shellcheck disable=SC2034
# Note: SC2034 (unused variable) is disabled because this script is designed to be
# sourced by other scripts. Variables like LOG_LEVEL_FATAL, LOG_CONFIG_FILE, VERBOSE,
# and current_section are intentionally exported for external use or future features.
#
# Quick usage: source logging.sh && init_logger [options]
#
# Public API Functions:
# Initialization:
# - init_logger [options] : Initialize the logger with options
# - check_logger_available : Check if system logger is available
#
# Logging Functions:
# - log_debug, log_info, log_notice : Standard logging functions
# - log_warn, log_error, log_critical
# - log_alert, log_emergency, log_fatal
# - log_init, log_sensitive : Special purpose logging
# - log_to_journal <level> <message> : Force a single message to the journal
#
# Runtime Configuration:
# - set_log_level <level> : Change log level dynamically
# - set_log_format <format> : Change message format
# - set_script_name <name> : Change script name in log messages
# - set_timezone_utc <true|false> : Toggle UTC timestamps
# - set_journal_logging <true|false>: Toggle system journal logging
# - set_journal_tag <tag> : Change journal tag
# - set_syslog_facility <facility> : Change syslog facility
# - set_color_mode <auto|always|never> : Change color output
# - set_unsafe_allow_newlines <true|false> : Allow newlines in log messages (NOT RECOMMENDED)
# - set_unsafe_allow_ansi_codes <true|false> : Allow ANSI codes in log messages (NOT RECOMMENDED)
#
# Internal Functions (prefixed with _):
# Functions prefixed with underscore (_) are internal implementation details
# and should not be called directly by consuming scripts.
#
# Comprehensive documentation:
# - Getting started: docs/getting-started.md
# - Command-line options: docs/initialization.md
# - Configuration files: docs/configuration.md
# - Log levels: docs/log-levels.md
# - Output and formatting: docs/output-streams.md, docs/formatting.md
# - Advanced features: docs/journal-logging.md, docs/runtime-configuration.md
# - Troubleshooting: docs/troubleshooting.md
# Version (updated by release workflow)
# Guard against re-initialization when sourced multiple times
# Use readonly status instead of emptiness to avoid environment bypass
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* BASH_LOGGER_VERSION="; then
readonly BASH_LOGGER_VERSION="2.5.1"
# Unset potentially malicious environment variables before setting internal constants
# Only unset if not already readonly (which would indicate re-sourcing)
# This protects against environment variable override attacks
for var in LOG_LEVEL_EMERGENCY LOG_LEVEL_ALERT LOG_LEVEL_CRITICAL LOG_LEVEL_ERROR \
LOG_LEVEL_WARN LOG_LEVEL_NOTICE LOG_LEVEL_INFO LOG_LEVEL_DEBUG LOG_LEVEL_FATAL; do
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* $var="; then
unset "$var" 2>/dev/null || true
fi
done
# Unset deduplication flags that gate write-failure warnings.
# These flags are mutable (legitimately set to "yes" during normal operation) so they
# are not readonly, but they must start empty on each fresh source to prevent a
# pre-existing environment value from permanently suppressing error reporting.
unset LOGGER_FILE_ERROR_REPORTED 2>/dev/null || true
unset LOGGER_JOURNAL_ERROR_REPORTED 2>/dev/null || true
# Log levels (following complete syslog standard - higher number = less severe)
# These are readonly to prevent malicious override after initialization
readonly LOG_LEVEL_EMERGENCY=0 # System is unusable (most severe)
readonly LOG_LEVEL_ALERT=1 # Action must be taken immediately
readonly LOG_LEVEL_CRITICAL=2 # Critical conditions
readonly LOG_LEVEL_ERROR=3 # Error conditions
readonly LOG_LEVEL_WARN=4 # Warning conditions
readonly LOG_LEVEL_NOTICE=5 # Normal but significant conditions
readonly LOG_LEVEL_INFO=6 # Informational messages
readonly LOG_LEVEL_DEBUG=7 # Debug information (least severe)
readonly LOG_LEVEL_INIT=6 # Initialization messages (maps to INFO for stderr routing)
# Aliases for backward compatibility
readonly LOG_LEVEL_FATAL=$LOG_LEVEL_EMERGENCY # Alias for EMERGENCY
fi
# Default settings (these can be overridden by init_logger)
CONSOLE_LOG="true"
LOG_FILE=""
VERBOSE="false"
CURRENT_LOG_LEVEL=$LOG_LEVEL_INFO
USE_UTC="false" # Set to true to use UTC time in logs
LOG_INIT_MESSAGE="true" # Set to false to suppress the INIT message written to the log file on init_logger
# Journal logging settings
USE_JOURNAL="false"
JOURNAL_TAG="" # Tag for syslog/journal entries
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* SYSLOG_FACILITY="; then
unset SYSLOG_FACILITY 2>/dev/null || true
fi
SYSLOG_FACILITY="${SYSLOG_FACILITY:-daemon}" # Syslog facility for journal entries
# Color settings
USE_COLORS="auto" # Can be "auto", "always", or "never"
# Initialize color constants only once (guard against re-sourcing)
if [[ -z "${COLOR_RESET:-}" ]] || ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* COLOR_RESET="; then
# Unset potentially malicious color variables before setting them
# Only unset if not already readonly (which would indicate re-sourcing)
for var in COLOR_RESET COLOR_BLUE COLOR_GREEN COLOR_YELLOW COLOR_RED \
COLOR_RED_BOLD COLOR_WHITE_ON_RED COLOR_BOLD_WHITE_ON_RED \
COLOR_PURPLE COLOR_CYAN; do
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* $var="; then
unset "$var" 2>/dev/null || true
fi
done
# ANSI color codes (using $'...' syntax for literal escape characters)
# These are readonly to prevent malicious override after initialization
readonly COLOR_RESET=$'\e[0m'
readonly COLOR_BLUE=$'\e[34m'
readonly COLOR_GREEN=$'\e[32m'
readonly COLOR_YELLOW=$'\e[33m'
readonly COLOR_RED=$'\e[31m'
readonly COLOR_RED_BOLD=$'\e[31;1m'
readonly COLOR_WHITE_ON_RED=$'\e[37;41m'
readonly COLOR_BOLD_WHITE_ON_RED=$'\e[1;37;41m'
readonly COLOR_PURPLE=$'\e[35m'
readonly COLOR_CYAN=$'\e[36m'
fi
# Stream output settings
# Messages at this level and above (more severe) go to stderr, below go to stdout
# Default: ERROR (level 3) and above to stderr
LOG_STDERR_LEVEL=$LOG_LEVEL_ERROR
# Default log format
# Format variables:
# %d = date and time (YYYY-MM-DD HH:MM:SS)
# %z = timezone (UTC or LOCAL)
# %l = log level name (DEBUG, INFO, WARN, ERROR)
# %s = script name
# %m = message
# Example:
# "[%l] %d [%s] %m" => "[INFO] 2025-03-03 12:34:56 [myscript.sh] Hello world"
# "%d %z [%l] [%s] %m" => "2025-03-03 12:34:56 UTC [INFO] [myscript.sh] Hello world"
LOG_FORMAT="%d [%l] [%s] %m"
# Security: Allow newlines in log messages (NOT RECOMMENDED)
# When false (default), newlines and carriage returns are sanitized to prevent log injection
# Set to true ONLY if you have explicit control over all logged messages and log parsing is tolerant
LOG_UNSAFE_ALLOW_NEWLINES="false"
# Security: Allow ANSI escape codes in log messages (NOT RECOMMENDED)
# When false (default), ANSI escape sequences are stripped from incoming messages to prevent
# terminal manipulation attacks. ANSI codes in library-generated output (colors) are preserved.
# Set to true ONLY if you have explicit control over all logged messages and trust their source.
LOG_UNSAFE_ALLOW_ANSI_CODES="false"
# Maximum message length before formatting (defense-in-depth against excessively large messages)
# Truncation is applied to the message portion before adding timestamp, level, and script name.
# Final formatted output may exceed these limits. Set to 0 to disable limits.
LOG_MAX_LINE_LENGTH=4096
LOG_MAX_JOURNAL_LENGTH=4096
# Configuration value validation limits
# Maximum length for configuration file values (defense against malicious/malformed configs)
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* CONFIG_MAX_VALUE_LENGTH="; then
readonly CONFIG_MAX_VALUE_LENGTH=4096
# Maximum length for file paths in configuration
readonly CONFIG_MAX_PATH_LENGTH=4096
fi
# Function to detect terminal color support (internal)
_detect_color_support() {
# Default to no colors if explicitly disabled
if [[ -n "${NO_COLOR:-}" || "${CLICOLOR:-}" == "0" ]]; then
return 1
fi
# Force colors if explicitly enabled
if [[ "${CLICOLOR_FORCE:-}" == "1" ]]; then
return 0
fi
# Check if stdout is a terminal
if [[ ! -t 1 ]]; then
return 1
fi
# Check color capabilities with tput if available
if command -v tput >/dev/null 2>&1; then
if [[ $(tput colors 2>/dev/null || echo 0) -ge 8 ]]; then
return 0
fi
fi
# Check TERM as fallback
if [[ -n "${TERM:-}" && "${TERM:-}" != "dumb" ]]; then
case "${TERM:-}" in
xterm*|rxvt*|ansi|linux|screen*|tmux*|vt100|vt220|alacritty)
return 0
;;
esac
fi
return 1 # Default to no colors
}
# Function to determine if colors should be used (internal)
_should_use_colors() {
case "$USE_COLORS" in
"always")
return 0
;;
"never")
return 1
;;
"auto"|*)
_detect_color_support
return $?
;;
esac
}
# Function to determine if a log level should output to stderr (internal)
# Returns 0 (true) if the given level should go to stderr
_should_use_stderr() {
local level_value="$1"
# Lower number = more severe, so use stderr if level <= threshold
[[ "$level_value" -le "$LOG_STDERR_LEVEL" ]]
}
# Path to validated logger command (set by _find_and_validate_logger)
# Keep mutable until first successful validation, then lock as readonly.
# Guard assignment for re-source safety when LOGGER_PATH was already locked.
if ! readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* LOGGER_PATH="; then
LOGGER_PATH=""
fi
# Internal flag: set to "true" by _find_and_validate_logger on every exit path
# (success and failure alike). Used by log_to_journal to skip discovery only when
# LOGGER_PATH is already set — i.e. a previous discovery succeeded and locked the path.
# When LOGGER_PATH is empty (prior discovery failed or logger was not found), discovery
# is always retried so that logger becoming available mid-session is handled correctly.
# Not readonly — resetting to "false" on re-source is correct (new context must re-validate).
_LOGGER_DISCOVERY_DONE="false"
# Find and validate the logger command to prevent PATH manipulation attacks
# This function finds the logger executable and validates it's in a safe system location
# Returns 0 if logger is found and valid, 1 otherwise
_find_and_validate_logger() {
# Try to find logger command
local logger_candidate
logger_candidate=$(command -v logger 2>/dev/null)
if [[ -z "$logger_candidate" ]]; then
USE_JOURNAL="false"
_LOGGER_DISCOVERY_DONE="true"
return 1
fi
# Resolve any symlinks to get the real path
if command -v readlink &>/dev/null; then
logger_candidate=$(readlink -f "$logger_candidate" 2>/dev/null || echo "$logger_candidate")
fi
# Validate logger is in a safe system location
# Accept: /bin, /usr/bin, /usr/local/bin, /sbin, /usr/sbin
case "$logger_candidate" in
/bin/logger|/usr/bin/logger|/usr/local/bin/logger|/sbin/logger|/usr/sbin/logger)
# If LOGGER_PATH is already locked, only accept the same validated path.
# This preserves immutability while still allowing repeat availability checks.
if readonly -p 2>/dev/null | grep -q "declare -[^ ]*r[^ ]* LOGGER_PATH="; then
if [[ "$LOGGER_PATH" == "$logger_candidate" ]]; then
_LOGGER_DISCOVERY_DONE="true"
return 0
fi
echo "Warning: logger path changed after validation: $logger_candidate" >&2
echo " Locked logger path is: $LOGGER_PATH" >&2
echo " Journal logging disabled for security" >&2
USE_JOURNAL="false"
_LOGGER_DISCOVERY_DONE="true"
return 1
fi
LOGGER_PATH="$logger_candidate"
readonly LOGGER_PATH
_LOGGER_DISCOVERY_DONE="true"
return 0
;;
*)
# Logger found but in unexpected location - could be malicious
echo "Warning: logger found at unexpected location: $logger_candidate" >&2
echo " Expected: /bin, /usr/bin, /usr/local/bin, /sbin, or /usr/sbin" >&2
echo " Journal logging disabled for security" >&2
USE_JOURNAL="false"
_LOGGER_DISCOVERY_DONE="true"
return 1
;;
esac
}
# Check if logger command is available (legacy compatibility wrapper)
check_logger_available() {
_find_and_validate_logger
}
# Configuration file path (set by init_logger when using -c option)
LOG_CONFIG_FILE=""
# Validate a string value using shared guard checks (internal)
# Checks: empty (optional), max length, and control characters (optional)
# Returns 0 if valid, 1 otherwise
_validate_string() {
local value="$1"
local max_length="$2"
local label="$3"
local allow_empty="${4:-false}"
local check_control_chars="${5:-true}"
if [[ "$allow_empty" != "true" && -z "$value" ]]; then
echo "Error: Empty $label" >&2
return 1
fi
if [[ ${#value} -gt $max_length ]]; then
echo "Error: $label exceeds maximum length of $max_length (actual: ${#value})" >&2
return 1
fi
if [[ "$check_control_chars" == "true" && "$value" =~ [[:cntrl:]] ]]; then
echo "Error: $label contains control characters" >&2
return 1
fi
return 0
}
# Validate configuration value length (internal)
# Returns 0 if valid, 1 if too long
_validate_config_value_length() {
local value="$1"
local max_length="$2"
local key="$3"
local line_num="$4"
local label="Configuration value for '$key' at line $line_num"
if ! _validate_string "$value" "$max_length" "$label" "true" "false"; then
return 1
fi
return 0
}
# Validate file path from configuration (internal)
# Checks that path is absolute, doesn't contain control characters or dangerous patterns
# Returns 0 if valid, 1 otherwise
_validate_config_file_path() {
local path="$1"
local key="$2"
local line_num="$3"
local label="Configuration value for '$key' at line $line_num"
if ! _validate_string "$path" "$CONFIG_MAX_PATH_LENGTH" "$label" "true" "true"; then
return 1
fi
# Check for empty path
if [[ -z "$path" ]]; then
return 0 # Empty is valid (means disabled)
fi
# Must be absolute path (starts with /)
if [[ "$path" != /* ]]; then
echo "Error: Configuration value for '$key' at line $line_num must be an absolute path (got: '$path')" >&2
return 1
fi
# Check for suspicious shell metacharacter patterns that could indicate injection attempts
# Allow normal path characters but reject dangerous patterns
# Note: We check for common command injection patterns
local suspicious_patterns='(\$\(|`|; *rm|; *dd|\| *sh|&& *(rm|dd))'
if [[ "$path" =~ $suspicious_patterns ]]; then
echo "Error: Configuration value for '$key' at line $line_num contains suspicious patterns" >&2
return 1
fi
return 0
}
# Validate format string from configuration (internal)
# Checks for excessively long format strings and dangerous patterns
# Returns 0 if valid, 1 otherwise
_validate_config_format() {
local format="$1"
local line_num="$2"
# Check for control characters (except standard format specifiers)
# Allow normal format variables like %d, %l, %s, %m, %z
local clean_format="$format"
# Remove valid format specifiers
clean_format="${clean_format//\%d/}"
clean_format="${clean_format//\%l/}"
clean_format="${clean_format//\%s/}"
clean_format="${clean_format//\%m/}"
clean_format="${clean_format//\%z/}"
# Check remaining string for control characters (excluding valid format specifiers)
if ! _validate_string "$clean_format" "$CONFIG_MAX_VALUE_LENGTH" "configuration format at line $line_num" "true" "true" >/dev/null 2>&1; then
echo "Warning: Configuration format at line $line_num contains control characters (may be stripped)" >&2
fi
return 0
}
# Validate journal tag from configuration (internal)
# Checks for reasonable length and dangerous characters
# Returns 0 if valid, 1 otherwise
_validate_config_journal_tag() {
local tag="$1"
local key="$2"
local line_num="$3"
local max_tag_length=64
# Handle empty tag explicitly to preserve single-warning behavior
if [[ -z "$tag" ]]; then
echo "Warning: Empty journal tag at line $line_num" >&2
return 1
fi
if ! _validate_string "$tag" "$max_tag_length" "journal tag at line $line_num" "false" "true"; then
if [[ ${#tag} -gt $max_tag_length ]]; then
echo " Hint: Truncating to maximum length" >&2
fi
return 1
fi
# Check for shell metacharacters that could cause issues
# Character class includes: $ ` ; | & < > ( ) { } [ ] \
if [[ "$tag" =~ []$\`\;\|\&\<\>\(\)\{\}\[\\] ]]; then
echo "Warning: Journal tag at line $line_num contains shell metacharacters (will be sanitized)" >&2
return 1
fi
return 0
}
# Validate journal tag value (internal)
# Checks for reasonable length and dangerous characters
# Returns 0 if valid, 1 otherwise
_validate_journal_tag() {
local tag="$1"
local max_tag_length=64
if [[ -z "$tag" ]]; then
echo "Warning: Empty journal tag" >&2
return 1
fi
if ! _validate_string "$tag" "$max_tag_length" "journal tag" "false" "true"; then
return 1
fi
# Check for shell metacharacters that could cause issues
# Character class includes: $ ` ; | & < > ( ) { } [ ] \
if [[ "$tag" =~ []$\`\;\|\&\<\>\(\)\{\}\[\\] ]]; then
echo "Warning: Journal tag contains shell metacharacters" >&2
return 1
fi
return 0
}
# Validate syslog facility value (internal)
# Returns 0 if valid, 1 otherwise
_validate_syslog_facility() {
local facility="$1"
# Normalize facility to lowercase for case-insensitive validation
local facility_normalized="${facility,,}"
case "$facility_normalized" in
kern|user|mail|daemon|auth|syslog|lpr|news|uucp|cron|authpriv|ftp|local0|local1|local2|local3|local4|local5|local6|local7)
return 0
;;
*)
echo "Warning: Invalid syslog facility '$facility'" >&2
echo " Valid facilities: kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, authpriv, ftp, local0-local7" >&2
return 1
;;
esac
}
# Parse a boolean string value to a canonical "true" or "false" (internal)
# Accepts: true/yes/on/1 -> prints "true"; false/no/off/0 -> prints "false"
# Returns 0 on success, 1 for unrecognised input (prints nothing)
_parse_bool_value() {
local input="${1,,}"
case "$input" in
true|yes|on|1) echo "true"; return 0 ;;
false|no|off|0) echo "false"; return 0 ;;
*) return 1 ;;
esac
}
# Parse an INI-style configuration file (internal)
# Usage: _parse_config_file "/path/to/config.ini"
# Returns 0 on success, 1 on error
# Config values are applied to global variables; CLI args can override them later
_parse_config_file() {
local config_file="$1"
# Validate file exists and is readable
if [[ ! -f "$config_file" ]]; then
echo "Error: Configuration file not found" >&2
echo " Hint: Check the --config argument and verify the file path is correct" >&2
return 1
fi
if [[ ! -r "$config_file" ]]; then
echo "Error: Configuration file not readable" >&2
echo " Hint: Check file permissions and ensure the process has read access" >&2
return 1
fi
local line_num=0
local current_section=""
while IFS= read -r line || [[ -n "$line" ]]; do
((line_num++))
# Remove leading/trailing whitespace
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
# Skip empty lines and comments
[[ -z "$line" || "$line" =~ ^[#\;] ]] && continue
# Handle section headers [section]
if [[ "$line" =~ ^\[([^]]+)\]$ ]]; then
current_section="${BASH_REMATCH[1]}"
continue
fi
# Parse key = value pairs
if [[ "$line" =~ ^([^=]+)=(.*)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
# Trim whitespace from key and value
key="${key#"${key%%[![:space:]]*}"}"
key="${key%"${key##*[![:space:]]}"}"
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
# Remove surrounding quotes if present
if [[ "$value" =~ ^\"(.*)\"$ ]] || [[ "$value" =~ ^\'(.*)\'$ ]]; then
value="${BASH_REMATCH[1]}"
fi
# Validate value length for all config values (defense-in-depth)
if ! _validate_config_value_length "$value" "$CONFIG_MAX_VALUE_LENGTH" "$key" "$line_num"; then
echo " Hint: Truncating value to maximum allowed length" >&2
value="${value:0:$CONFIG_MAX_VALUE_LENGTH}"
fi
# Apply configuration based on key (case-insensitive)
case "${key,,}" in
level|log_level)
CURRENT_LOG_LEVEL=$(_get_log_level_value "$value" "$line_num")
;;
format|log_format)
# Validate format string
if _validate_config_format "$value" "$line_num"; then
LOG_FORMAT="$value"
else
echo " Hint: Skipping invalid format string, using default" >&2
fi
;;
log_file|logfile|file)
# Validate file path
if _validate_config_file_path "$value" "$key" "$line_num"; then
LOG_FILE="$value"
else
echo " Hint: Skipping invalid log file path" >&2
fi
;;
journal|use_journal)
case "${value,,}" in
true|yes|1|on)
if check_logger_available; then
USE_JOURNAL="true"
else
echo "Warning: logger command not found, journal logging disabled (config line $line_num)" >&2
fi
;;
false|no|0|off)
USE_JOURNAL="false"
;;
*)
echo "Warning: Invalid journal value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
tag|journal_tag)
if _validate_config_journal_tag "$value" "$key" "$line_num"; then
JOURNAL_TAG="$value"
else
# Truncate or sanitize if validation failed
if [[ ${#value} -gt 64 ]]; then
JOURNAL_TAG="${value:0:64}"
echo " Hint: Truncated journal tag to 64 characters" >&2
else
# Strip problematic characters
JOURNAL_TAG="${value//[^a-zA-Z0-9._-]/_}"
echo " Hint: Sanitized journal tag to remove shell metacharacters" >&2
fi
fi
;;
facility|syslog_facility)
if _validate_syslog_facility "$value"; then
SYSLOG_FACILITY="${value,,}"
else
echo " Hint: Skipping invalid syslog facility at line $line_num" >&2
fi
;;
utc|use_utc)
case "${value,,}" in
true|yes|1|on)
USE_UTC="true"
;;
false|no|0|off)
USE_UTC="false"
;;
*)
echo "Warning: Invalid utc value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
color|colour|colors|colours|use_colors)
case "${value,,}" in
auto)
USE_COLORS="auto"
;;
always|true|yes|1|on)
USE_COLORS="always"
;;
never|false|no|0|off)
USE_COLORS="never"
;;
*)
echo "Warning: Invalid color value '$value' at line $line_num, expected auto/always/never" >&2
;;
esac
;;
stderr_level|stderr-level)
LOG_STDERR_LEVEL=$(_get_log_level_value "$value" "$line_num")
;;
quiet|console_log)
case "${key,,}" in
quiet)
# quiet=true means CONSOLE_LOG=false
case "${value,,}" in
true|yes|1|on)
CONSOLE_LOG="false"
;;
false|no|0|off)
CONSOLE_LOG="true"
;;
*)
echo "Warning: Invalid quiet value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
console_log)
case "${value,,}" in
true|yes|1|on)
CONSOLE_LOG="true"
;;
false|no|0|off)
CONSOLE_LOG="false"
;;
*)
echo "Warning: Invalid console_log value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
esac
;;
script_name|scriptname|name)
# Sanitize to prevent shell metacharacter injection
SCRIPT_NAME=$(_sanitize_script_name "$value")
;;
verbose)
case "${value,,}" in
true|yes|1|on)
VERBOSE="true"
CURRENT_LOG_LEVEL=$LOG_LEVEL_DEBUG
;;
false|no|0|off)
VERBOSE="false"
;;
*)
echo "Warning: Invalid verbose value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
unsafe_allow_newlines|unsafe-allow-newlines)
if ! LOG_UNSAFE_ALLOW_NEWLINES=$(_parse_bool_value "$value"); then
echo "Warning: Invalid unsafe_allow_newlines value '$value' at line $line_num, expected true/false" >&2
fi
;;
unsafe_allow_ansi_codes|unsafe-allow-ansi-codes)
if ! LOG_UNSAFE_ALLOW_ANSI_CODES=$(_parse_bool_value "$value"); then
echo "Warning: Invalid unsafe_allow_ansi_codes value '$value' at line $line_num, expected true/false" >&2
fi
;;
max_line_length|max-line-length|log_max_line_length|log-max-line-length)
if [[ "$value" =~ ^[0-9]+$ ]] && [[ "$value" -ge 0 ]] && [[ "$value" -le 1048576 ]]; then
LOG_MAX_LINE_LENGTH="$value"
else
echo "Warning: Invalid max_line_length value '$value' at line $line_num, expected integer 0-1048576" >&2
echo " Hint: Using default value of 4096" >&2
fi
;;
max_journal_length|max-journal-length|journal_max_length|journal-max-line-length)
if [[ "$value" =~ ^[0-9]+$ ]] && [[ "$value" -ge 0 ]] && [[ "$value" -le 1048576 ]]; then
LOG_MAX_JOURNAL_LENGTH="$value"
else
echo "Warning: Invalid max_journal_length value '$value' at line $line_num, expected integer 0-1048576" >&2
echo " Hint: Using default value of 4096" >&2
fi
;;
init_message|log_init_message)
case "${value,,}" in
true|yes|1|on)
LOG_INIT_MESSAGE="true"
;;
false|no|0|off)
LOG_INIT_MESSAGE="false"
;;
*)
echo "Warning: Invalid init_message value '$value' at line $line_num, expected true/false" >&2
;;
esac
;;
*)
echo "Warning: Unknown configuration key '$key' at line $line_num" >&2
echo " Hint: Valid keys are: level, format, log_file, journal, tag, utc, color," >&2
echo " stderr_level, quiet, console_log, script_name, verbose," >&2
echo " unsafe_allow_newlines, unsafe_allow_ansi_codes, max_line_length, max_journal_length," >&2
echo " init_message" >&2
;;
esac
else
echo "Warning: Invalid syntax at line $line_num: $line" >&2
fi
done < "$config_file"
LOG_CONFIG_FILE="$config_file"
return 0
}
# Convert log level name to numeric value (internal)
_get_log_level_value() {
local level_name="$1"
local line_num="${2:-}"
case "${level_name^^}" in
"DEBUG")
echo "$LOG_LEVEL_DEBUG"
;;
"INFO")
echo "$LOG_LEVEL_INFO"
;;
"NOTICE")
echo "$LOG_LEVEL_NOTICE"
;;
"WARN" | "WARNING")
echo "$LOG_LEVEL_WARN"
;;
"ERROR" | "ERR")
echo "$LOG_LEVEL_ERROR"
;;
"CRITICAL" | "CRIT")
echo "$LOG_LEVEL_CRITICAL"
;;
"ALERT")
echo "$LOG_LEVEL_ALERT"
;;
"EMERGENCY" | "EMERG" | "FATAL")
echo "$LOG_LEVEL_EMERGENCY"
;;
*)
# If it's a number between 0-7 (valid syslog levels), use it directly
if [[ "$level_name" =~ ^[0-7]$ ]]; then
echo "$level_name"
else
# Warn if line number provided (config file context)
if [[ -n "$line_num" ]]; then
echo "Warning: Invalid log level '$level_name' at line $line_num, using INFO" >&2
echo " Hint: Valid levels are: DEBUG, INFO, NOTICE, WARN, ERROR, CRITICAL, ALERT, EMERGENCY (or 0-7)" >&2
fi
# Default to INFO if invalid
echo "$LOG_LEVEL_INFO"
fi
;;
esac
}
# Get log level name from numeric value (internal)
_get_log_level_name() {
local level_value="$1"
case "$level_value" in
"$LOG_LEVEL_DEBUG")
echo "DEBUG"
;;
"$LOG_LEVEL_INFO")
echo "INFO"
;;
"$LOG_LEVEL_NOTICE")
echo "NOTICE"
;;
"$LOG_LEVEL_WARN")
echo "WARN"
;;
"$LOG_LEVEL_ERROR")
echo "ERROR"
;;
"$LOG_LEVEL_CRITICAL")
echo "CRITICAL"
;;
"$LOG_LEVEL_ALERT")
echo "ALERT"
;;
"$LOG_LEVEL_EMERGENCY")
echo "EMERGENCY"
;;
*)
echo "UNKNOWN"
;;
esac
}
# Gets the ANSI color codes for a level name (internal)
_get_log_level_color() {
local level_name="$1"
case "$level_name" in
"DEBUG")
echo "${COLOR_BLUE}"
;;
"INFO")
echo ""
;;
"NOTICE")
echo "${COLOR_GREEN}"
;;
"WARN")
echo "${COLOR_YELLOW}"
;;
"ERROR")
echo "${COLOR_RED}"
;;
"CRITICAL")
echo "${COLOR_RED_BOLD}"
;;
"ALERT")
echo "${COLOR_WHITE_ON_RED}"
;;
"EMERGENCY"|"FATAL")
echo "${COLOR_BOLD_WHITE_ON_RED}"
;;
"INIT")
echo "${COLOR_PURPLE}"
;;
"SENSITIVE")
echo "${COLOR_CYAN}"
;;
*)
echo ""
;;
esac
}
# Map log level to syslog priority (internal)
_get_syslog_priority() {
local level_value="$1"
case "$level_value" in
"$LOG_LEVEL_DEBUG")
echo "debug"
;;
"$LOG_LEVEL_INFO")
echo "info"
;;
"$LOG_LEVEL_NOTICE")
echo "notice"
;;
"$LOG_LEVEL_WARN")
echo "warning"
;;
"$LOG_LEVEL_ERROR")
echo "err"
;;
"$LOG_LEVEL_CRITICAL")
echo "crit"
;;
"$LOG_LEVEL_ALERT")
echo "alert"
;;
"$LOG_LEVEL_EMERGENCY")
echo "emerg"
;;
*)
echo "notice" # Default to notice for unknown levels
;;
esac
}
# Write to system journal safely (internal)
# Disables journal logging after first logger availability/execution failure
_write_to_journal() {
local priority="$1"
local tag="$2"
local message="$3"
local force_when_disabled="${4:-false}"
if [[ "$force_when_disabled" != "true" && "$USE_JOURNAL" != "true" ]]; then
return 0
fi
if [[ -z "$LOGGER_PATH" || ! -x "$LOGGER_PATH" ]]; then
if [[ -z "${LOGGER_JOURNAL_ERROR_REPORTED:-}" ]]; then
echo "Warning: logger command unavailable at '$LOGGER_PATH'" >&2
echo " Journal logging disabled to prevent repeated failures" >&2
LOGGER_JOURNAL_ERROR_REPORTED="yes"
fi
USE_JOURNAL="false"
return 1
fi
"$LOGGER_PATH" -p "${SYSLOG_FACILITY}.${priority}" -t "$tag" "$message" 2>/dev/null || {
if [[ -z "${LOGGER_JOURNAL_ERROR_REPORTED:-}" ]]; then
echo "Warning: logger command failed; disabling journal logging" >&2
LOGGER_JOURNAL_ERROR_REPORTED="yes"
fi
USE_JOURNAL="false"
return 1
}
return 0
}
# Function to sanitize log messages to prevent log injection (internal)
# Removes control characters that could break log formats or inject fake entries
_strip_ansi_codes() {
local input="$1"
# If unsafe mode is enabled, skip ANSI stripping and return input as-is
if [[ "$LOG_UNSAFE_ALLOW_ANSI_CODES" == "true" ]]; then
echo "$input"
return
fi
# Remove various ANSI escape sequences using multiple patterns
# This approach removes ANSI codes that would otherwise manipulate terminal display
# Remove CSI (Control Sequence Introducer) sequences: ESC [ ... letter
# Includes color codes (\e[...m), cursor movement (\e[H), clearing (\e[2J), etc.
# Also handles DEC private modes (e.g., \e[?25l, \e[?1049h) and other parameter bytes
# Pattern: \e[ followed by zero or more parameter bytes ([<=>?!] plus digits/semicolons),
# followed by a letter or @
local esc bel
esc=$'\033'
bel=$'\a'
local step1
step1=$(printf '%s' "$input" | sed "s/${esc}\[[0-9;<?>=!]*[a-zA-Z@]//g")
# Remove OSC (Operating System Command) sequences: ESC ] ... BEL/ST
# Pattern: \e] followed by anything up to \a (BEL) or \e\\ (ST)
# First, remove BEL-terminated OSC sequences
local step2
# Remove BEL-terminated OSC sequences (match any char until BEL)
step2=$(printf '%s' "$step1" | sed "s/${esc}][^${bel}]*${bel}//g")
# Remove ST-terminated OSC sequences - loop to handle multiple sequences and embedded escapes
# Pattern: \([^ESC]\|ESC[^\\]\)* matches any char except ESC, OR ESC if not followed by \
# This allows embedded ESC codes like \e[31m while still stopping at \e\\ terminator
# The loop ensures multiple consecutive OSC sequences are all removed
step2=$(printf '%s' "$step2" | sed ":loop; s/${esc}]\(\([^${esc}]\|${esc}[^\\\\]\)*\)${esc}\\\\//g; t loop")
# Remove ST-terminated OSC sequences (ESC ] ... ESC \)
# Using | as delimiter to avoid escaping issues with backslash in pattern
local step2b
step2b=$(printf '%s' "$step2" | sed "s|${esc}][^${esc}]*${esc}\\\\||g")
# Remove DCS (Device Control String) sequences: ESC P ... ESC \