106 lines
2.1 KiB
Go
106 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"log"
|
|
"net"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"syscall"
|
|
)
|
|
|
|
func main() {
|
|
running := true
|
|
instance_path, err := get_instance_path()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
instance, err := filepath.EvalSymlinks(instance_path)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
socket_path, err := filepath.Abs(filepath.Join(instance, "/boundaries.sock"))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
ln, err := net.Listen("unix", socket_path)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
log.Println("Listening on", instance+"/boundaries.sock")
|
|
signalChannel := make(chan os.Signal, 1)
|
|
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM)
|
|
go func() {
|
|
sig := <-signalChannel
|
|
switch sig {
|
|
case os.Interrupt:
|
|
running = false
|
|
log.Println("Received interrupt")
|
|
ln.Close()
|
|
os.Exit(0)
|
|
case syscall.SIGTERM:
|
|
running = false
|
|
log.Println("Received SIGTERM")
|
|
ln.Close()
|
|
os.Exit(15)
|
|
}
|
|
}()
|
|
|
|
accept_clients(&ln, &instance, &running)
|
|
}
|
|
|
|
func path_exists(path string) (bool, error) {
|
|
_, err := os.Stat(path)
|
|
if err == nil {
|
|
return true, nil
|
|
}
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
|
|
func accept_clients(ln *net.Listener, instance *string, running *bool) {
|
|
for *running {
|
|
conn, err := (*ln).Accept()
|
|
if err != nil {
|
|
if !(*running) {
|
|
continue
|
|
}
|
|
log.Println(err)
|
|
}
|
|
go func() {
|
|
err := client(conn, *instance)
|
|
if err != nil {
|
|
conn.Write([]byte(err.Error()))
|
|
}
|
|
conn.Close()
|
|
}()
|
|
}
|
|
}
|
|
|
|
func get_instance_path() (string, error) {
|
|
if len(os.Args) == 2 {
|
|
return filepath.Abs(os.Args[1])
|
|
}
|
|
|
|
// When bndd has been started by boundaries, this can be used to get the instance it used
|
|
app_dir, has := os.LookupEnv("APP_DIR")
|
|
if has {
|
|
return filepath.Abs(filepath.Join(app_dir, "..", ".."))
|
|
}
|
|
|
|
// Fallback to the user-path
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
home_instance_path, err := filepath.Abs(filepath.Join(home, "boundaries"))
|
|
if exists, err := path_exists(home_instance_path); exists && err == nil {
|
|
return home_instance_path, nil
|
|
}
|
|
|
|
return "", errors.New("no suitable instance path found")
|
|
}
|