Skip to content

Commit

Permalink
Support Unix Domain Sockets (cesanta#328)
Browse files Browse the repository at this point in the history
  • Loading branch information
YC authored Nov 29, 2021
1 parent 06294f5 commit 636c09a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
25 changes: 23 additions & 2 deletions auth_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"crypto/tls"
"flag"
"math/rand"
"net"
"net/http"
"os"
"os/signal"
Expand Down Expand Up @@ -134,15 +135,35 @@ func ServeOnce(c *server.Config, cf string) (*server.AuthServer, *http.Server) {
Handler: as,
TLSConfig: tlsConfig,
}

var listener net.Listener
if c.Server.Net == "unix" {
// Remove socket, if exists
if _, err := os.Stat(c.Server.ListenAddress); err == nil {
if err := os.Remove(c.Server.ListenAddress); err != nil {
glog.Fatal(err.Error())
}
}
listener, err = net.Listen("unix", c.Server.ListenAddress)
if err != nil {
glog.Fatal(err.Error())
}
} else {
listener, err = net.Listen("tcp", c.Server.ListenAddress)
if err != nil {
glog.Fatal(err.Error())
}
}

go func() {
if c.Server.CertFile == "" && c.Server.KeyFile == "" {
if err := hs.ListenAndServe(); err != nil {
if err := hs.Serve(listener); err != nil {
if err == http.ErrServerClosed {
return
}
}
} else {
if err := hs.ListenAndServeTLS(c.Server.CertFile, c.Server.KeyFile); err != nil {
if err := hs.ServeTLS(listener, c.Server.CertFile, c.Server.KeyFile); err != nil {
if err == http.ErrServerClosed {
return
}
Expand Down
8 changes: 8 additions & 0 deletions auth_server/server/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ type Config struct {

type ServerConfig struct {
ListenAddress string `yaml:"addr,omitempty"`
Net string `yaml:"net,omitempty"`
PathPrefix string `yaml:"path_prefix,omitempty"`
RealIPHeader string `yaml:"real_ip_header,omitempty"`
RealIPPos int `yaml:"real_ip_pos,omitempty"`
Expand Down Expand Up @@ -150,6 +151,13 @@ func validate(c *Config) error {
if c.Server.ListenAddress == "" {
return errors.New("server.addr is required")
}
if c.Server.Net != "unix" && c.Server.Net != "tcp" {
if c.Server.Net == "" {
c.Server.Net = "tcp"
} else {
return errors.New("server.net must be unix or tcp")
}
}
if c.Server.PathPrefix != "" && !strings.HasPrefix(c.Server.PathPrefix, "/") {
return errors.New("server.path_prefix must be an absolute path")
}
Expand Down
4 changes: 4 additions & 0 deletions examples/reference.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@

server: # Server settings.
# Address to listen on.
# Can be HOST:PORT for TCP or file path (e.g. /run/docker_auth.sock) for Unix socket.
addr: ":5001"

# Network, can be "tcp" or "unix" ("tcp" if unspecified).
net: "tcp"

# URL path prefix to use.
path_prefix: ""

Expand Down

0 comments on commit 636c09a

Please sign in to comment.