misc: small fix or general refactoring i did not bother commenting

This commit is contained in:
Simone Margaritelli 2024-09-21 17:38:52 +02:00
commit 26c532316a
21 changed files with 355 additions and 75 deletions

View file

@ -5,6 +5,8 @@ import (
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net"
"os"
"strings"
"time"
@ -20,6 +22,27 @@ type Advertiser struct {
Acceptors []*Acceptor
}
func isPortAvailable(port int) bool {
address := fmt.Sprintf("127.0.0.1:%d", port)
if conn, err := net.DialTimeout("tcp", address, 10*time.Millisecond); err != nil {
return true
} else if conn == nil {
return true
} else {
conn.Close()
return false
}
}
func isPortRequested(svc *ServiceData, services []*ServiceData) bool {
for _, other := range services {
if svc != other && svc.Port == other.Port {
return true
}
}
return false
}
func (mod *ZeroGod) loadTLSConfig() (*tls.Config, error) {
var certFile string
var keyFile string
@ -104,6 +127,21 @@ func (mod *ZeroGod) startAdvertiser(fileName string) error {
Acceptors: make([]*Acceptor, 0),
}
// fix ports
for _, svc := range advertiser.Services {
// if no external responder has been specified, check if port is available
if svc.Responder == "" {
for svc.Port == 0 || !isPortAvailable(svc.Port) || isPortRequested(svc, services) {
newPort := (rand.Intn(65535-1024) + 1024)
mod.Warning("port %d for service %s is not avaialble, trying %d ...",
svc.Port,
svc.FullName(),
newPort)
svc.Port = newPort
}
}
}
// paralleize initialization
svcChan := make(chan error, numServices)
for _, svc := range advertiser.Services {