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.
This commit is contained in:
Klemens Nanni 2024-09-30 16:25:04 +03:00 committed by GitHub
parent ccda1075c0
commit 874083da79
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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!")
}
}
}