2

I use echo framework for creation of my API server. It is started by systemd and needs root by default, in order to aquire ports below 1024. For security I like to downgrade privileges of my go program after the listening port has been aquired by echo framework.

I know how to downgrade, but I can not find a suitable event/callback for this? The problem is, that echo.Start() and echo.StartAutoTLS() do not come back. I can create a parallel thread and try to find some status value of my echo session telling me that the port was opened, but I can not find such status indication either.

How can I make sure that I get some code executed after the port is aquired (and know for sure)?

Until now I run a parallel go thread just before server creation and wait 5 seconds to do the downgrade then. It works so far, but this is hacky and I don't like it :-(

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Volker
  • 428
  • 4
  • 15
  • Does this answer your question? https://stackoverflow.com/q/41248866/13860 – Jonathan Hall Jun 07 '21 at 07:59
  • TL;DR; what you're attempting is very difficult to impossible in Go, due to its threading model. It's usually best to use a work-around. – Jonathan Hall Jun 07 '21 at 07:59
  • you could try "ListenerAddr()" it should not return until "Start" has opened the port, as it is locked by "startupMutex" – lumos0815 Jun 07 '21 at 10:43
  • @lumos0815 This worked! I do a loop nn my extra thread until it does not return nil. If it comes back, the port was opened and I can downgrade. If you make a separate entry, I can mark it as solution! This is how I solved: func degradePrivileges(e *echo.Echo, userName string) { for { adr := e.ListenerAddr() if adr != nil { degradeMe(userName) break } time.Sleep(100 * time.Millisecond) } } – Volker Jun 07 '21 at 13:58

1 Answers1

2

You can use e.ListenerAddr() to check if the port is open. It will return nil until the port is open.

func degradePrivileges(e *echo.Echo, userName string) { 
    for { adr := e.ListenerAddr() if adr != nil { 
        degradeMe(userName) break 
    } 
    time.Sleep(100 * time.Millisecond) } 
} 
lumos0815
  • 3,908
  • 2
  • 25
  • 25