@marcel91200 / caddy Mirror · read-only / commits / 8e0d3e1e
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 12, 10:45 UTC

logging: set file mode when the file already exist (#6391)

101d3e7 introduced a configuration option to set the log file mode. This option was not taken into account if the file already exists, making users having to delete their logs to have new logs created with the right mode.

Ririsoft committed Jun 12, 2024 at 23:17 UTC 8e0d3e1ec56cd349f02c9d201234c56373688ddd
2 files changed +50 -1
modules/logging/filewriter.go
+11 -1
@@ -167,8 +167,18 @@ func (fw FileWriter) OpenWriter() (io.WriteCloser, error) {
167 fw.RollKeepDays = 90
168 }
169
170 - f_tmp, _ := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode))
170 + // create the file if it does not exist with the right mode.
171 + // lumberjack will reuse the file mode across log rotation.
172 + f_tmp, err := os.OpenFile(fw.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(fw.Mode))
173 + if err != nil {
174 + return nil, err
175 + }
176 f_tmp.Close()
177 + // ensure already existing files have the right mode,
178 + // since OpenFile will not set the mode in such case.
179 + if err = os.Chmod(fw.Filename, os.FileMode(fw.Mode)); err != nil {
180 + return nil, err
181 + }
182
183 return &lumberjack.Logger{
184 Filename: fw.Filename,
modules/logging/filewriter_test.go
+39
@@ -345,3 +345,42 @@ func TestFileModeToJSON(t *testing.T) {
345 })
346 }
347 }
348 +
349 +func TestFileModeModification(t *testing.T) {
350 + m := syscall.Umask(0o000)
351 + defer syscall.Umask(m)
352 +
353 + dir, err := os.MkdirTemp("", "caddytest")
354 + if err != nil {
355 + t.Fatalf("failed to create tempdir: %v", err)
356 + }
357 + defer os.RemoveAll(dir)
358 +
359 + fpath := path.Join(dir, "test.log")
360 + f_tmp, err := os.OpenFile(fpath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.FileMode(0600))
361 + if err != nil {
362 + t.Fatalf("failed to create test file: %v", err)
363 + }
364 + f_tmp.Close()
365 +
366 + fw := FileWriter{
367 + Mode: 0o666,
368 + Filename: fpath,
369 + }
370 +
371 + logger, err := fw.OpenWriter()
372 + if err != nil {
373 + t.Fatalf("failed to create file: %v", err)
374 + }
375 + defer logger.Close()
376 +
377 + st, err := os.Stat(fpath)
378 + if err != nil {
379 + t.Fatalf("failed to check file permissions: %v", err)
380 + }
381 +
382 + want := os.FileMode(fw.Mode)
383 + if st.Mode() != want {
384 + t.Errorf("file mode is %v, want %v", st.Mode(), want)
385 + }
386 +}