Debian Codegraph @

internal/config/config.go

raw symbols SCIP
1 // # Copyright (C) 2025 Francois Marier
2 //
3 // Email-Reminder is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU General Public License as
5 // published by the Free Software Foundation; either version 3 of the
6 // License, or (at your option) any later version.
7 //
8 // Email-Reminder is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with Email-Reminder; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 // 02110-1301, USA.
17 package config
18
19 import (
20 "bufio"
21 _ "embed"
22 "log"
23 "os"
24 "path/filepath"
25 "regexp"
26 "strconv"
27 "strings"
28
29 "launchpad.net/email-reminder/internal/util"
30 )
31
32 //go:embed version
33 var VersionNumber string
34
35 const (
36 LegacyUserConfigFile = ".email-reminders"
37 UserConfigDir = ".config/email-reminder"
38 UserConfigFile = "reminders.xml"
39 SpoolDir = "/var/spool/email-reminder"
40 systemWideConfigFile = "email-reminder.conf" // relative to /etc
41 )
42
43 type Config struct {
44 SmtpServer string
45 SmtpUsername string
46 SmtpPassword string
47 MailFrom string
48 SendReminders bool
49 SmtpSsl bool
50
51 // Limits to prevent resource exhaustion
52 MaxEventsPerUser int
53 MaxRecipientsPerEvent int
54 MaxXMLSizeBytes int
55
56 // Runtime flags
57 Simulate bool
58 Verbose bool
59 }
60
61 var smtpServerRegex = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9.\-]*[A-Za-z0-9])$`)
62
63 func readConfig(dir string, filename string) Config {
64 // Use the local machine's hostname so that the server name matches the self-signed cert that Debian creates for STARTTLS purposes.
65 hostname, err := os.Hostname()
66 if err != nil {
67 hostname = "localhost"
68 }
69
70 // Default values
71 config := Config{
72 SendReminders: true,
73 SmtpServer: hostname,
74 SmtpSsl: false,
75 SmtpUsername: "",
76 SmtpPassword: "",
77 MailFrom: "root@localhost",
78
79 MaxEventsPerUser: 10000,
80 MaxRecipientsPerEvent: 200,
81 MaxXMLSizeBytes: 50 * 1024 * 1024, // 50MB
82 }
83
84 file, err := os.OpenInRoot(dir, filename)
85 if err != nil {
86 log.Printf("failed to open system-wide config file in /etc: %v", err)
87 log.Println("Using default configuration values")
88 return config
89 }
90 defer file.Close()
91
92 if info, err := file.Stat(); err == nil {
93 permissions := info.Mode().Perm()
94 if permissions&0024 != 0 {
95 log.Printf("Warning: '%s' has insecure permissions: %o. This file could contain sensitive credentials and should be 640 at most.", file.Name(), permissions)
96 }
97 }
98
99 scanner := bufio.NewScanner(file)
100 for scanner.Scan() {
101 // Strip out comments
102 tokens := strings.SplitN(scanner.Text(), "#", 2)
103 line := strings.TrimSpace(tokens[0])
104
105 if line == "" {
106 // Skip blank lines
107 continue
108 }
109
110 tokens = strings.Split(line, "=")
111 if len(tokens) != 2 {
112 // Stop processing invalid file
113 log.Printf("Ignoring invalid line in %s: %s", filename, line)
114 continue
115 }
116
117 key := strings.TrimSpace(tokens[0])
118 value := strings.TrimSpace(tokens[1])
119 switch key {
120 case "send_reminders":
121 b, err := util.ParseBool(value)
122 if err == nil {
123 config.SendReminders = b
124 }
125 case "smtp_server":
126 if smtpServerRegex.MatchString(value) {
127 config.SmtpServer = value
128 } else {
129 log.Printf("Ignoring invalid SMTP server '%s'", value)
130 }
131 case "smtp_ssl":
132 b, err := util.ParseBool(value)
133 if err == nil {
134 config.SmtpSsl = b
135 }
136 case "smtp_username":
137 if len(value) <= 128 {
138 config.SmtpUsername = value
139 } else {
140 log.Printf("Ignoring invalid SMTP username: length exceeds 128 characters")
141 }
142 case "smtp_password":
143 if len(value) <= 128 {
144 config.SmtpPassword = value
145 } else {
146 log.Printf("Ignoring invalid SMTP password: length exceeds 128 characters")
147 }
148 case "mail_from":
149 if err := util.ValidateEmail(value); err != nil {
150 log.Printf("Ignoring invalid mail_from '%s': %v", value, err)
151 } else {
152 config.MailFrom = value
153 }
154 case "max_events_per_user":
155 if n, err := strconv.Atoi(value); err != nil {
156 log.Printf("Ignoring invalid max_events_per_user '%s': %v", value, err)
157 } else if n <= 0 {
158 log.Printf("Ignoring invalid max_events_per_user '%s': must be positive and non-zero", value)
159 } else {
160 config.MaxEventsPerUser = n
161 }
162 case "max_recipients_per_event":
163 if n, err := strconv.Atoi(value); err != nil {
164 log.Printf("Ignoring invalid max_recipients_per_event '%s': %v", value, err)
165 } else if n <= 0 || n > 10_000 {
166 log.Printf("Ignoring invalid max_recipients_per_event '%s': must be between 1 and 10000 inclusively", value)
167 } else {
168 config.MaxRecipientsPerEvent = n
169 }
170 case "max_xml_size_mb":
171 if n, err := strconv.Atoi(value); err != nil {
172 log.Printf("Ignoring invalid max_xml_size_mb '%s': %v", value, err)
173 } else if n <= 0 || n > 1_000_000 {
174 log.Printf("Ignoring invalid max_xml_size_mb '%s': must be between 1 and 1M inclusively", value)
175 } else {
176 config.MaxXMLSizeBytes = n * 1024 * 1024
177 }
178 }
179 }
180
181 if err := scanner.Err(); err != nil {
182 log.Printf("Invalid system-wide config file %s: %s\n", filename, err)
183 }
184 return config
185 }
186
187 func ReadSystemWideConfig(simulate bool, verbose bool) Config {
188 config := readConfig("/etc", systemWideConfigFile)
189 config.Simulate = simulate
190 config.Verbose = verbose
191 return config
192 }
193
194 // Returns the name of the user's config file relative to homeDir or empty string if there isn't one
195 func GetUserConfigFilename(homeDir string) (string, []error) {
196 errors := make([]error, 0, 2)
197 preferredFilename := filepath.Join(UserConfigDir, UserConfigFile)
198 if _, err := os.Stat(filepath.Join(homeDir, preferredFilename)); err == nil {
199 return preferredFilename, nil
200 } else {
201 errors = append(errors, err)
202 }
203
204 if _, err := os.Stat(filepath.Join(homeDir, LegacyUserConfigFile)); err == nil {
205 return LegacyUserConfigFile, nil
206 } else {
207 errors = append(errors, err)
208 }
209
210 return "", errors
211 }