Skip to content

Commit

Permalink
Replace repeated subscripts with single TrimPrefix (#1176)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
klemensn authored Sep 30, 2024
1 parent ccda107 commit 874083d
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions src/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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!")
}
}
}
Expand Down

0 comments on commit 874083d

Please sign in to comment.