From 874083da790f69132c468a4f7fa5c07fbd97b5a3 Mon Sep 17 00:00:00 2001 From: Klemens Nanni Date: Mon, 30 Sep 2024 16:25:04 +0300 Subject: [PATCH] Replace repeated subscripts with single TrimPrefix (#1176) This stood out to me while reading the code: [7:] is skipping "unix://", so why not do that? Doing so reveals a bug in the last line changed, where chmod(2) failure would print just the prefix, not everything but it... easy to miss, but now this kind of bug can no longer happen. --- src/admin/admin.go | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/admin/admin.go b/src/admin/admin.go index 7cca1bbba..0b9e5e711 100644 --- a/src/admin/admin.go +++ b/src/admin/admin.go @@ -238,27 +238,28 @@ func (a *AdminSocket) listen() { if err == nil { switch strings.ToLower(u.Scheme) { case "unix": - if _, err := os.Stat(listenaddr[7:]); err == nil { - a.log.Debugln("Admin socket", listenaddr[7:], "already exists, trying to clean up") - if _, err := net.DialTimeout("unix", listenaddr[7:], time.Second*2); err == nil || err.(net.Error).Timeout() { - a.log.Errorln("Admin socket", listenaddr[7:], "already exists and is in use by another process") + file := strings.TrimPrefix(listenaddr, "unix://") + if _, err := os.Stat(file); err == nil { + a.log.Debugln("Admin socket", file, "already exists, trying to clean up") + if _, err := net.DialTimeout("unix", file, time.Second*2); err == nil || err.(net.Error).Timeout() { + a.log.Errorln("Admin socket", file, "already exists and is in use by another process") os.Exit(1) } else { - if err := os.Remove(listenaddr[7:]); err == nil { - a.log.Debugln(listenaddr[7:], "was cleaned up") + if err := os.Remove(file); err == nil { + a.log.Debugln(file, "was cleaned up") } else { - a.log.Errorln(listenaddr[7:], "already exists and was not cleaned up:", err) + a.log.Errorln(file, "already exists and was not cleaned up:", err) os.Exit(1) } } } - a.listener, err = net.Listen("unix", listenaddr[7:]) + a.listener, err = net.Listen("unix", file) if err == nil { - switch listenaddr[7:8] { + switch file[:1] { case "@": // maybe abstract namespace default: - if err := os.Chmod(listenaddr[7:], 0660); err != nil { - a.log.Warnln("WARNING:", listenaddr[:7], "may have unsafe permissions!") + if err := os.Chmod(file, 0660); err != nil { + a.log.Warnln("WARNING:", file, "may have unsafe permissions!") } } }