├── VERSION ├── .golangci.toml ├── .envrc ├── examples ├── client-token.secret ├── relay-token.secret ├── client-base.toml ├── client-destination.toml ├── client-source.toml ├── routes.toml └── minimal.toml ├── .gitignore ├── nix ├── client-module.nix ├── relay-server-module.nix ├── server-module.nix ├── control-server-module.nix ├── docker.nix ├── package.nix └── module.nix ├── quicc ├── rtt.go ├── conn.go └── conf.go ├── netc ├── addrs_test.go ├── name.go ├── prefix.go ├── join.go └── addrs.go ├── model ├── build.go ├── hostport.go ├── key.go ├── route.go ├── endpoint.go ├── loadbalance.go ├── role.go ├── proxy.go ├── protos.go └── encryption.go ├── restr ├── name.go ├── name_test.go ├── ip_test.go └── ip.go ├── control ├── relay_id.go ├── client_id.go ├── ingress.go ├── secrets.go ├── server.go └── store.go ├── certc ├── json.go └── cert.go ├── proto ├── model.proto ├── pbclient │ └── proto.go ├── pberror │ └── error.go ├── pbconnect │ └── proto.go ├── error.proto ├── connect.proto ├── relay.proto ├── pbmodel │ └── addr.go ├── client.proto └── proto.go ├── iterc ├── slices.go └── iter.go ├── notify ├── value_test.go └── value.go ├── cryptoc ├── derive_test.go ├── streamer.go ├── derive.go ├── hkdf.go ├── stream_test.go └── stream.go ├── statusc ├── status.go └── server.go ├── reliable ├── time.go ├── backoff.go ├── group_test.go └── group.go ├── nat ├── local.go └── resolver.go ├── process-compose.yaml ├── go.mod ├── selfhosted ├── relays.go └── clients.go ├── websocketc └── join.go ├── slogc └── log.go ├── .github └── workflows │ ├── release-tag.yml │ ├── ci.yml │ ├── tip.yaml │ └── release.yml ├── flake.lock ├── destination_config.go ├── source_config.go ├── Makefile ├── server ├── server.go └── config.go ├── relay ├── store.go ├── server.go └── ingress.go ├── relay.go ├── direct.go ├── logc └── log.go ├── go.sum ├── destinations.go ├── cmd └── connet │ ├── server.go │ ├── relay.go │ └── main.go ├── endpoint.go └── config.go /VERSION: -------------------------------------------------------------------------------- 1 | 0.10.1 2 | -------------------------------------------------------------------------------- /.golangci.toml: -------------------------------------------------------------------------------- 1 | version = "2" 2 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | layout go 3 | -------------------------------------------------------------------------------- /examples/client-token.secret: -------------------------------------------------------------------------------- 1 | xxyxx 2 | -------------------------------------------------------------------------------- /examples/relay-token.secret: -------------------------------------------------------------------------------- 1 | yyxyy 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | .direnv 3 | result 4 | dist 5 | -------------------------------------------------------------------------------- /examples/client-base.toml: -------------------------------------------------------------------------------- 1 | log-level = "debug" 2 | 3 | [client] 4 | token-file = "examples/client-token.secret" 5 | server-cas-file = ".direnv/minica.pem" 6 | direct-addr = ":" 7 | -------------------------------------------------------------------------------- /nix/client-module.nix: -------------------------------------------------------------------------------- 1 | { config, lib, pkgs, ... }: 2 | import ./module.nix { 3 | inherit config lib pkgs; 4 | role = "client"; 5 | ports = [ 6 | { path = [ "client" "direct-addr" ]; default = ":19192"; } 7 | ]; 8 | } 9 | -------------------------------------------------------------------------------- /nix/relay-server-module.nix: -------------------------------------------------------------------------------- 1 | { config, lib, pkgs, ... }: 2 | import ./module.nix { 3 | inherit config lib pkgs; 4 | role = "relay"; 5 | hasStorage = true; 6 | ports = [ 7 | { path = [ "relay" "addr" ]; default = ":19191"; } 8 | ]; 9 | } 10 | -------------------------------------------------------------------------------- /examples/client-destination.toml: -------------------------------------------------------------------------------- 1 | log-level = "debug" 2 | 3 | [client] 4 | token-file = "examples/client-token.secret" 5 | server-cas-file = ".direnv/minica.pem" 6 | 7 | [client.destinations.sws] 8 | relay-encryptions = ["tls", "dhxcp"] 9 | url = "file:." 10 | -------------------------------------------------------------------------------- /examples/client-source.toml: -------------------------------------------------------------------------------- 1 | log-level = "debug" 2 | 3 | [client] 4 | token-file = "examples/client-token.secret" 5 | server-cas-file = ".direnv/minica.pem" 6 | direct-addr = ":19193" 7 | 8 | [client.sources.sws] 9 | relay-encryptions = ["tls"] 10 | url = "tcp://:9999" 11 | -------------------------------------------------------------------------------- /quicc/rtt.go: -------------------------------------------------------------------------------- 1 | package quicc 2 | 3 | import ( 4 | "log/slog" 5 | 6 | "github.com/quic-go/quic-go" 7 | ) 8 | 9 | func LogRTTStats(conn *quic.Conn, logger *slog.Logger) { 10 | stats := conn.ConnectionStats() 11 | logger.Debug("rtt stats", "last", stats.LatestRTT, "smoothed", stats.SmoothedRTT) 12 | } 13 | -------------------------------------------------------------------------------- /netc/addrs_test.go: -------------------------------------------------------------------------------- 1 | package netc 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestLocalAddrs(t *testing.T) { 11 | ls, err := LocalAddrs() 12 | require.NoError(t, err) 13 | 14 | for _, l := range ls { 15 | fmt.Println("addr:", l) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /nix/server-module.nix: -------------------------------------------------------------------------------- 1 | { config, lib, pkgs, ... }: 2 | import ./module.nix { 3 | inherit config lib pkgs; 4 | role = "server"; 5 | hasCerts = true; 6 | hasStorage = true; 7 | ports = [ 8 | { path = [ "server" "addr" ]; default = ":19190"; } 9 | { path = [ "server" "relay-addr" ]; default = ":19191"; } 10 | ]; 11 | } 12 | -------------------------------------------------------------------------------- /nix/control-server-module.nix: -------------------------------------------------------------------------------- 1 | { config, lib, pkgs, ... }: 2 | import ./module.nix { 3 | inherit config lib pkgs; 4 | role = "control"; 5 | hasCerts = true; 6 | hasStorage = true; 7 | ports = [ 8 | { path = [ "control" "clients-addr" ]; default = ":19190"; } 9 | { path = [ "control" "relays-addr" ]; default = ":19189"; } 10 | ]; 11 | } 12 | -------------------------------------------------------------------------------- /model/build.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "runtime/debug" 4 | 5 | // Injected by ldflags 6 | var Version string 7 | 8 | func BuildVersion() string { 9 | if Version != "" { 10 | return Version 11 | } 12 | 13 | if bi, ok := debug.ReadBuildInfo(); ok { 14 | for _, setting := range bi.Settings { 15 | if setting.Key == "vcs.revision" { 16 | return setting.Value 17 | } 18 | } 19 | } 20 | 21 | return "/+unknown+/" 22 | } 23 | -------------------------------------------------------------------------------- /restr/name.go: -------------------------------------------------------------------------------- 1 | package restr 2 | 3 | import "regexp" 4 | 5 | type Name struct { 6 | Expression *regexp.Regexp `json:"expression,omitempty"` 7 | } 8 | 9 | func ParseName(s string) (Name, error) { 10 | exp, err := regexp.Compile(s) 11 | if err != nil { 12 | return Name{}, err 13 | } 14 | return Name{exp}, nil 15 | } 16 | 17 | func (r Name) IsAllowed(s string) bool { 18 | if r.Expression == nil { 19 | return true 20 | } 21 | return r.Expression.MatchString(s) 22 | } 23 | -------------------------------------------------------------------------------- /control/relay_id.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import "github.com/connet-dev/connet/netc" 4 | 5 | type RelayID struct{ string } 6 | 7 | var RelayIDNil = RelayID{""} 8 | 9 | func NewRelayID() RelayID { 10 | return RelayID{netc.GenName()} 11 | } 12 | 13 | func (k RelayID) String() string { 14 | return k.string 15 | } 16 | 17 | func (k RelayID) MarshalText() ([]byte, error) { 18 | return []byte(k.string), nil 19 | } 20 | 21 | func (k *RelayID) UnmarshalText(b []byte) error { 22 | k.string = string(b) 23 | return nil 24 | } 25 | -------------------------------------------------------------------------------- /control/client_id.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import "github.com/connet-dev/connet/netc" 4 | 5 | type ClientID struct{ string } 6 | 7 | var ClientIDNil = ClientID{""} 8 | 9 | func NewClientID() ClientID { 10 | return ClientID{netc.GenName()} 11 | } 12 | 13 | func (k ClientID) String() string { 14 | return k.string 15 | } 16 | 17 | func (k ClientID) MarshalText() ([]byte, error) { 18 | return []byte(k.string), nil 19 | } 20 | 21 | func (k *ClientID) UnmarshalText(b []byte) error { 22 | k.string = string(b) 23 | return nil 24 | } 25 | -------------------------------------------------------------------------------- /netc/name.go: -------------------------------------------------------------------------------- 1 | package netc 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/base32" 6 | "fmt" 7 | "io" 8 | ) 9 | 10 | var DNSSECEncoding = base32.NewEncoding("0123456789abcdefghijklmnopqrstuv").WithPadding(base32.NoPadding) 11 | 12 | func GenDomainName(suffix string) string { 13 | return fmt.Sprintf("%s.%s.invalid", GenName(), suffix) 14 | } 15 | 16 | func GenName() string { 17 | data := make([]byte, 32) 18 | if _, err := io.ReadFull(rand.Reader, data); err != nil { 19 | panic(err) 20 | } 21 | return DNSSECEncoding.EncodeToString(data) 22 | } 23 | -------------------------------------------------------------------------------- /certc/json.go: -------------------------------------------------------------------------------- 1 | package certc 2 | 3 | import ( 4 | "crypto/x509" 5 | "encoding/json" 6 | ) 7 | 8 | func MarshalJSONCert(cert *x509.Certificate) ([]byte, error) { 9 | s := struct { 10 | Cert []byte `json:"cert"` 11 | }{ 12 | Cert: cert.Raw, 13 | } 14 | return json.Marshal(s) 15 | } 16 | 17 | func UnmarshalJSONCert(b []byte) (*x509.Certificate, error) { 18 | s := struct { 19 | Cert []byte `json:"cert"` 20 | }{} 21 | 22 | if err := json.Unmarshal(b, &s); err != nil { 23 | return nil, err 24 | } 25 | 26 | return x509.ParseCertificate(s.Cert) 27 | } 28 | -------------------------------------------------------------------------------- /proto/model.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package model; 3 | 4 | option go_package = "github.com/connet-dev/connet/proto/pbmodel"; 5 | 6 | message Addr { 7 | bytes v4 = 1; 8 | bytes v6 = 2; 9 | } 10 | 11 | message AddrPort { 12 | Addr addr = 1; 13 | uint32 port = 2; // really uint16, but not a thing in protobuf 14 | } 15 | 16 | message HostPort { 17 | string host = 1; 18 | uint32 port = 2; 19 | } 20 | 21 | message Endpoint { 22 | string name = 1; 23 | } 24 | 25 | enum Role { 26 | RoleUnknown = 0; 27 | RoleDestination = 1; 28 | RoleSource = 2; 29 | } 30 | -------------------------------------------------------------------------------- /iterc/slices.go: -------------------------------------------------------------------------------- 1 | package iterc 2 | 3 | import ( 4 | "fmt" 5 | "slices" 6 | ) 7 | 8 | func MapSlice[S ~[]P, P any, R any](s S, f func(P) R) []R { 9 | return slices.Collect(Map(slices.Values(s), f)) 10 | } 11 | 12 | func MapSliceStrings[S ~[]P, P fmt.Stringer](s S) []string { 13 | return slices.Collect(Map(slices.Values(s), P.String)) 14 | } 15 | 16 | func FilterSlice[S ~[]P, P any](s S, f func(P) bool) S { 17 | return slices.Collect(Filter(slices.Values(s), f)) 18 | } 19 | 20 | func FlattenSlice[SP ~[]S, S ~[]P, P any](sp SP) S { 21 | return slices.Collect(Flatten(slices.Values(sp))) 22 | } 23 | -------------------------------------------------------------------------------- /notify/value_test.go: -------------------------------------------------------------------------------- 1 | package notify 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestNV(t *testing.T) { 12 | n := NewEmpty[int]() 13 | 14 | go func() { 15 | for i := 0; i <= 1000; i++ { 16 | n.Set(i) 17 | } 18 | }() 19 | 20 | version := uint64(0) 21 | observed := 0 22 | for { 23 | v, next, err := n.Get(context.Background(), version) 24 | require.NoError(t, err) 25 | version = next 26 | observed++ 27 | if v == 1000 { 28 | break 29 | } 30 | } 31 | fmt.Println("observed", observed) 32 | } 33 | -------------------------------------------------------------------------------- /cryptoc/derive_test.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/ecdh" 5 | "crypto/rand" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestDeriveKeys(t *testing.T) { 12 | srcKey, err := ecdh.X25519().GenerateKey(rand.Reader) 13 | require.NoError(t, err) 14 | dstKey, err := ecdh.X25519().GenerateKey(rand.Reader) 15 | require.NoError(t, err) 16 | 17 | sl, sr, err := DeriveKeys(srcKey, dstKey.PublicKey(), true) 18 | require.NoError(t, err) 19 | dl, dr, err := DeriveKeys(dstKey, srcKey.PublicKey(), false) 20 | require.NoError(t, err) 21 | 22 | require.Equal(t, sl, dl) 23 | require.Equal(t, sr, dr) 24 | } 25 | -------------------------------------------------------------------------------- /quicc/conn.go: -------------------------------------------------------------------------------- 1 | package quicc 2 | 3 | import ( 4 | "net" 5 | 6 | "github.com/quic-go/quic-go" 7 | ) 8 | 9 | func StreamConn(s *quic.Stream, c *quic.Conn) net.Conn { 10 | return &streamConn{ 11 | Stream: s, 12 | Local: c.LocalAddr(), 13 | Remote: c.RemoteAddr(), 14 | } 15 | } 16 | 17 | type streamConn struct { 18 | *quic.Stream 19 | Local net.Addr 20 | Remote net.Addr 21 | } 22 | 23 | func (s *streamConn) LocalAddr() net.Addr { 24 | return s.Local 25 | } 26 | 27 | func (s *streamConn) RemoteAddr() net.Addr { 28 | return s.Remote 29 | } 30 | 31 | func (s *streamConn) Close() error { 32 | s.CancelRead(0) 33 | return s.Stream.Close() 34 | } 35 | -------------------------------------------------------------------------------- /proto/pbclient/proto.go: -------------------------------------------------------------------------------- 1 | package pbclient 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/connet-dev/connet/proto" 8 | ) 9 | 10 | func ReadRequest(r io.Reader) (*Request, error) { 11 | req := &Request{} 12 | if err := proto.Read(r, req); err != nil { 13 | return nil, fmt.Errorf("server request read: %w", err) 14 | } 15 | return req, nil 16 | } 17 | 18 | func ReadResponse(r io.Reader) (*Response, error) { 19 | resp := &Response{} 20 | if err := proto.Read(r, resp); err != nil { 21 | return nil, fmt.Errorf("server response read: %w", err) 22 | } 23 | if resp.Error != nil { 24 | return nil, resp.Error 25 | } 26 | return resp, nil 27 | } 28 | -------------------------------------------------------------------------------- /examples/routes.toml: -------------------------------------------------------------------------------- 1 | log-level = "debug" 2 | 3 | [server] 4 | tokens-file = "examples/client-token.secret" 5 | 6 | [[server.ingress]] 7 | cert-file = ".direnv/localhost/cert.pem" 8 | key-file = ".direnv/localhost/key.pem" 9 | 10 | [client] 11 | token-file = "examples/client-token.secret" 12 | server-cas-file = ".direnv/minica.pem" 13 | 14 | [client.destinations.sws-direct] 15 | route = "direct" 16 | url = "file:." 17 | 18 | [client.sources.sws-direct] 19 | route = "direct" 20 | url = "tcp://:9999" 21 | 22 | [client.destinations.sws-relay] 23 | route = "relay" 24 | url = "file:." 25 | 26 | [client.sources.sws-relay] 27 | route = "relay" 28 | url = "tcp://:9998" 29 | -------------------------------------------------------------------------------- /proto/pberror/error.go: -------------------------------------------------------------------------------- 1 | package pberror 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | 7 | "github.com/quic-go/quic-go" 8 | ) 9 | 10 | func NewError(code Code, msg string, args ...any) *Error { 11 | return &Error{ 12 | Code: code, 13 | Message: fmt.Sprintf(msg, args...), 14 | } 15 | } 16 | 17 | func (e *Error) Error() string { 18 | return fmt.Sprintf("%s (%d)", e.Message, e.Code) 19 | } 20 | 21 | func GetError(err error) *Error { 22 | var e *Error 23 | if errors.As(err, &e) { 24 | return e 25 | } 26 | return nil 27 | } 28 | 29 | func GetAppError(err error) *quic.ApplicationError { 30 | var e *quic.ApplicationError 31 | if errors.As(err, &e) { 32 | return e 33 | } 34 | return nil 35 | } 36 | -------------------------------------------------------------------------------- /iterc/iter.go: -------------------------------------------------------------------------------- 1 | package iterc 2 | 3 | import ( 4 | "iter" 5 | ) 6 | 7 | func Map[P any, R any](it iter.Seq[P], f func(P) R) iter.Seq[R] { 8 | return func(yield func(R) bool) { 9 | for p := range it { 10 | if !yield(f(p)) { 11 | return 12 | } 13 | } 14 | } 15 | } 16 | 17 | func Filter[P any](it iter.Seq[P], f func(P) bool) iter.Seq[P] { 18 | return func(yield func(P) bool) { 19 | for p := range it { 20 | if f(p) { 21 | if !yield(p) { 22 | return 23 | } 24 | } 25 | } 26 | } 27 | } 28 | 29 | func Flatten[S ~[]P, P any](it iter.Seq[S]) iter.Seq[P] { 30 | return func(yield func(P) bool) { 31 | for s := range it { 32 | for _, p := range s { 33 | if !yield(p) { 34 | return 35 | } 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /netc/prefix.go: -------------------------------------------------------------------------------- 1 | package netc 2 | 3 | import ( 4 | "fmt" 5 | "net/netip" 6 | ) 7 | 8 | func ParseCIDRs(strs []string) ([]netip.Prefix, error) { 9 | var err error 10 | cidrs := make([]netip.Prefix, len(strs)) 11 | for i, str := range strs { 12 | cidrs[i], err = ParseCIDR(str) 13 | if err != nil { 14 | return nil, fmt.Errorf("parse CIDR at %d: %w", i, err) 15 | } 16 | } 17 | return cidrs, nil 18 | } 19 | 20 | func ParseCIDR(str string) (netip.Prefix, error) { 21 | if cidr, err := netip.ParsePrefix(str); err == nil { 22 | return cidr, nil 23 | } else if addr, aerr := netip.ParseAddr(str); aerr == nil { 24 | return netip.PrefixFrom(addr, addr.BitLen()), nil 25 | } else { 26 | return netip.Prefix{}, fmt.Errorf("parse CIDR %s: %w", str, err) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /model/hostport.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/connet-dev/connet/iterc" 7 | "github.com/connet-dev/connet/proto/pbmodel" 8 | ) 9 | 10 | type HostPort struct { 11 | Host string `json:"host"` 12 | Port uint16 `json:"port"` 13 | } 14 | 15 | func HostPortFromPB(h *pbmodel.HostPort) HostPort { 16 | return HostPort{ 17 | Host: h.Host, 18 | Port: uint16(h.Port), 19 | } 20 | } 21 | 22 | func HostPortFromPBs(hs []*pbmodel.HostPort) []HostPort { 23 | return iterc.MapSlice(hs, HostPortFromPB) 24 | } 25 | 26 | func (h HostPort) PB() *pbmodel.HostPort { 27 | return &pbmodel.HostPort{ 28 | Host: h.Host, 29 | Port: uint32(h.Port), 30 | } 31 | } 32 | 33 | func (h HostPort) String() string { 34 | return fmt.Sprintf("%s:%d", h.Host, h.Port) 35 | } 36 | -------------------------------------------------------------------------------- /model/key.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "crypto/x509" 5 | 6 | "github.com/connet-dev/connet/netc" 7 | "golang.org/x/crypto/blake2s" 8 | ) 9 | 10 | type Key struct{ string } 11 | 12 | func NewKey(cert *x509.Certificate) Key { 13 | return newKeyRaw(cert.Raw) 14 | } 15 | 16 | func newKeyRaw(raw []byte) Key { 17 | hash := blake2s.Sum256(raw) 18 | return Key{netc.DNSSECEncoding.EncodeToString(hash[:])} 19 | } 20 | 21 | func NewKeyString(s string) Key { 22 | return Key{s} 23 | } 24 | 25 | func (k Key) String() string { 26 | return k.string 27 | } 28 | 29 | func (k Key) IsValid() bool { 30 | return k.string != "" 31 | } 32 | 33 | func (k Key) MarshalText() ([]byte, error) { 34 | return []byte(k.string), nil 35 | } 36 | 37 | func (k *Key) UnmarshalText(b []byte) error { 38 | k.string = string(b) 39 | return nil 40 | } 41 | -------------------------------------------------------------------------------- /cryptoc/streamer.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/ecdh" 5 | "io" 6 | "net" 7 | 8 | "golang.org/x/crypto/chacha20poly1305" 9 | ) 10 | 11 | type Streamer func(io.ReadWriter) net.Conn 12 | 13 | func NewStreamer(selfSecret *ecdh.PrivateKey, peerPublic *ecdh.PublicKey, initiator bool) (Streamer, error) { 14 | lKey, rKey, err := DeriveKeys(selfSecret, peerPublic, initiator) 15 | if err != nil { 16 | return nil, err 17 | } 18 | 19 | lCipher, err := chacha20poly1305.New(lKey) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | rCipher, err := chacha20poly1305.New(rKey) 25 | if err != nil { 26 | return nil, err 27 | } 28 | 29 | return func(stream io.ReadWriter) net.Conn { 30 | if initiator { 31 | return NewStream(stream, rCipher, lCipher) 32 | } 33 | return NewStream(stream, lCipher, rCipher) 34 | }, nil 35 | } 36 | -------------------------------------------------------------------------------- /statusc/status.go: -------------------------------------------------------------------------------- 1 | package statusc 2 | 3 | import "fmt" 4 | 5 | type Status struct{ string } 6 | 7 | var ( 8 | NotConnected = Status{"not_connected"} 9 | Connected = Status{"connected"} 10 | Reconnecting = Status{"reconnecting"} 11 | Disconnected = Status{"disconnected"} 12 | ) 13 | 14 | func (s Status) String() string { 15 | return s.string 16 | } 17 | 18 | func (s Status) MarshalText() ([]byte, error) { 19 | return []byte(s.string), nil 20 | } 21 | 22 | func (s *Status) UnmarshalText(b []byte) error { 23 | switch str := string(b); str { 24 | case NotConnected.string: 25 | *s = NotConnected 26 | case Connected.string: 27 | *s = Connected 28 | case Reconnecting.string: 29 | *s = Reconnecting 30 | case Disconnected.string: 31 | *s = Disconnected 32 | default: 33 | return fmt.Errorf("invalid status '%s'", s) 34 | } 35 | return nil 36 | } 37 | -------------------------------------------------------------------------------- /reliable/time.go: -------------------------------------------------------------------------------- 1 | package reliable 2 | 3 | import ( 4 | "context" 5 | "math/rand/v2" 6 | "time" 7 | ) 8 | 9 | func Wait(ctx context.Context, d time.Duration) error { 10 | select { 11 | case <-time.After(d): 12 | return nil 13 | case <-ctx.Done(): 14 | return ctx.Err() 15 | } 16 | } 17 | 18 | func NextDeline(d time.Duration) time.Duration { 19 | idur := int64(d) / 4 20 | change := rand.Int64N(idur * 2) 21 | return time.Duration(3*idur + change) 22 | } 23 | 24 | func WaitDeline(ctx context.Context, d time.Duration) error { 25 | return Wait(ctx, NextDeline(d)) 26 | } 27 | 28 | func rerunDeline(ctx context.Context, d time.Duration, fn func(ctx context.Context) error) error { 29 | for { 30 | if err := fn(ctx); err != nil { 31 | return err 32 | } 33 | 34 | if err := Wait(ctx, NextDeline(d)); err != nil { 35 | return err 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /restr/name_test.go: -------------------------------------------------------------------------------- 1 | package restr 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | ) 8 | 9 | func TestName(t *testing.T) { 10 | tcs := []struct { 11 | name string 12 | exp string 13 | accept bool 14 | }{ 15 | { 16 | name: "exact", 17 | exp: `^exact$`, 18 | accept: true, 19 | }, 20 | { 21 | name: "exact-no", 22 | exp: `^exact$`, 23 | accept: false, 24 | }, 25 | { 26 | name: "oneof", 27 | exp: `oneof|twoof`, 28 | accept: true, 29 | }, 30 | { 31 | name: "three", 32 | exp: `oneof|twoof`, 33 | accept: false, 34 | }, 35 | } 36 | 37 | for _, tc := range tcs { 38 | t.Run(tc.name, func(t *testing.T) { 39 | restr, err := ParseName(tc.exp) 40 | require.NoError(t, err) 41 | require.Equal(t, tc.accept, restr.IsAllowed(tc.name)) 42 | }) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /nat/local.go: -------------------------------------------------------------------------------- 1 | package nat 2 | 3 | import ( 4 | "context" 5 | "log/slog" 6 | "net/netip" 7 | 8 | "github.com/connet-dev/connet/netc" 9 | ) 10 | 11 | type Local struct { 12 | localPort uint16 13 | logger *slog.Logger 14 | } 15 | 16 | func NewLocal(localPort uint16, logger *slog.Logger) *Local { 17 | return &Local{localPort, logger.With("component", "local")} 18 | } 19 | 20 | func (s *Local) Get() []netip.AddrPort { 21 | localAddrs, err := netc.LocalAddrs() 22 | if err == nil { 23 | localAddrPorts := make([]netip.AddrPort, len(localAddrs)) 24 | for i, addr := range localAddrs { 25 | localAddrPorts[i] = netip.AddrPortFrom(addr, s.localPort) 26 | } 27 | return localAddrPorts 28 | } else { 29 | s.logger.Warn("cannot get local addrs", "err", err) 30 | } 31 | 32 | return nil 33 | } 34 | 35 | func (s *Local) Listen(ctx context.Context, fn func([]netip.AddrPort) error) error { 36 | return nil 37 | } 38 | -------------------------------------------------------------------------------- /proto/pbconnect/proto.go: -------------------------------------------------------------------------------- 1 | package pbconnect 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/connet-dev/connet/proto" 8 | pberror "github.com/connet-dev/connet/proto/pberror" 9 | ) 10 | 11 | func ReadRequest(r io.Reader) (*Request, error) { 12 | req := &Request{} 13 | if err := proto.Read(r, req); err != nil { 14 | return nil, err 15 | } 16 | return req, nil 17 | } 18 | 19 | func ReadResponse(r io.Reader) (*Response, error) { 20 | resp := &Response{} 21 | if err := proto.Read(r, resp); err != nil { 22 | return nil, err 23 | } 24 | if resp.Error != nil { 25 | return nil, resp.Error 26 | } 27 | return resp, nil 28 | } 29 | 30 | func WriteError(w io.Writer, code pberror.Code, msg string, args ...any) error { 31 | err := pberror.NewError(code, msg, args...) 32 | if err := proto.Write(w, &Response{Error: err}); err != nil { 33 | return fmt.Errorf("write err response: %w", err) 34 | } 35 | return err 36 | } 37 | -------------------------------------------------------------------------------- /examples/minimal.toml: -------------------------------------------------------------------------------- 1 | log-level = "debug" 2 | 3 | [client] 4 | token-file = "examples/client-token.secret" 5 | server-cas-file = ".direnv/minica.pem" 6 | 7 | [client.destinations.sws] 8 | url = "file:." 9 | 10 | [client.sources.sws] 11 | url = "tcp://:9999" 12 | 13 | [server] 14 | tokens-file = "examples/client-token.secret" 15 | 16 | [[server.ingress]] 17 | cert-file = ".direnv/localhost/cert.pem" 18 | key-file = ".direnv/localhost/key.pem" 19 | 20 | [control] 21 | clients-tokens-file = "examples/client-token.secret" 22 | relays-tokens-file = "examples/relay-token.secret" 23 | 24 | [[control.clients-ingress]] 25 | cert-file = ".direnv/localhost/cert.pem" 26 | key-file = ".direnv/localhost/key.pem" 27 | 28 | [[control.relays-ingress]] 29 | cert-file = ".direnv/localhost/cert.pem" 30 | key-file = ".direnv/localhost/key.pem" 31 | 32 | [relay] 33 | token-file = "examples/relay-token.secret" 34 | control-cas-file = ".direnv/localhost/cert.pem" 35 | -------------------------------------------------------------------------------- /nix/docker.nix: -------------------------------------------------------------------------------- 1 | { pkgs }: 2 | let 3 | connet = pkgs.callPackage ./package.nix { }; 4 | in 5 | pkgs.dockerTools.buildLayeredImage { 6 | name = "ghcr.io/connet-dev/connet"; 7 | tag = "latest-${if pkgs.stdenv.hostPlatform.isAarch then "arm64" else "amd64"}"; 8 | contents = with pkgs; [ cacert ]; 9 | config = { 10 | Entrypoint = [ "${connet}/bin/connet" ]; 11 | Cmd = [ "--help" ]; 12 | ExposedPorts = { 13 | # working ports 14 | "19189/udp" = { }; # control listens for relays 15 | "19190/udp" = { }; # control listens for clients 16 | "19191/udp" = { }; # relay listens for clients 17 | "19192/udp" = { }; # client listens for clients 18 | }; 19 | Env = [ 20 | "CONNET_STATE_DIR=/data" # server to store data 21 | "CONNET_CACHE_DIR=/cache" # client to store caches 22 | ]; 23 | Volumes = { 24 | "/data" = { }; # server to store data 25 | "/cache" = { }; # client to store caches 26 | }; 27 | }; 28 | } 29 | -------------------------------------------------------------------------------- /proto/error.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package error; 3 | 4 | option go_package = "github.com/connet-dev/connet/proto/pberror"; 5 | 6 | enum Code { 7 | // Generic 8 | Unknown = 0; 9 | RequestUnknown = 1; 10 | ConnectionCheckFailed = 2; 11 | 12 | // Authentication 13 | AuthenticationFailed = 100; 14 | EndpointNotAllowed = 101; 15 | RoleNotAllowed = 102; 16 | 17 | // Announce 18 | AnnounceValidationFailed = 200; 19 | AnnounceInvalidClientCertificate = 201; 20 | AnnounceInvalidServerCertificate = 202; 21 | 22 | // Relay 23 | RelayValidationFailed = 300; 24 | RelayInvalidCertificate = 301; 25 | RelayKeepaliveClosed = 302; 26 | 27 | // Direct 28 | DirectConnectionClosed = 400; 29 | DirectKeepaliveClosed = 401; 30 | 31 | // Client connect codes 32 | DestinationNotFound = 500; 33 | DestinationDialFailed = 501; 34 | DestinationRelayEncryptionError = 502; 35 | } 36 | 37 | message Error { 38 | Code code = 1; 39 | string message = 2; 40 | } 41 | -------------------------------------------------------------------------------- /model/route.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "fmt" 4 | 5 | type RouteOption struct{ string } 6 | 7 | var ( 8 | RouteAny = RouteOption{"any"} 9 | RouteDirect = RouteOption{"direct"} 10 | RouteRelay = RouteOption{"relay"} 11 | ) 12 | 13 | func ParseRouteOption(s string) (RouteOption, error) { 14 | switch s { 15 | case RouteAny.string: 16 | return RouteAny, nil 17 | case RouteDirect.string: 18 | return RouteDirect, nil 19 | case RouteRelay.string: 20 | return RouteRelay, nil 21 | } 22 | return RouteOption{}, fmt.Errorf("invalid route option '%s'", s) 23 | } 24 | 25 | func (r RouteOption) AllowFrom(from RouteOption) bool { 26 | switch from { 27 | case RouteDirect: 28 | return r.AllowDirect() 29 | case RouteRelay: 30 | return r.AllowRelay() 31 | } 32 | return false 33 | } 34 | 35 | func (r RouteOption) AllowDirect() bool { 36 | return r == RouteAny || r == RouteDirect 37 | } 38 | 39 | func (r RouteOption) AllowRelay() bool { 40 | return r == RouteAny || r == RouteRelay 41 | } 42 | -------------------------------------------------------------------------------- /quicc/conf.go: -------------------------------------------------------------------------------- 1 | package quicc 2 | 3 | import ( 4 | "net" 5 | "time" 6 | 7 | "github.com/quic-go/quic-go" 8 | ) 9 | 10 | func ClientTransport(conn net.PacketConn, statelessResetKey *quic.StatelessResetKey) *quic.Transport { 11 | return &quic.Transport{ 12 | Conn: conn, 13 | StatelessResetKey: statelessResetKey, 14 | DisableVersionNegotiationPackets: true, 15 | // TODO review other options 16 | } 17 | } 18 | 19 | func ServerTransport(conn net.PacketConn, statelessResetKey *quic.StatelessResetKey) *quic.Transport { 20 | return &quic.Transport{ 21 | Conn: conn, 22 | ConnectionIDLength: 8, 23 | StatelessResetKey: statelessResetKey, 24 | DisableVersionNegotiationPackets: true, 25 | // TODO review other options 26 | } 27 | } 28 | 29 | var StdConfig = &quic.Config{ 30 | MaxIdleTimeout: 20 * time.Second, 31 | KeepAlivePeriod: 10 * time.Second, 32 | Versions: []quic.Version{quic.Version1}, 33 | // TODO review other options 34 | } 35 | -------------------------------------------------------------------------------- /process-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "0.5" 2 | 3 | processes: 4 | build: 5 | command: make build 6 | availability: 7 | restart: "exit_on_failure" 8 | certs: 9 | command: gen-local-certs 10 | server: 11 | command: connet server --config examples/minimal.toml 12 | depends_on: 13 | build: 14 | condition: process_completed_successfully 15 | certs: 16 | condition: process_completed 17 | client-dst: 18 | command: connet --config examples/client-destination.toml 19 | depends_on: 20 | build: 21 | condition: process_completed_successfully 22 | certs: 23 | condition: process_completed 24 | server: 25 | condition: process_started 26 | client-src: 27 | command: connet --config examples/client-source.toml 28 | depends_on: 29 | build: 30 | condition: process_completed_successfully 31 | certs: 32 | condition: process_completed 33 | server: 34 | condition: process_started 35 | client-dst: 36 | condition: process_started 37 | -------------------------------------------------------------------------------- /model/endpoint.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "github.com/connet-dev/connet/proto/pbmodel" 5 | ) 6 | 7 | type Endpoint struct{ string } 8 | 9 | func NewEndpoint(s string) Endpoint { 10 | return Endpoint{s} 11 | } 12 | 13 | func EndpointFromPB(f *pbmodel.Endpoint) Endpoint { 14 | return Endpoint{f.Name} 15 | } 16 | 17 | func (f Endpoint) PB() *pbmodel.Endpoint { 18 | return &pbmodel.Endpoint{Name: f.string} 19 | } 20 | 21 | func (f Endpoint) String() string { 22 | return f.string 23 | } 24 | 25 | func PBFromEndpoints(eps []Endpoint) []*pbmodel.Endpoint { 26 | pbs := make([]*pbmodel.Endpoint, len(eps)) 27 | for i, ep := range eps { 28 | pbs[i] = ep.PB() 29 | } 30 | return pbs 31 | } 32 | 33 | func (f Endpoint) MarshalText() ([]byte, error) { 34 | return []byte(f.string), nil 35 | } 36 | 37 | func (f *Endpoint) UnmarshalText(b []byte) error { 38 | *f = Endpoint{string(b)} 39 | return nil 40 | } 41 | 42 | func EndpointNames(eps []Endpoint) []string { 43 | var strs = make([]string, len(eps)) 44 | for i, ep := range eps { 45 | strs[i] = ep.string 46 | } 47 | return strs 48 | } 49 | -------------------------------------------------------------------------------- /statusc/server.go: -------------------------------------------------------------------------------- 1 | package statusc 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "net" 8 | "net/http" 9 | 10 | "github.com/connet-dev/connet/slogc" 11 | ) 12 | 13 | func Run[T any](ctx context.Context, addr *net.TCPAddr, f func(ctx context.Context) (T, error)) error { 14 | srv := &http.Server{ 15 | Addr: addr.String(), 16 | Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 17 | stat, err := f(r.Context()) 18 | if err == nil { 19 | w.Header().Add("Content-Type", "application/json") 20 | enc := json.NewEncoder(w) 21 | err = enc.Encode(stat) 22 | } 23 | if err != nil { 24 | w.WriteHeader(http.StatusInternalServerError) 25 | if _, err := fmt.Fprintf(w, "server error: %v", err.Error()); err != nil { 26 | slogc.FineDefault("error writing server error", "err", err) 27 | } 28 | } 29 | }), 30 | } 31 | 32 | go func() { 33 | <-ctx.Done() 34 | if err := srv.Close(); err != nil { 35 | slogc.FineDefault("error closing status server", "err", err) 36 | } 37 | }() 38 | 39 | return srv.ListenAndServe() 40 | } 41 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/connet-dev/connet 2 | 3 | go 1.24.4 4 | 5 | require ( 6 | github.com/gorilla/websocket v1.5.3 7 | github.com/jackpal/gateway v1.1.1 8 | github.com/klev-dev/klevdb v0.10.1 9 | github.com/pelletier/go-toml/v2 v2.2.4 10 | github.com/pires/go-proxyproto v0.8.1 11 | github.com/quic-go/quic-go v0.57.1 12 | github.com/spf13/cobra v1.10.2 13 | github.com/stretchr/testify v1.11.1 14 | golang.org/x/crypto v0.45.0 15 | golang.org/x/sync v0.18.0 16 | google.golang.org/protobuf v1.36.10 17 | ) 18 | 19 | require ( 20 | github.com/davecgh/go-spew v1.1.1 // indirect 21 | github.com/gofrs/flock v0.13.0 // indirect 22 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 23 | github.com/plar/go-adaptive-radix-tree/v2 v2.0.4 // indirect 24 | github.com/pmezard/go-difflib v1.0.0 // indirect 25 | github.com/spf13/pflag v1.0.10 // indirect 26 | github.com/stretchr/objx v0.5.3 // indirect 27 | go.uber.org/mock v0.6.0 // indirect 28 | golang.org/x/exp v0.0.0-20251125195548-87e1e737ad39 // indirect 29 | golang.org/x/net v0.47.0 // indirect 30 | golang.org/x/sys v0.38.0 // indirect 31 | gopkg.in/yaml.v3 v3.0.1 // indirect 32 | ) 33 | -------------------------------------------------------------------------------- /proto/connect.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package connect; 3 | 4 | import "error.proto"; 5 | 6 | option go_package = "github.com/connet-dev/connet/proto/pbconnect"; 7 | 8 | message Request { 9 | // Soft one-of 10 | Connect connect = 1; 11 | 12 | message Connect { 13 | repeated RelayEncryptionScheme source_encryption = 1; 14 | TLSConfiguration source_tls = 2; 15 | ECDHConfiguration source_dh_x25519 = 3; 16 | } 17 | } 18 | 19 | message Response { 20 | error.Error error = 1; 21 | 22 | Connect connect = 2; 23 | 24 | message Connect { 25 | ProxyProtoVersion proxy_proto = 1; 26 | RelayEncryptionScheme destination_encryption = 2; 27 | TLSConfiguration destination_tls = 3; 28 | ECDHConfiguration destination_dh_x25519 = 4; 29 | } 30 | } 31 | 32 | enum ProxyProtoVersion { 33 | ProxyProtoNone = 0; 34 | V1 = 1; 35 | V2 = 2; 36 | } 37 | 38 | enum RelayEncryptionScheme { 39 | EncryptionNone = 0; 40 | TLS = 1; 41 | DHX25519_CHACHAPOLY = 2; 42 | } 43 | 44 | message TLSConfiguration { 45 | string client_name = 1; 46 | } 47 | 48 | message ECDHConfiguration { 49 | string client_name = 1; 50 | bytes key_time = 2; 51 | bytes signature = 3; 52 | } 53 | -------------------------------------------------------------------------------- /cryptoc/derive.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/ecdh" 5 | "hash" 6 | 7 | "golang.org/x/crypto/blake2s" 8 | ) 9 | 10 | func DeriveKeys(selfSecret *ecdh.PrivateKey, peerPublic *ecdh.PublicKey, initiator bool) ([]byte, []byte, error) { 11 | ck, hk := initck() 12 | 13 | if initiator { 14 | hk = mixHash(hk, selfSecret.PublicKey().Bytes()) 15 | hk = mixHash(hk, peerPublic.Bytes()) 16 | } else { 17 | hk = mixHash(hk, peerPublic.Bytes()) 18 | hk = mixHash(hk, selfSecret.PublicKey().Bytes()) 19 | } 20 | 21 | dh, err := selfSecret.ECDH(peerPublic) 22 | if err != nil { 23 | return nil, nil, err 24 | } 25 | ck = hkdf1(newhash, ck, dh) 26 | 27 | hk1, hk2 := hkdf2(newhash, ck, hk) 28 | return hk1, hk2, nil 29 | } 30 | 31 | func initck() ([]byte, []byte) { 32 | ck := make([]byte, blake2s.Size) 33 | copy(ck, "connet-chaining") 34 | 35 | hk := make([]byte, blake2s.Size) 36 | copy(hk, "connet-hashing") 37 | 38 | return ck, hk 39 | } 40 | 41 | func newhash() hash.Hash { 42 | h, err := blake2s.New256([]byte("connet-hash")) 43 | if err != nil { 44 | panic(err) 45 | } 46 | return h 47 | } 48 | 49 | func mixHash(oldHash, data []byte) []byte { 50 | h := newhash() 51 | h.Write(oldHash) 52 | h.Write(data) 53 | return h.Sum(nil) 54 | } 55 | -------------------------------------------------------------------------------- /selfhosted/relays.go: -------------------------------------------------------------------------------- 1 | package selfhosted 2 | 3 | import ( 4 | "github.com/connet-dev/connet/control" 5 | "github.com/connet-dev/connet/model" 6 | "github.com/connet-dev/connet/proto/pberror" 7 | "github.com/connet-dev/connet/restr" 8 | ) 9 | 10 | type RelayAuthentication struct { 11 | Token string 12 | IPs restr.IP 13 | } 14 | 15 | func NewRelayAuthenticator(auths ...RelayAuthentication) control.RelayAuthenticator { 16 | s := &relayAuthenticator{map[string]*RelayAuthentication{}} 17 | for _, auth := range auths { 18 | s.tokens[auth.Token] = &auth 19 | } 20 | return s 21 | } 22 | 23 | type relayAuthenticator struct { 24 | tokens map[string]*RelayAuthentication 25 | } 26 | 27 | func (s *relayAuthenticator) Authenticate(req control.RelayAuthenticateRequest) (control.RelayAuthentication, error) { 28 | r, ok := s.tokens[req.Token] 29 | if !ok { 30 | return nil, pberror.NewError(pberror.Code_AuthenticationFailed, "token not found") 31 | } 32 | if !r.IPs.IsAllowedAddr(req.Addr) { 33 | return nil, pberror.NewError(pberror.Code_AuthenticationFailed, "address not allowed: %s", req.Addr) 34 | } 35 | return []byte(r.Token), nil 36 | } 37 | 38 | func (s *relayAuthenticator) Allow(_ control.RelayAuthentication, _ control.ClientAuthentication, _ model.Endpoint) (bool, error) { 39 | return true, nil 40 | } 41 | -------------------------------------------------------------------------------- /proto/relay.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package relay; 3 | 4 | import "error.proto"; 5 | import "model.proto"; 6 | 7 | option go_package = "github.com/connet-dev/connet/proto/pbrelay"; 8 | 9 | message AuthenticateReq { 10 | string token = 1; 11 | repeated model.HostPort addresses = 5; 12 | bytes reconnect_token = 3; 13 | string build_version = 4; 14 | } 15 | 16 | message AuthenticateResp { 17 | error.Error error = 1; 18 | string control_id = 2; 19 | bytes reconnect_token = 3; 20 | } 21 | 22 | enum ChangeType { 23 | ChangeUnknown = 0; 24 | ChangePut = 1; 25 | ChangeDel = 2; 26 | } 27 | 28 | message ClientsReq { 29 | int64 offset = 1; 30 | } 31 | 32 | message ClientsResp { 33 | repeated Change changes = 1; 34 | int64 offset = 2; 35 | bool restart = 3; 36 | 37 | message Change { 38 | ChangeType change = 1; 39 | model.Endpoint endpoint = 2; 40 | model.Role role = 3; 41 | string certificate_key = 4; 42 | bytes certificate = 5; 43 | } 44 | } 45 | 46 | message ServersReq { 47 | int64 offset = 1; 48 | } 49 | 50 | message ServersResp { 51 | repeated Change changes = 1; 52 | int64 offset = 2; 53 | bool restart = 3; 54 | 55 | message Change { 56 | ChangeType change = 1; 57 | model.Endpoint endpoint = 2; 58 | bytes server_certificate = 3; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /websocketc/join.go: -------------------------------------------------------------------------------- 1 | package websocketc 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | 7 | "github.com/connet-dev/connet/slogc" 8 | "github.com/gorilla/websocket" 9 | "golang.org/x/sync/errgroup" 10 | ) 11 | 12 | func Join(nc net.Conn, wc *websocket.Conn) error { 13 | var g errgroup.Group 14 | 15 | g.Go(func() error { 16 | defer func() { 17 | if err := nc.Close(); err != nil { 18 | slogc.FineDefault("error closing source connection", "err", err) 19 | } 20 | }() 21 | for { 22 | _, data, err := wc.ReadMessage() 23 | if err != nil { 24 | return fmt.Errorf("websocked connection read: %w", err) 25 | } 26 | if _, err := nc.Write(data); err != nil { 27 | return fmt.Errorf("source connection write: %w", err) 28 | } 29 | } 30 | }) 31 | 32 | g.Go(func() error { 33 | defer func() { 34 | if err := wc.Close(); err != nil { 35 | slogc.FineDefault("error closing websocket connection", "err", err) 36 | } 37 | }() 38 | var buf = make([]byte, 4096) 39 | for { 40 | n, err := nc.Read(buf) 41 | if err != nil { 42 | return fmt.Errorf("source connection read: %w", err) 43 | } 44 | if err := wc.WriteMessage(websocket.BinaryMessage, buf[0:n]); err != nil { 45 | return fmt.Errorf("websocked connection write: %w", err) 46 | } 47 | } 48 | }) 49 | 50 | return g.Wait() 51 | } 52 | -------------------------------------------------------------------------------- /reliable/backoff.go: -------------------------------------------------------------------------------- 1 | package reliable 2 | 3 | import ( 4 | "context" 5 | "math/rand/v2" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | const ( 11 | MinBackoff time.Duration = 10 * time.Millisecond 12 | MaxBackoff time.Duration = 15 * time.Second 13 | ) 14 | 15 | func NextBackoff(d time.Duration) time.Duration { 16 | return NextBackoffCustom(d, MinBackoff, MaxBackoff) 17 | } 18 | 19 | func NextBackoffCustom(d, jmin, jmax time.Duration) time.Duration { 20 | dt := int64(d*3 - jmin) 21 | nd := jmin + time.Duration(rand.Int64N(dt)) 22 | return min(jmax, nd) 23 | } 24 | 25 | type SpinBackoff struct { 26 | MinBackoff time.Duration 27 | MaxBackoff time.Duration 28 | 29 | init sync.Once 30 | lastWait time.Time 31 | lastBoff time.Duration 32 | } 33 | 34 | // Wait will block on backoff if called too often 35 | func (s *SpinBackoff) Wait(ctx context.Context) error { 36 | s.init.Do(func() { 37 | if s.MinBackoff == 0 { 38 | s.MinBackoff = MinBackoff 39 | } 40 | if s.MaxBackoff == 0 { 41 | s.MaxBackoff = MaxBackoff 42 | } 43 | s.MaxBackoff = max(s.MinBackoff, s.MaxBackoff) 44 | }) 45 | 46 | delta := time.Since(s.lastWait) 47 | s.lastWait = time.Now() 48 | 49 | if delta > s.MaxBackoff { 50 | s.lastBoff = s.MinBackoff 51 | return nil 52 | } 53 | 54 | s.lastBoff = NextBackoffCustom(s.lastBoff, s.MinBackoff, s.MaxBackoff) 55 | return Wait(ctx, s.lastBoff) 56 | } 57 | -------------------------------------------------------------------------------- /proto/pbmodel/addr.go: -------------------------------------------------------------------------------- 1 | package pbmodel 2 | 3 | import ( 4 | "net" 5 | "net/netip" 6 | 7 | "github.com/connet-dev/connet/netc" 8 | ) 9 | 10 | func AddrFromNetip(addr netip.Addr) *Addr { 11 | if addr.Is6() { 12 | v6 := addr.As16() 13 | return &Addr{V6: v6[:]} 14 | } 15 | v4 := addr.As4() 16 | return &Addr{V4: v4[:]} 17 | } 18 | 19 | func (a *Addr) AsNetip() netip.Addr { 20 | if len(a.V6) > 0 { 21 | return netip.AddrFrom16([16]byte(a.V6)) 22 | } 23 | return netip.AddrFrom4([4]byte(a.V4)) 24 | } 25 | 26 | func AddrPortFromNet(addr net.Addr) (*AddrPort, error) { 27 | a, err := netc.AddrPortFromNet(addr) 28 | if err != nil { 29 | return nil, err 30 | } 31 | return AddrPortFromNetip(a), nil 32 | } 33 | 34 | func AddrPortFromNetip(addr netip.AddrPort) *AddrPort { 35 | return &AddrPort{ 36 | Addr: AddrFromNetip(addr.Addr()), 37 | Port: uint32(addr.Port()), 38 | } 39 | } 40 | 41 | func (a *AddrPort) AsNetip() netip.AddrPort { 42 | return netip.AddrPortFrom(a.Addr.AsNetip(), uint16(a.Port)) 43 | } 44 | 45 | func AsNetips(pb []*AddrPort) []netip.AddrPort { 46 | s := make([]netip.AddrPort, len(pb)) 47 | for i, pbi := range pb { 48 | s[i] = pbi.AsNetip() 49 | } 50 | return s 51 | } 52 | 53 | func AsAddrPorts(addrs []netip.AddrPort) []*AddrPort { 54 | s := make([]*AddrPort, len(addrs)) 55 | for i, addr := range addrs { 56 | s[i] = AddrPortFromNetip(addr) 57 | } 58 | return s 59 | } 60 | -------------------------------------------------------------------------------- /reliable/group_test.go: -------------------------------------------------------------------------------- 1 | package reliable 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | var errTest = errors.New("the error") 13 | 14 | func testNoError(ctx context.Context) error { 15 | return nil 16 | } 17 | 18 | func testError(ctx context.Context) error { 19 | return errTest 20 | } 21 | 22 | func testWaitError(ctx context.Context) error { 23 | if err := Wait(ctx, 2*time.Nanosecond); err != nil { 24 | return err 25 | } 26 | return errTest 27 | } 28 | 29 | func testWait(ctx context.Context) error { 30 | return Wait(ctx, 2*time.Nanosecond) 31 | } 32 | 33 | func testLongWait(ctx context.Context) error { 34 | return Wait(ctx, 11*time.Second) 35 | } 36 | 37 | func TestGroup(t *testing.T) { 38 | err := RunGroup(context.Background(), testNoError) 39 | require.NoError(t, err) 40 | 41 | err = RunGroup(context.Background(), testError) 42 | require.ErrorIs(t, errTest, err) 43 | 44 | err = RunGroup(context.Background(), testError, testNoError) 45 | require.ErrorIs(t, errTest, err) 46 | 47 | err = RunGroup(context.Background(), testWait, testWait) 48 | require.NoError(t, err) 49 | 50 | err = RunGroup(context.Background(), testWait, testWaitError) 51 | require.ErrorIs(t, errTest, err) 52 | 53 | err = RunGroup(context.Background(), testWaitError, testLongWait) 54 | require.ErrorIs(t, errTest, err) 55 | } 56 | -------------------------------------------------------------------------------- /nix/package.nix: -------------------------------------------------------------------------------- 1 | { pkgs, lib, ... }: 2 | let 3 | sourceFiles = lib.fileset.difference ../. (lib.fileset.unions [ 4 | (lib.fileset.maybeMissing ../result) 5 | ../.envrc 6 | ../.gitignore 7 | ../examples 8 | ../flake.lock 9 | ../flake.nix 10 | ../LICENSE 11 | ../Makefile 12 | ../nix 13 | ../process-compose.yaml 14 | ../README.md 15 | ]); 16 | in 17 | # lib.fileset.trace sourceFiles 18 | pkgs.buildGoModule 19 | { 20 | name = "connet"; 21 | 22 | src = lib.fileset.toSource { 23 | root = ../.; 24 | fileset = sourceFiles; 25 | }; 26 | 27 | vendorHash = "sha256-nw68Mv9KkqsPVVHUdDOi97QMlPk+4vvaePP/AgBmgNI="; 28 | subPackages = [ "cmd/connet" ]; 29 | ldflags = [ "-X 'github.com/connet-dev/connet/model.Version=${lib.strings.fileContents ../VERSION}'" ]; 30 | 31 | nativeBuildInputs = [ pkgs.installShellFiles ]; 32 | postInstall = lib.optionalString (pkgs.stdenv.buildPlatform.canExecute pkgs.stdenv.hostPlatform) '' 33 | installShellCompletion --cmd connet \ 34 | --bash <($out/bin/connet completion bash) \ 35 | --fish <($out/bin/connet completion fish) \ 36 | --zsh <($out/bin/connet completion zsh) 37 | ''; 38 | 39 | meta = with lib; { 40 | description = "A p2p reverse proxy, written in Golang"; 41 | homepage = "https://github.com/connet-dev/connet"; 42 | license = licenses.asl20; 43 | mainProgram = "connet"; 44 | }; 45 | } 46 | -------------------------------------------------------------------------------- /reliable/group.go: -------------------------------------------------------------------------------- 1 | package reliable 2 | 3 | import ( 4 | "context" 5 | "time" 6 | 7 | "golang.org/x/sync/errgroup" 8 | ) 9 | 10 | type RunFn func(context.Context) error 11 | 12 | func Bind[T any](t T, fn func(context.Context, T) error) RunFn { 13 | return func(ctx context.Context) error { 14 | return fn(ctx, t) 15 | } 16 | } 17 | 18 | func Schedule(d time.Duration, fn RunFn) RunFn { 19 | return ScheduleDelayed(d, d, fn) 20 | } 21 | 22 | func ScheduleNow(d time.Duration, fn RunFn) RunFn { 23 | return func(ctx context.Context) error { 24 | return rerunDeline(ctx, d, fn) 25 | } 26 | } 27 | 28 | func ScheduleDelayed(delay, d time.Duration, fn RunFn) RunFn { 29 | return func(ctx context.Context) error { 30 | if err := Wait(ctx, NextDeline(delay)); err != nil { 31 | return err 32 | } 33 | 34 | return rerunDeline(ctx, d, fn) 35 | } 36 | } 37 | 38 | type Group struct { 39 | group *errgroup.Group 40 | ctx context.Context 41 | } 42 | 43 | func NewGroup(ctx context.Context) *Group { 44 | group, ctx := errgroup.WithContext(ctx) 45 | return &Group{ 46 | group: group, 47 | ctx: ctx, 48 | } 49 | } 50 | 51 | func RunGroup(ctx context.Context, fns ...RunFn) error { 52 | return NewGroup(ctx).Go(fns...).Wait() 53 | } 54 | 55 | func (g *Group) Go(fns ...RunFn) *Group { 56 | for _, fn := range fns { 57 | g.group.Go(func() error { 58 | return fn(g.ctx) 59 | }) 60 | } 61 | return g 62 | } 63 | 64 | func (g *Group) Wait() error { 65 | return g.group.Wait() 66 | } 67 | -------------------------------------------------------------------------------- /cryptoc/hkdf.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/hmac" 5 | "hash" 6 | ) 7 | 8 | type hasher func() hash.Hash 9 | 10 | func hkdf1(h hasher, chainingKey, inputKey []byte) []byte { 11 | tempMac := hmac.New(h, chainingKey) 12 | tempMac.Write(inputKey) 13 | tempKey := tempMac.Sum(nil) 14 | 15 | out1Mac := hmac.New(h, tempKey) 16 | out1Mac.Write([]byte{0x01}) 17 | return out1Mac.Sum(nil) 18 | } 19 | 20 | func hkdf2(h hasher, chainingKey, inputKey []byte) ([]byte, []byte) { 21 | tempMac := hmac.New(h, chainingKey) 22 | tempMac.Write(inputKey) 23 | tempKey := tempMac.Sum(nil) 24 | 25 | out1Mac := hmac.New(h, tempKey) 26 | out1Mac.Write([]byte{0x01}) 27 | out1 := out1Mac.Sum(nil) 28 | 29 | out2Mac := hmac.New(h, tempKey) 30 | out2Mac.Write(out1) 31 | out2Mac.Write([]byte{0x02}) 32 | out2 := out2Mac.Sum(nil) 33 | 34 | return out1, out2 35 | } 36 | 37 | func hkdf3(h hasher, chainingKey, inputKey []byte) ([]byte, []byte, []byte) { 38 | tempMac := hmac.New(h, chainingKey) 39 | tempMac.Write(inputKey) 40 | tempKey := tempMac.Sum(nil) 41 | 42 | out1Mac := hmac.New(h, tempKey) 43 | out1Mac.Write([]byte{0x01}) 44 | out1 := out1Mac.Sum(nil) 45 | 46 | out2Mac := hmac.New(h, tempKey) 47 | out2Mac.Write(out1) 48 | out2Mac.Write([]byte{0x02}) 49 | out2 := out2Mac.Sum(nil) 50 | 51 | out3Mac := hmac.New(h, tempKey) 52 | out3Mac.Write(out2) 53 | out3Mac.Write([]byte{0x03}) 54 | out3 := out3Mac.Sum(nil) 55 | 56 | return out1, out2, out3 57 | } 58 | 59 | var _ = hkdf3 60 | -------------------------------------------------------------------------------- /model/loadbalance.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "fmt" 4 | 5 | type LoadBalancePolicy struct{ string } 6 | 7 | var ( 8 | NoPolicy = LoadBalancePolicy{} 9 | LeastLatencyPolicy = LoadBalancePolicy{"least-latency"} 10 | LeastConnsPolicy = LoadBalancePolicy{"least-conns"} 11 | RoundRobinPolicy = LoadBalancePolicy{"round-robin"} 12 | RandomPolicy = LoadBalancePolicy{"random"} 13 | ) 14 | 15 | func ParseLBPolicy(s string) (LoadBalancePolicy, error) { 16 | switch s { 17 | case NoPolicy.string: 18 | return NoPolicy, nil 19 | case LeastLatencyPolicy.string: 20 | return LeastLatencyPolicy, nil 21 | case LeastConnsPolicy.string: 22 | return LeastConnsPolicy, nil 23 | case RoundRobinPolicy.string: 24 | return RoundRobinPolicy, nil 25 | case RandomPolicy.string: 26 | return RandomPolicy, nil 27 | } 28 | return NoPolicy, fmt.Errorf("invalid load balance policy '%s'", s) 29 | } 30 | 31 | type LoadBalanceRetry struct{ string } 32 | 33 | var ( 34 | NeverRetry = LoadBalanceRetry{} 35 | CountRetry = LoadBalanceRetry{"count"} 36 | TimedRetry = LoadBalanceRetry{"timed"} 37 | AllRetry = LoadBalanceRetry{"all"} 38 | ) 39 | 40 | func ParseLBRetry(s string) (LoadBalanceRetry, error) { 41 | switch s { 42 | case NeverRetry.string: 43 | return NeverRetry, nil 44 | case CountRetry.string: 45 | return CountRetry, nil 46 | case TimedRetry.string: 47 | return TimedRetry, nil 48 | case AllRetry.string: 49 | return AllRetry, nil 50 | } 51 | return NeverRetry, fmt.Errorf("invalid load balance retry '%s'", s) 52 | } 53 | -------------------------------------------------------------------------------- /nat/resolver.go: -------------------------------------------------------------------------------- 1 | package nat 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "net" 8 | 9 | "github.com/connet-dev/connet/netc" 10 | "github.com/jackpal/gateway" 11 | ) 12 | 13 | var errDiscoverInterface = errors.New("pmp discover interface") 14 | 15 | func LocalIPSystemResolver() LocalIPResolver { 16 | return func(ctx context.Context) (net.IP, error) { 17 | localIP, err := gateway.DiscoverInterface() 18 | if err != nil { 19 | return net.IPv4zero, fmt.Errorf("%w: %w", errDiscoverInterface, err) 20 | } 21 | return localIP, nil 22 | } 23 | } 24 | 25 | func LocalIPDialResolver(addr string) LocalIPResolver { 26 | return func(ctx context.Context) (net.IP, error) { 27 | conn, err := net.Dial("udp", addr) 28 | if err != nil { 29 | return net.IPv4zero, err 30 | } 31 | addr, err := netc.IPFromNet(conn.LocalAddr()) 32 | if err != nil { 33 | return net.IPv4zero, err 34 | } 35 | return addr, nil 36 | } 37 | } 38 | 39 | var errDiscoverGateway = errors.New("pmp discover gateway") 40 | 41 | func GatewayIPSystemResolver() GatewayIPResolver { 42 | return func(ctx context.Context, localIP net.IP) (net.IP, error) { 43 | gatewayIP, err := gateway.DiscoverGateway() 44 | if err != nil { 45 | return net.IPv4zero, fmt.Errorf("%w: %w", errDiscoverGateway, err) 46 | } 47 | return gatewayIP, nil 48 | } 49 | } 50 | 51 | func GatewayIPNet24Resolver() GatewayIPResolver { 52 | return func(ctx context.Context, localIP net.IP) (net.IP, error) { 53 | s := []byte(localIP) 54 | return net.IPv4(s[0], s[1], s[2], 1), nil 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /slogc/log.go: -------------------------------------------------------------------------------- 1 | package slogc 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log/slog" 7 | "os" 8 | ) 9 | 10 | const LevelFine = slog.LevelDebug - 4 11 | 12 | func New(level string, format string) (*slog.Logger, error) { 13 | var logLevel slog.Level 14 | switch level { 15 | case "fine": 16 | logLevel = LevelFine 17 | case "debug": 18 | logLevel = slog.LevelDebug 19 | case "warn": 20 | logLevel = slog.LevelWarn 21 | case "error": 22 | logLevel = slog.LevelError 23 | case "info", "": 24 | logLevel = slog.LevelInfo 25 | default: 26 | return nil, fmt.Errorf("invalid level '%s' (fine|debug|info|warn|error)", level) 27 | } 28 | 29 | switch format { 30 | case "json": 31 | return slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ 32 | Level: logLevel, 33 | ReplaceAttr: levelReplacer, 34 | })), nil 35 | case "text", "": 36 | return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ 37 | Level: logLevel, 38 | ReplaceAttr: levelReplacer, 39 | })), nil 40 | default: 41 | return nil, fmt.Errorf("invalid format '%s' (json|text)", format) 42 | } 43 | } 44 | 45 | func levelReplacer(_ []string, attr slog.Attr) slog.Attr { 46 | if attr.Key == slog.LevelKey && attr.Value.Any() == LevelFine { 47 | return slog.String(attr.Key, "FINE") 48 | } 49 | return attr 50 | } 51 | 52 | func Fine(logger *slog.Logger, msg string, args ...any) { 53 | logger.Log(context.Background(), LevelFine, msg, args...) 54 | } 55 | 56 | func FineDefault(msg string, args ...any) { 57 | slog.Log(context.Background(), LevelFine, msg, args...) 58 | } 59 | -------------------------------------------------------------------------------- /netc/join.go: -------------------------------------------------------------------------------- 1 | package netc 2 | 3 | import ( 4 | "context" 5 | "io" 6 | "net" 7 | 8 | "github.com/connet-dev/connet/slogc" 9 | "golang.org/x/sync/errgroup" 10 | ) 11 | 12 | func Join(l io.ReadWriteCloser, r io.ReadWriteCloser) error { 13 | var g errgroup.Group 14 | g.Go(func() error { 15 | defer func() { 16 | if err := l.Close(); err != nil { 17 | slogc.FineDefault("error closing lconn", "err", err) 18 | } 19 | }() 20 | _, err := io.Copy(l, r) 21 | return err 22 | }) 23 | g.Go(func() error { 24 | defer func() { 25 | if err := r.Close(); err != nil { 26 | slogc.FineDefault("error closing rconn", "err", err) 27 | } 28 | }() 29 | _, err := io.Copy(r, l) 30 | return err 31 | }) 32 | return g.Wait() 33 | } 34 | 35 | type Joiner struct { 36 | Accept func(context.Context) (net.Conn, error) 37 | Dial func(context.Context) (net.Conn, error) 38 | Join func(ctx context.Context, acceptConn net.Conn, dialConn net.Conn) 39 | } 40 | 41 | func (j *Joiner) Run(ctx context.Context) error { 42 | for { 43 | acceptConn, err := j.Accept(ctx) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | go func() { 49 | defer func() { 50 | if err := acceptConn.Close(); err != nil { 51 | slogc.FineDefault("error closing accepted conn", "err", err) 52 | } 53 | }() 54 | 55 | dialConn, err := j.Dial(ctx) 56 | if err != nil { 57 | return 58 | } 59 | defer func() { 60 | if err := dialConn.Close(); err != nil { 61 | slogc.FineDefault("error closing dial conn", "err", err) 62 | } 63 | }() 64 | 65 | j.Join(ctx, acceptConn, dialConn) 66 | }() 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /model/role.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/connet-dev/connet/proto/pbmodel" 7 | ) 8 | 9 | type Role struct{ string } 10 | 11 | var ( 12 | UnknownRole = Role{} 13 | Destination = Role{"destination"} 14 | Source = Role{"source"} 15 | ) 16 | 17 | func RoleFromPB(r pbmodel.Role) Role { 18 | switch r { 19 | case pbmodel.Role_RoleDestination: 20 | return Destination 21 | case pbmodel.Role_RoleSource: 22 | return Source 23 | default: 24 | return UnknownRole 25 | } 26 | } 27 | 28 | func ParseRole(s string) (Role, error) { 29 | switch s { 30 | case Destination.string: 31 | return Destination, nil 32 | case Source.string: 33 | return Source, nil 34 | } 35 | return UnknownRole, fmt.Errorf("invalid role '%s'", s) 36 | } 37 | 38 | func (r Role) PB() pbmodel.Role { 39 | switch r { 40 | case Destination: 41 | return pbmodel.Role_RoleDestination 42 | case Source: 43 | return pbmodel.Role_RoleSource 44 | default: 45 | return pbmodel.Role_RoleUnknown 46 | } 47 | } 48 | 49 | func (r Role) Invert() Role { 50 | switch r { 51 | case Destination: 52 | return Source 53 | case Source: 54 | return Destination 55 | default: 56 | return UnknownRole 57 | } 58 | } 59 | 60 | func (r Role) String() string { 61 | return r.string 62 | } 63 | 64 | func (r Role) MarshalText() ([]byte, error) { 65 | return []byte(r.string), nil 66 | } 67 | 68 | func (r *Role) UnmarshalText(b []byte) error { 69 | switch s := string(b); s { 70 | case Destination.string: 71 | *r = Destination 72 | case Source.string: 73 | *r = Source 74 | default: 75 | return fmt.Errorf("invalid role '%s'", s) 76 | } 77 | return nil 78 | } 79 | -------------------------------------------------------------------------------- /proto/client.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package client; 3 | 4 | import "error.proto"; 5 | import "model.proto"; 6 | 7 | option go_package = "github.com/connet-dev/connet/proto/pbclient"; 8 | 9 | message Authenticate { 10 | string token = 1; 11 | bytes reconnect_token = 2; 12 | string build_version = 3; 13 | } 14 | 15 | message AuthenticateResp { 16 | error.Error error = 1; 17 | 18 | model.AddrPort public = 2; 19 | bytes reconnect_token = 3; 20 | } 21 | 22 | message Request { 23 | // Soft one-of 24 | Announce announce = 1; 25 | Relay relay = 2; 26 | 27 | message Announce { 28 | model.Endpoint endpoint = 1; 29 | model.Role role = 2; 30 | Peer peer = 3; 31 | } 32 | message Relay { 33 | model.Endpoint endpoint = 1; 34 | model.Role role = 2; 35 | bytes client_certificate = 3; // certificate to use when connecting to a relay 36 | } 37 | } 38 | 39 | message Response { 40 | error.Error error = 1; 41 | 42 | // Soft one-of if error is nil 43 | Announce announce = 2; 44 | Relays relay = 3; 45 | 46 | message Announce { 47 | repeated RemotePeer peers = 1; 48 | } 49 | message Relays { 50 | repeated Relay relays = 1; 51 | } 52 | } 53 | 54 | message Peer { 55 | repeated model.AddrPort directs = 3; 56 | repeated string relayIds = 6; 57 | bytes server_certificate = 4; // certificate to use when connecting to this client 58 | bytes client_certificate = 5; // certificate that this client uses when connecting 59 | } 60 | 61 | message RemotePeer { 62 | string id = 1; 63 | Peer peer = 8; 64 | } 65 | 66 | message Relay { 67 | string id = 3; 68 | repeated model.HostPort addresses = 4; 69 | bytes server_certificate = 2; 70 | } 71 | -------------------------------------------------------------------------------- /.github/workflows/release-tag.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_run: 3 | workflows: [ci] 4 | types: [completed] 5 | branches: [main] 6 | push: 7 | branches: [main] 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-tag 11 | cancel-in-progress: false 12 | 13 | jobs: 14 | changes: 15 | name: Detect version change 16 | runs-on: ubuntu-latest 17 | permissions: 18 | contents: read 19 | outputs: 20 | version: ${{ steps.filter.outputs.version }} 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: dorny/paths-filter@v3 24 | id: filter 25 | with: 26 | filters: | 27 | version: 28 | - 'VERSION' 29 | 30 | tag-release: 31 | name: Tag release on version change 32 | runs-on: ubuntu-latest 33 | needs: changes 34 | if: ${{ needs.changes.outputs.version == 'true' }} 35 | permissions: 36 | contents: write 37 | outputs: 38 | version: ${{ steps.extract_version.outputs.version }} 39 | steps: 40 | - uses: actions/checkout@v4 41 | - name: Extract Version 42 | id: extract_version 43 | run: | 44 | echo "version=$(cat VERSION)" >> $GITHUB_OUTPUT 45 | - name: Create release 46 | uses: softprops/action-gh-release@v2 47 | with: 48 | tag_name: v${{ steps.extract_version.outputs.version }} 49 | generate_release_notes: true 50 | 51 | perform-release: 52 | name: Perform release 53 | needs: tag-release 54 | uses: ./.github/workflows/release.yml 55 | with: 56 | version: ${{ needs.tag-release.outputs.version }} 57 | permissions: 58 | contents: write 59 | packages: write 60 | id-token: write 61 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-utils": { 4 | "inputs": { 5 | "systems": "systems" 6 | }, 7 | "locked": { 8 | "lastModified": 1731533236, 9 | "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", 10 | "owner": "numtide", 11 | "repo": "flake-utils", 12 | "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", 13 | "type": "github" 14 | }, 15 | "original": { 16 | "owner": "numtide", 17 | "repo": "flake-utils", 18 | "type": "github" 19 | } 20 | }, 21 | "nixpkgs": { 22 | "locked": { 23 | "lastModified": 1764642553, 24 | "narHash": "sha256-mvbFFzVBhVK1FjyPHZGMAKpNiqkr7k++xIwy+p/NQvA=", 25 | "owner": "NixOS", 26 | "repo": "nixpkgs", 27 | "rev": "f720de59066162ee879adcc8c79e15c51fe6bfb4", 28 | "type": "github" 29 | }, 30 | "original": { 31 | "owner": "NixOS", 32 | "ref": "nixpkgs-unstable", 33 | "repo": "nixpkgs", 34 | "type": "github" 35 | } 36 | }, 37 | "root": { 38 | "inputs": { 39 | "flake-utils": "flake-utils", 40 | "nixpkgs": "nixpkgs" 41 | } 42 | }, 43 | "systems": { 44 | "locked": { 45 | "lastModified": 1681028828, 46 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 47 | "owner": "nix-systems", 48 | "repo": "default", 49 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 50 | "type": "github" 51 | }, 52 | "original": { 53 | "owner": "nix-systems", 54 | "repo": "default", 55 | "type": "github" 56 | } 57 | } 58 | }, 59 | "root": "root", 60 | "version": 7 61 | } 62 | -------------------------------------------------------------------------------- /proto/proto.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | import ( 4 | "encoding/binary" 5 | "io" 6 | 7 | "github.com/connet-dev/connet/proto/pberror" 8 | "google.golang.org/protobuf/proto" 9 | ) 10 | 11 | func Write(w io.Writer, msg proto.Message) error { 12 | msgBytes, err := proto.Marshal(msg) 13 | if err != nil { 14 | return err 15 | } 16 | szBytes := make([]byte, 0, 8) 17 | szBytes = binary.BigEndian.AppendUint64(szBytes, uint64(len(msgBytes))) 18 | if _, err := w.Write(szBytes); err != nil { 19 | if aperr := pberror.GetAppError(err); aperr != nil { 20 | return &pberror.Error{ 21 | Code: pberror.Code(aperr.ErrorCode), 22 | Message: aperr.ErrorMessage, 23 | } 24 | } 25 | return err 26 | } 27 | _, err = w.Write(msgBytes) 28 | if err != nil { 29 | if aperr := pberror.GetAppError(err); aperr != nil { 30 | return &pberror.Error{ 31 | Code: pberror.Code(aperr.ErrorCode), 32 | Message: aperr.ErrorMessage, 33 | } 34 | } 35 | } 36 | return err 37 | } 38 | 39 | func Read(r io.Reader, msg proto.Message) error { 40 | szBytes := make([]byte, 8) 41 | 42 | _, err := io.ReadFull(r, szBytes) 43 | if err != nil { 44 | if aperr := pberror.GetAppError(err); aperr != nil { 45 | return &pberror.Error{ 46 | Code: pberror.Code(aperr.ErrorCode), 47 | Message: aperr.ErrorMessage, 48 | } 49 | } 50 | return err 51 | } 52 | sz := binary.BigEndian.Uint64(szBytes) 53 | 54 | msgBytes := make([]byte, sz) 55 | _, err = io.ReadFull(r, msgBytes) 56 | if err != nil { 57 | if aperr := pberror.GetAppError(err); aperr != nil { 58 | return &pberror.Error{ 59 | Code: pberror.Code(aperr.ErrorCode), 60 | Message: aperr.ErrorMessage, 61 | } 62 | } 63 | return err 64 | } 65 | 66 | return proto.Unmarshal(msgBytes, msg) 67 | } 68 | -------------------------------------------------------------------------------- /netc/addrs.go: -------------------------------------------------------------------------------- 1 | package netc 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "net/netip" 7 | ) 8 | 9 | func LocalAddrs() ([]netip.Addr, error) { 10 | ifaces, err := net.Interfaces() 11 | if err != nil { 12 | return nil, fmt.Errorf("net interfaces: %w", err) 13 | } 14 | 15 | var localAddrs []netip.Addr 16 | for _, iface := range ifaces { 17 | addrs, err := iface.Addrs() 18 | if err != nil { 19 | continue 20 | } 21 | 22 | NEXT: 23 | for _, addr := range addrs { 24 | var ip net.IP 25 | switch ipAddr := addr.(type) { 26 | case *net.IPAddr: 27 | ip = ipAddr.IP 28 | case *net.IPNet: 29 | ip = ipAddr.IP 30 | default: 31 | continue NEXT 32 | } 33 | if ip.IsLoopback() { 34 | continue 35 | } 36 | if ip4 := ip.To4(); ip4 != nil { 37 | localAddrs = append(localAddrs, netip.AddrFrom4([4]byte(ip4))) 38 | } 39 | if ip6 := ip.To16(); ip6 != nil { 40 | localAddrs = append(localAddrs, netip.AddrFrom16([16]byte(ip6))) 41 | } 42 | } 43 | } 44 | 45 | return localAddrs, nil 46 | } 47 | 48 | func AddrFromNet(addr net.Addr) (netip.Addr, error) { 49 | a, err := AddrPortFromNet(addr) 50 | if err != nil { 51 | return netip.Addr{}, err 52 | } 53 | return a.Addr(), nil 54 | } 55 | 56 | func AddrPortFromNet(addr net.Addr) (netip.AddrPort, error) { 57 | switch t := addr.(type) { 58 | case *net.UDPAddr: 59 | return t.AddrPort(), nil 60 | case *net.TCPAddr: 61 | return t.AddrPort(), nil 62 | default: 63 | naddr, err := netip.ParseAddrPort(addr.String()) 64 | if err != nil { 65 | return netip.AddrPort{}, err 66 | } 67 | return naddr, nil 68 | } 69 | } 70 | 71 | func IPFromNet(addr net.Addr) (net.IP, error) { 72 | a, err := AddrPortFromNet(addr) 73 | if err != nil { 74 | return net.IP{}, err 75 | } 76 | return net.IP(a.Addr().AsSlice()), nil 77 | } 78 | -------------------------------------------------------------------------------- /restr/ip_test.go: -------------------------------------------------------------------------------- 1 | package restr 2 | 3 | import ( 4 | "net/netip" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestIP(t *testing.T) { 11 | tcs := []struct { 12 | name string 13 | allow []string 14 | deny []string 15 | check string 16 | accept bool 17 | }{ 18 | { 19 | name: "empty", 20 | check: "10.100.2.100", 21 | accept: true, 22 | }, 23 | { 24 | name: "allow match", 25 | allow: []string{"10.100.2.0/24"}, 26 | check: "10.100.2.100", 27 | accept: true, 28 | }, 29 | { 30 | name: "allow nomatch", 31 | allow: []string{"10.100.2.0/24"}, 32 | check: "10.101.2.100", 33 | accept: false, 34 | }, 35 | { 36 | name: "deny match", 37 | deny: []string{"10.100.2.0/24"}, 38 | check: "10.100.2.100", 39 | accept: false, 40 | }, 41 | { 42 | name: "deny empty allow", 43 | deny: []string{"10.100.2.0/24"}, 44 | check: "10.101.2.100", 45 | accept: true, 46 | }, 47 | { 48 | name: "deny with allow", 49 | allow: []string{"10.100.2.0/24"}, 50 | deny: []string{"10.100.2.0/24"}, 51 | check: "10.100.2.100", 52 | accept: false, 53 | }, 54 | { 55 | name: "allow explicit", 56 | allow: []string{"10.101.2.0/24"}, 57 | deny: []string{"10.100.2.0/24"}, 58 | check: "10.102.2.100", 59 | accept: false, 60 | }, 61 | { 62 | name: "allow exact", 63 | allow: []string{"10.101.2.0/24"}, 64 | deny: []string{"10.100.2.0/24"}, 65 | check: "10.101.2.100", 66 | accept: true, 67 | }, 68 | } 69 | 70 | for _, tc := range tcs { 71 | t.Run(tc.name, func(t *testing.T) { 72 | restr, err := ParseIP(tc.allow, tc.deny) 73 | require.NoError(t, err) 74 | require.Equal(t, tc.accept, restr.IsAllowed(netip.MustParseAddr(tc.check))) 75 | }) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /selfhosted/clients.go: -------------------------------------------------------------------------------- 1 | package selfhosted 2 | 3 | import ( 4 | "github.com/connet-dev/connet/control" 5 | "github.com/connet-dev/connet/model" 6 | "github.com/connet-dev/connet/proto/pberror" 7 | "github.com/connet-dev/connet/restr" 8 | ) 9 | 10 | type ClientAuthentication struct { 11 | Token string 12 | IPs restr.IP 13 | Names restr.Name 14 | Role model.Role 15 | } 16 | 17 | func NewClientAuthenticator(auths ...ClientAuthentication) control.ClientAuthenticator { 18 | s := &clientsAuthenticator{map[string]*ClientAuthentication{}} 19 | for _, auth := range auths { 20 | s.tokens[auth.Token] = &auth 21 | } 22 | return s 23 | } 24 | 25 | type clientsAuthenticator struct { 26 | tokens map[string]*ClientAuthentication 27 | } 28 | 29 | func (s *clientsAuthenticator) Authenticate(req control.ClientAuthenticateRequest) (control.ClientAuthentication, error) { 30 | r, ok := s.tokens[req.Token] 31 | if !ok { 32 | return nil, pberror.NewError(pberror.Code_AuthenticationFailed, "token not found") 33 | } 34 | if !r.IPs.IsAllowedAddr(req.Addr) { 35 | return nil, pberror.NewError(pberror.Code_AuthenticationFailed, "address not allowed: %s", req.Addr) 36 | } 37 | return []byte(req.Token), nil 38 | } 39 | 40 | func (s *clientsAuthenticator) Validate(auth control.ClientAuthentication, endpoint model.Endpoint, role model.Role) (model.Endpoint, error) { 41 | r, ok := s.tokens[string(auth)] 42 | if !ok { 43 | return model.Endpoint{}, pberror.NewError(pberror.Code_AuthenticationFailed, "token not found") 44 | } 45 | if !r.Names.IsAllowed(endpoint.String()) { 46 | return model.Endpoint{}, pberror.NewError(pberror.Code_EndpointNotAllowed, "endpoint not allowed: %s", endpoint) 47 | } 48 | if r.Role != model.UnknownRole && r.Role != role { 49 | return model.Endpoint{}, pberror.NewError(pberror.Code_RoleNotAllowed, "role not allowed: %s", role) 50 | } 51 | return endpoint, nil 52 | } 53 | -------------------------------------------------------------------------------- /destination_config.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/connet-dev/connet/model" 7 | ) 8 | 9 | // DestinationConfig structure represents destination configuration. 10 | type DestinationConfig struct { 11 | Endpoint model.Endpoint 12 | Route model.RouteOption 13 | Proxy model.ProxyVersion 14 | RelayEncryptions []model.EncryptionScheme 15 | DialTimeout time.Duration 16 | } 17 | 18 | // NewDestinationConfig creates a destination config for a given name 19 | func NewDestinationConfig(name string) DestinationConfig { 20 | return DestinationConfig{ 21 | Endpoint: model.NewEndpoint(name), 22 | Route: model.RouteAny, 23 | Proxy: model.ProxyNone, 24 | RelayEncryptions: []model.EncryptionScheme{model.NoEncryption}, 25 | } 26 | } 27 | 28 | // WithRoute sets the route option for this configuration. 29 | func (cfg DestinationConfig) WithRoute(route model.RouteOption) DestinationConfig { 30 | cfg.Route = route 31 | return cfg 32 | } 33 | 34 | // WithProxy sets the proxy version option for this configuration. 35 | func (cfg DestinationConfig) WithProxy(proxy model.ProxyVersion) DestinationConfig { 36 | cfg.Proxy = proxy 37 | return cfg 38 | } 39 | 40 | // WithRelayEncryptions sets the relay encryptions option for this configuration. 41 | func (cfg DestinationConfig) WithRelayEncryptions(schemes ...model.EncryptionScheme) DestinationConfig { 42 | cfg.RelayEncryptions = schemes 43 | return cfg 44 | } 45 | 46 | // WithDialTimeout sets the dial timeout 47 | func (cfg DestinationConfig) WithDialTimeout(timeout time.Duration) DestinationConfig { 48 | cfg.DialTimeout = timeout 49 | return cfg 50 | } 51 | 52 | func (cfg DestinationConfig) endpointConfig() endpointConfig { 53 | return endpointConfig{ 54 | endpoint: cfg.Endpoint, 55 | role: model.Destination, 56 | route: cfg.Route, 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /model/proxy.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | 7 | "github.com/connet-dev/connet/proto/pbconnect" 8 | "github.com/pires/go-proxyproto" 9 | ) 10 | 11 | type ProxyVersion struct{ string } 12 | 13 | var ( 14 | ProxyNone = ProxyVersion{"none"} 15 | ProxyV1 = ProxyVersion{"v1"} 16 | ProxyV2 = ProxyVersion{"v2"} 17 | ) 18 | 19 | func ProxyVersionFromPB(r pbconnect.ProxyProtoVersion) ProxyVersion { 20 | switch r { 21 | case pbconnect.ProxyProtoVersion_V1: 22 | return ProxyV1 23 | case pbconnect.ProxyProtoVersion_V2: 24 | return ProxyV2 25 | default: 26 | return ProxyNone 27 | } 28 | } 29 | 30 | func ParseProxyVersion(s string) (ProxyVersion, error) { 31 | switch s { 32 | case ProxyV1.string: 33 | return ProxyV1, nil 34 | case ProxyV2.string: 35 | return ProxyV2, nil 36 | } 37 | return ProxyNone, fmt.Errorf("invalid proxy proto version: %s", s) 38 | } 39 | 40 | func (v ProxyVersion) PB() pbconnect.ProxyProtoVersion { 41 | switch v { 42 | case ProxyV1: 43 | return pbconnect.ProxyProtoVersion_V1 44 | case ProxyV2: 45 | return pbconnect.ProxyProtoVersion_V2 46 | default: 47 | return pbconnect.ProxyProtoVersion_ProxyProtoNone 48 | } 49 | } 50 | 51 | func (v ProxyVersion) Wrap(conn net.Conn) net.Conn { 52 | if v == ProxyNone { 53 | return conn 54 | } 55 | version := byte(2) 56 | if v == ProxyV1 { 57 | version = byte(1) 58 | } 59 | return &proxyProtoConn{conn, version} 60 | } 61 | 62 | type ProxyProtoConn interface { 63 | WriteProxyHeader(sourceAddr, destAddr net.Addr) error 64 | } 65 | 66 | type proxyProtoConn struct { 67 | net.Conn 68 | proxyProtoVersion byte 69 | } 70 | 71 | var _ ProxyProtoConn = (*proxyProtoConn)(nil) 72 | 73 | func (c *proxyProtoConn) WriteProxyHeader(sourceAddr net.Addr, destAddr net.Addr) error { 74 | pp := proxyproto.HeaderProxyFromAddrs(c.proxyProtoVersion, sourceAddr, destAddr) 75 | _, err := pp.WriteTo(c.Conn) 76 | return err 77 | } 78 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | push: 4 | branches: [main] 5 | 6 | permissions: 7 | id-token: write 8 | contents: read 9 | 10 | jobs: 11 | build: 12 | name: Build 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: DeterminateSystems/nix-installer-action@main 17 | with: 18 | determinate: true 19 | github-token: ${{ secrets.GITHUB_TOKEN }} 20 | - uses: DeterminateSystems/flakehub-cache-action@main 21 | - name: Build connet 22 | run: nix develop --command make build 23 | 24 | test: 25 | name: Test 26 | runs-on: ubuntu-latest 27 | needs: [build] 28 | steps: 29 | - uses: actions/checkout@v4 30 | - uses: DeterminateSystems/nix-installer-action@main 31 | with: 32 | determinate: true 33 | github-token: ${{ secrets.GITHUB_TOKEN }} 34 | - uses: DeterminateSystems/flakehub-cache-action@main 35 | - name: Run tests 36 | run: nix develop --command make test 37 | - name: Run lint 38 | run: nix develop --command make lint 39 | - name: Go module tidy 40 | run: nix develop --command go mod tidy 41 | - name: Gen proto 42 | run: nix develop --command make gen 43 | - name: Check if tidy or gen proto changed anything 44 | run: git diff --exit-code 45 | 46 | nix-build: 47 | name: Build nix packages 48 | runs-on: ubuntu-latest 49 | needs: [build] 50 | steps: 51 | - uses: actions/checkout@v4 52 | - uses: DeterminateSystems/nix-installer-action@main 53 | with: 54 | determinate: true 55 | github-token: ${{ secrets.GITHUB_TOKEN }} 56 | - uses: DeterminateSystems/flakehub-cache-action@main 57 | - uses: DeterminateSystems/flake-checker-action@main 58 | - name: Build default 59 | run: nix build . 60 | - name: Build docker 61 | run: nix build .#docker 62 | - name: Flake check 63 | run: nix flake check -L 64 | -------------------------------------------------------------------------------- /restr/ip.go: -------------------------------------------------------------------------------- 1 | package restr 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "net/netip" 7 | 8 | "github.com/connet-dev/connet/netc" 9 | ) 10 | 11 | type IP struct { 12 | Allows []netip.Prefix `json:"allows,omitempty"` 13 | Denies []netip.Prefix `json:"denies,omitempty"` 14 | } 15 | 16 | // ParseIP parses a slice of allows/denys restrictions in CIDR format. 17 | func ParseIP(allowsStr []string, deniesStr []string) (IP, error) { 18 | allows, err := netc.ParseCIDRs(allowsStr) 19 | if err != nil { 20 | return IP{}, fmt.Errorf("parse allow cidrs %v: %w", allowsStr, err) 21 | } 22 | 23 | denies, err := netc.ParseCIDRs(deniesStr) 24 | if err != nil { 25 | return IP{}, fmt.Errorf("parse deny cidrs: %w", err) 26 | } 27 | 28 | return IP{allows, denies}, nil 29 | } 30 | 31 | func (r IP) IsEmpty() bool { 32 | return len(r.Allows) == 0 && len(r.Denies) == 0 33 | } 34 | 35 | func (r IP) IsNotEmpty() bool { 36 | return !r.IsEmpty() 37 | } 38 | 39 | // IsAllowed checks if an IP address is allowed according to Allows and Denies rules. 40 | // 41 | // If the IP matches any of the Denies rules, IsAllowed returns false. 42 | // If the IP matches any of the Allows rules (after checking all Denies rules), IsAllowed returns true. 43 | // 44 | // Finally, if the IP matches no Allows or Denies rules, IsAllowed returns true only if no explicit Allows rules were defined. 45 | func (r IP) IsAllowed(ip netip.Addr) bool { 46 | ip = ip.Unmap() // remove any ipv6 prefix for ipv4 47 | 48 | for _, d := range r.Denies { 49 | if d.Contains(ip) { 50 | return false 51 | } 52 | } 53 | 54 | for _, a := range r.Allows { 55 | if a.Contains(ip) { 56 | return true 57 | } 58 | } 59 | 60 | return len(r.Allows) == 0 61 | } 62 | 63 | // IsAllowedAddr extracts the IP address from net.Addr and checks if it is allowed 64 | func (r IP) IsAllowedAddr(addr net.Addr) bool { 65 | switch taddr := addr.(type) { 66 | case *net.UDPAddr: 67 | return r.IsAllowed(taddr.AddrPort().Addr()) 68 | case *net.TCPAddr: 69 | return r.IsAllowed(taddr.AddrPort().Addr()) 70 | default: 71 | naddr, err := netip.ParseAddrPort(addr.String()) 72 | if err != nil { 73 | return false 74 | } 75 | return r.IsAllowed(naddr.Addr()) 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /model/protos.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "github.com/connet-dev/connet/iterc" 5 | "github.com/quic-go/quic-go" 6 | ) 7 | 8 | type ClientNextProto struct{ string } 9 | 10 | func (v ClientNextProto) String() string { 11 | return v.string 12 | } 13 | 14 | func GetClientNextProto(conn *quic.Conn) ClientNextProto { 15 | proto := conn.ConnectionState().TLS.NegotiatedProtocol 16 | for _, v := range AllClientNextProtos { 17 | if v.string == proto { 18 | return v 19 | } 20 | } 21 | return CNUnknown 22 | } 23 | 24 | var ( 25 | CNUnknown = ClientNextProto{} 26 | CNv02 = ClientNextProto{"connet-client/0.2"} // 0.8.0 27 | ) 28 | 29 | var AllClientNextProtos = []ClientNextProto{CNv02} 30 | 31 | var ClientNextProtos = iterc.MapSliceStrings(AllClientNextProtos) 32 | 33 | type ConnectDirectNextProto struct{ string } 34 | 35 | func (v ConnectDirectNextProto) String() string { 36 | return v.string 37 | } 38 | 39 | var ( 40 | CCv01 = ConnectDirectNextProto{"connet-peer/0.1"} // 0.7.0 41 | ) 42 | 43 | var AllConnectDirectNextProtos = []ConnectDirectNextProto{CCv01} 44 | 45 | var ConnectDirectNextProtos = iterc.MapSlice(AllConnectDirectNextProtos, ConnectDirectNextProto.String) 46 | 47 | type ConnectRelayNextProto struct{ string } 48 | 49 | func (v ConnectRelayNextProto) String() string { 50 | return v.string 51 | } 52 | 53 | var ( 54 | CRv01 = ConnectRelayNextProto{"connet-peer-relay/0.1"} // 0.7.0 55 | ) 56 | 57 | var AllConnectRelayNextProtos = []ConnectRelayNextProto{CRv01} 58 | 59 | var ConnectRelayNextProtos = iterc.MapSlice(AllConnectRelayNextProtos, ConnectRelayNextProto.String) 60 | 61 | type RelayNextProto struct{ string } 62 | 63 | func (v RelayNextProto) String() string { 64 | return v.string 65 | } 66 | 67 | func GetRelayNextProto(conn *quic.Conn) RelayNextProto { 68 | proto := conn.ConnectionState().TLS.NegotiatedProtocol 69 | for _, v := range AllRelayNextProtos { 70 | if v.string == proto { 71 | return v 72 | } 73 | } 74 | return RNUnknown 75 | } 76 | 77 | var ( 78 | RNUnknown = RelayNextProto{} 79 | RNv02 = RelayNextProto{"connet-relay/0.2"} // 0.8.0 80 | ) 81 | 82 | var AllRelayNextProtos = []RelayNextProto{RNv02} 83 | 84 | var RelayNextProtos = iterc.MapSliceStrings(AllRelayNextProtos) 85 | -------------------------------------------------------------------------------- /source_config.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/connet-dev/connet/model" 7 | ) 8 | 9 | // SourceConfig structure represents source configuration. 10 | type SourceConfig struct { 11 | Endpoint model.Endpoint 12 | Route model.RouteOption 13 | RelayEncryptions []model.EncryptionScheme 14 | DialTimeout time.Duration 15 | 16 | DestinationPolicy model.LoadBalancePolicy 17 | DestinationRetry model.LoadBalanceRetry 18 | DestinationRetryMax int 19 | } 20 | 21 | // NewSourceConfig creates a source config for a given name. 22 | func NewSourceConfig(name string) SourceConfig { 23 | return SourceConfig{ 24 | Endpoint: model.NewEndpoint(name), 25 | Route: model.RouteAny, 26 | RelayEncryptions: []model.EncryptionScheme{model.NoEncryption}, 27 | DestinationPolicy: model.NoPolicy, 28 | DestinationRetry: model.NeverRetry, 29 | } 30 | } 31 | 32 | // WithRoute sets the route option for this configuration. 33 | func (cfg SourceConfig) WithRoute(route model.RouteOption) SourceConfig { 34 | cfg.Route = route 35 | return cfg 36 | } 37 | 38 | // WithRelayEncryptions sets the relay encryptions option for this configuration. 39 | func (cfg SourceConfig) WithRelayEncryptions(schemes ...model.EncryptionScheme) SourceConfig { 40 | cfg.RelayEncryptions = schemes 41 | return cfg 42 | } 43 | 44 | // WithDialTimeout sets the dial timeout 45 | func (cfg SourceConfig) WithDialTimeout(timeout time.Duration) SourceConfig { 46 | cfg.DialTimeout = timeout 47 | return cfg 48 | } 49 | 50 | // WithLoadBalance sets the load balancing behavior for this source 51 | func (cfg SourceConfig) WithLoadBalance(policy model.LoadBalancePolicy, retry model.LoadBalanceRetry, max int) SourceConfig { 52 | cfg.DestinationPolicy = policy 53 | cfg.DestinationRetry = retry 54 | cfg.DestinationRetryMax = max 55 | 56 | switch { 57 | case cfg.DestinationRetry == model.CountRetry && cfg.DestinationRetryMax == 0: 58 | cfg.DestinationRetryMax = 2 59 | case cfg.DestinationRetry == model.TimedRetry && cfg.DestinationRetryMax == 0: 60 | cfg.DestinationRetryMax = 1000 61 | } 62 | 63 | return cfg 64 | } 65 | 66 | func (cfg SourceConfig) endpointConfig() endpointConfig { 67 | return endpointConfig{ 68 | endpoint: cfg.Endpoint, 69 | role: model.Source, 70 | route: cfg.Route, 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /control/ingress.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "net" 7 | 8 | "github.com/connet-dev/connet/restr" 9 | ) 10 | 11 | type Ingress struct { 12 | Addr *net.UDPAddr 13 | TLS *tls.Config 14 | Restr restr.IP 15 | } 16 | 17 | type IngressBuilder struct { 18 | ingress Ingress 19 | err error 20 | } 21 | 22 | func NewIngressBuilder() *IngressBuilder { return &IngressBuilder{} } 23 | 24 | func (b *IngressBuilder) WithAddr(addr *net.UDPAddr) *IngressBuilder { 25 | if b.err != nil { 26 | return b 27 | } 28 | b.ingress.Addr = addr 29 | return b 30 | } 31 | 32 | func (b *IngressBuilder) WithAddrFrom(addrStr string) *IngressBuilder { 33 | if b.err != nil { 34 | return b 35 | } 36 | 37 | addr, err := net.ResolveUDPAddr("udp", addrStr) 38 | if err != nil { 39 | b.err = fmt.Errorf("resolve udp address: %w", err) 40 | return b 41 | } 42 | return b.WithAddr(addr) 43 | } 44 | 45 | func (b *IngressBuilder) WithTLS(cfg *tls.Config) *IngressBuilder { 46 | if b.err != nil { 47 | return b 48 | } 49 | 50 | b.ingress.TLS = cfg 51 | return b 52 | } 53 | 54 | func (b *IngressBuilder) WithTLSCert(cert tls.Certificate) *IngressBuilder { 55 | if b.err != nil { 56 | return b 57 | } 58 | 59 | return b.WithTLS(&tls.Config{Certificates: []tls.Certificate{cert}}) 60 | } 61 | 62 | func (b *IngressBuilder) WithTLSCertFrom(certFile, keyFile string) *IngressBuilder { 63 | if b.err != nil { 64 | return b 65 | } 66 | 67 | cert, err := tls.LoadX509KeyPair(certFile, keyFile) 68 | if err != nil { 69 | b.err = fmt.Errorf("load certificate: %w", err) 70 | return b 71 | } 72 | 73 | return b.WithTLSCert(cert) 74 | } 75 | 76 | func (b *IngressBuilder) WithRestr(iprestr restr.IP) *IngressBuilder { 77 | if b.err != nil { 78 | return b 79 | } 80 | 81 | b.ingress.Restr = iprestr 82 | return b 83 | } 84 | 85 | func (b *IngressBuilder) WithRestrFrom(allows []string, denies []string) *IngressBuilder { 86 | if b.err != nil { 87 | return b 88 | } 89 | 90 | iprestr, err := restr.ParseIP(allows, denies) 91 | if err != nil { 92 | b.err = fmt.Errorf("parse restrictions: %w", err) 93 | return b 94 | } 95 | return b.WithRestr(iprestr) 96 | } 97 | 98 | func (b *IngressBuilder) Error() error { 99 | return b.err 100 | } 101 | 102 | func (b *IngressBuilder) Ingress() (Ingress, error) { 103 | return b.ingress, b.err 104 | } 105 | -------------------------------------------------------------------------------- /cryptoc/stream_test.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/cipher" 5 | "crypto/rand" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/require" 12 | "golang.org/x/crypto/chacha20poly1305" 13 | ) 14 | 15 | func TestStream(t *testing.T) { 16 | serverReader, clientWriter := io.Pipe() 17 | clientReader, serverWriter := io.Pipe() 18 | 19 | var client = &rwc{clientReader, clientWriter} 20 | var server = &rwc{serverReader, serverWriter} 21 | 22 | var clientAEAD = newAEAD(t) 23 | var serverAEAD = newAEAD(t) 24 | 25 | var clientStream = NewStream(client, serverAEAD, clientAEAD) 26 | var serverStream = NewStream(server, clientAEAD, serverAEAD) 27 | 28 | go func() { 29 | _, err := io.Copy(serverStream, serverStream) 30 | require.NoError(t, err) 31 | }() 32 | 33 | t.Run("small", func(t *testing.T) { 34 | go func() { 35 | for i := range 1024 { 36 | var out = []byte(fmt.Sprintf("hello world %d", i)) 37 | _, err := clientStream.Write(out) 38 | require.NoError(t, err) 39 | } 40 | }() 41 | 42 | for i := range 1024 { 43 | var out = []byte(fmt.Sprintf("hello world %d", i)) 44 | 45 | var in = make([]byte, len(out)) 46 | n, err := clientStream.Read(in) 47 | require.NoError(t, err) 48 | require.Equal(t, len(out), n) 49 | require.Equal(t, out, in) 50 | } 51 | }) 52 | 53 | t.Run("big", func(t *testing.T) { 54 | var out = make([]byte, 1024*1024) 55 | _, err := io.ReadFull(rand.Reader, out) 56 | require.NoError(t, err) 57 | 58 | go func() { 59 | _, err := clientStream.Write(out) 60 | require.NoError(t, err) 61 | }() 62 | 63 | var in = make([]byte, len(out)) 64 | n, err := io.ReadFull(clientStream, in) 65 | require.NoError(t, err) 66 | require.Equal(t, len(out), n) 67 | require.Equal(t, out, in) 68 | }) 69 | } 70 | 71 | func newAEAD(t *testing.T) cipher.AEAD { 72 | key := make([]byte, chacha20poly1305.KeySize) 73 | _, err := io.ReadFull(rand.Reader, key) 74 | require.NoError(t, err) 75 | ccp, err := chacha20poly1305.New(key) 76 | require.NoError(t, err) 77 | return ccp 78 | } 79 | 80 | type rwc struct { 81 | reader io.ReadCloser 82 | writer io.WriteCloser 83 | } 84 | 85 | func (r *rwc) Close() error { 86 | return errors.Join(r.writer.Close(), r.reader.Close()) 87 | } 88 | 89 | func (r *rwc) Read(p []byte) (n int, err error) { 90 | return r.reader.Read(p) 91 | } 92 | 93 | func (r *rwc) Write(p []byte) (n int, err error) { 94 | return r.writer.Write(p) 95 | } 96 | -------------------------------------------------------------------------------- /model/encryption.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "fmt" 5 | "slices" 6 | 7 | "github.com/connet-dev/connet/proto/pbconnect" 8 | ) 9 | 10 | type EncryptionScheme struct{ string } 11 | 12 | var ( 13 | NoEncryption = EncryptionScheme{"none"} 14 | TLSEncryption = EncryptionScheme{"tls"} 15 | DHXCPEncryption = EncryptionScheme{"dhxcp"} 16 | ) 17 | 18 | func EncryptionFromPB(pb pbconnect.RelayEncryptionScheme) EncryptionScheme { 19 | switch pb { 20 | case pbconnect.RelayEncryptionScheme_EncryptionNone: 21 | return NoEncryption 22 | case pbconnect.RelayEncryptionScheme_TLS: 23 | return TLSEncryption 24 | case pbconnect.RelayEncryptionScheme_DHX25519_CHACHAPOLY: 25 | return DHXCPEncryption 26 | default: 27 | panic(fmt.Sprintf("invalid encryption scheme: %d", pb)) 28 | } 29 | } 30 | 31 | func ParseEncryptionScheme(s string) (EncryptionScheme, error) { 32 | switch s { 33 | case NoEncryption.string: 34 | return NoEncryption, nil 35 | case TLSEncryption.string: 36 | return TLSEncryption, nil 37 | case DHXCPEncryption.string: 38 | return DHXCPEncryption, nil 39 | default: 40 | return EncryptionScheme{}, fmt.Errorf("invalid encryption scheme '%s'", s) 41 | } 42 | } 43 | 44 | func (e EncryptionScheme) PB() pbconnect.RelayEncryptionScheme { 45 | switch e { 46 | case NoEncryption: 47 | return pbconnect.RelayEncryptionScheme_EncryptionNone 48 | case TLSEncryption: 49 | return pbconnect.RelayEncryptionScheme_TLS 50 | case DHXCPEncryption: 51 | return pbconnect.RelayEncryptionScheme_DHX25519_CHACHAPOLY 52 | default: 53 | panic(fmt.Sprintf("invalid encryption scheme: %s", e.string)) 54 | } 55 | } 56 | 57 | func PBFromEncryptions(schemes []EncryptionScheme) []pbconnect.RelayEncryptionScheme { 58 | pbs := make([]pbconnect.RelayEncryptionScheme, len(schemes)) 59 | for i, sc := range schemes { 60 | pbs[i] = sc.PB() 61 | } 62 | return pbs 63 | } 64 | 65 | func EncryptionsFromPB(pbs []pbconnect.RelayEncryptionScheme) []EncryptionScheme { 66 | schemes := make([]EncryptionScheme, len(pbs)) 67 | for i, s := range pbs { 68 | schemes[i] = EncryptionFromPB(s) 69 | } 70 | return schemes 71 | } 72 | 73 | func SelectEncryptionScheme(dst []EncryptionScheme, src []EncryptionScheme) (EncryptionScheme, error) { 74 | switch { 75 | case slices.Contains(dst, TLSEncryption) && slices.Contains(src, TLSEncryption): 76 | return TLSEncryption, nil 77 | case slices.Contains(dst, DHXCPEncryption) && slices.Contains(src, DHXCPEncryption): 78 | return DHXCPEncryption, nil 79 | case slices.Contains(dst, NoEncryption) && slices.Contains(src, NoEncryption): 80 | return NoEncryption, nil 81 | default: 82 | return EncryptionScheme{}, fmt.Errorf("no shared encryption schemes") 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all build test lint test-always 2 | 3 | default: all 4 | 5 | all: build test lint 6 | 7 | build: 8 | go install -v github.com/connet-dev/connet/cmd/... 9 | 10 | test: 11 | go test -v -cover -timeout 10s ./... 12 | 13 | lint: 14 | golangci-lint run 15 | 16 | test-always: 17 | go test -v -cover -timeout 10s -count 1 ./... 18 | 19 | test-nix: 20 | nix build .#checks.x86_64-linux.moduleTest 21 | 22 | test-nix-interactive: 23 | nix run .#checks.x86_64-linux.moduleTest.driverInteractive 24 | 25 | .PHONY: gen 26 | gen: 27 | fd --extension ".pb.go" . --exec-batch rm {} 28 | protoc --proto_path=proto/ --go_opt=module=github.com/connet-dev/connet --go_out=./ proto/*.proto 29 | 30 | .PHONY: run-server run-client run-sws 31 | run-server: build 32 | connet server --config examples/minimal.toml 33 | 34 | run-client: build 35 | connet --config examples/minimal.toml 36 | 37 | .PHONY: update-go update-nix 38 | 39 | update-go: 40 | go get -u ./... 41 | go mod tidy 42 | 43 | update-nix: 44 | nix flake update 45 | 46 | .PHONY: release-clean release-build release-archive release 47 | 48 | release-clean: 49 | rm -rf dist/ 50 | 51 | CONNET_VERSION ?= $(shell git describe --exact-match --tags 2> /dev/null || git rev-parse --short HEAD) 52 | LDFLAGS := "-X 'github.com/connet-dev/connet/model.Version=${CONNET_VERSION}'" 53 | 54 | release-build: 55 | GOOS=darwin GOARCH=amd64 go build -v -ldflags ${LDFLAGS} -o dist/build/darwin-amd64/connet github.com/connet-dev/connet/cmd/connet 56 | GOOS=darwin GOARCH=arm64 go build -v -ldflags ${LDFLAGS} -o dist/build/darwin-arm64/connet github.com/connet-dev/connet/cmd/connet 57 | GOOS=linux GOARCH=amd64 go build -v -ldflags ${LDFLAGS} -o dist/build/linux-amd64/connet github.com/connet-dev/connet/cmd/connet 58 | GOOS=linux GOARCH=arm64 go build -v -ldflags ${LDFLAGS} -o dist/build/linux-arm64/connet github.com/connet-dev/connet/cmd/connet 59 | GOOS=freebsd GOARCH=amd64 go build -v -ldflags ${LDFLAGS} -o dist/build/freebsd-amd64/connet github.com/connet-dev/connet/cmd/connet 60 | GOOS=freebsd GOARCH=arm64 go build -v -ldflags ${LDFLAGS} -o dist/build/freebsd-arm64/connet github.com/connet-dev/connet/cmd/connet 61 | GOOS=windows GOARCH=amd64 go build -v -ldflags ${LDFLAGS} -o dist/build/windows-amd64/connet.exe github.com/connet-dev/connet/cmd/connet 62 | GOOS=windows GOARCH=arm64 go build -v -ldflags ${LDFLAGS} -o dist/build/windows-arm64/connet.exe github.com/connet-dev/connet/cmd/connet 63 | 64 | release-archive: 65 | mkdir dist/archive 66 | for x in $(shell ls dist/build); do \ 67 | if [[ $$x == windows* || $$x == darwin* ]]; then \ 68 | zip --junk-paths dist/archive/connet-$(CONNET_VERSION)-$$x.zip dist/build/$$x/*; \ 69 | else \ 70 | tar -czf dist/archive/connet-$(CONNET_VERSION)-$$x.tar.gz -C dist/build/$$x connet; \ 71 | fi \ 72 | done 73 | 74 | release: release-clean release-build release-archive 75 | -------------------------------------------------------------------------------- /.github/workflows/tip.yaml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [main] 4 | 5 | permissions: 6 | packages: write 7 | id-token: write 8 | contents: read 9 | 10 | jobs: 11 | binary: 12 | name: Binaries 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: DeterminateSystems/nix-installer-action@main 17 | with: 18 | determinate: true 19 | github-token: ${{ secrets.GITHUB_TOKEN }} 20 | - uses: DeterminateSystems/flakehub-cache-action@main 21 | - name: Build release 22 | run: nix develop --command make release 23 | 24 | docker-build-x86: 25 | name: Build x86 image 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v4 29 | - uses: DeterminateSystems/nix-installer-action@main 30 | with: 31 | determinate: true 32 | github-token: ${{ secrets.GITHUB_TOKEN }} 33 | - uses: DeterminateSystems/flakehub-cache-action@main 34 | - name: Docker build 35 | run: nix build .#docker 36 | - name: Docker login 37 | uses: docker/login-action@v3 38 | with: 39 | registry: ghcr.io 40 | username: ${{ github.actor }} 41 | password: ${{ secrets.GITHUB_TOKEN }} 42 | - name: Docker push 43 | run: nix develop --command skopeo copy "docker-archive:result" "docker://ghcr.io/connet-dev/connet:latest-amd64" 44 | 45 | docker-build-arm: 46 | name: Build arm image 47 | runs-on: ubuntu-latest 48 | steps: 49 | - uses: actions/checkout@v4 50 | - uses: docker/setup-qemu-action@v3 51 | - uses: DeterminateSystems/nix-installer-action@main 52 | with: 53 | determinate: true 54 | github-token: ${{ secrets.GITHUB_TOKEN }} 55 | extra-conf: system = aarch64-linux 56 | - uses: DeterminateSystems/flakehub-cache-action@main 57 | - name: Docker build 58 | run: nix build .#docker 59 | - name: Docker login 60 | uses: docker/login-action@v3 61 | with: 62 | registry: ghcr.io 63 | username: ${{ github.actor }} 64 | password: ${{ secrets.GITHUB_TOKEN }} 65 | - name: Docker push 66 | run: nix develop --command skopeo copy "docker-archive:result" "docker://ghcr.io/connet-dev/connet:latest-arm64" 67 | 68 | docker-multiarch: 69 | name: Tag multi-arch 70 | runs-on: ubuntu-latest 71 | needs: [docker-build-x86, docker-build-arm] 72 | steps: 73 | - uses: actions/checkout@v4 74 | - uses: DeterminateSystems/nix-installer-action@main 75 | with: 76 | determinate: true 77 | github-token: ${{ secrets.GITHUB_TOKEN }} 78 | - uses: DeterminateSystems/flakehub-cache-action@main 79 | - name: Docker login 80 | uses: docker/login-action@v3 81 | with: 82 | registry: ghcr.io 83 | username: ${{ github.actor }} 84 | password: ${{ secrets.GITHUB_TOKEN }} 85 | - name: Docker tag 86 | run: nix develop --command manifest-tool push from-args --platforms linux/amd64,linux/arm64 --template ghcr.io/connet-dev/connet:latest-ARCHVARIANT --target ghcr.io/connet-dev/connet:latest 87 | 88 | -------------------------------------------------------------------------------- /server/server.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "fmt" 7 | "net" 8 | "path/filepath" 9 | 10 | "github.com/connet-dev/connet/certc" 11 | "github.com/connet-dev/connet/control" 12 | "github.com/connet-dev/connet/netc" 13 | "github.com/connet-dev/connet/relay" 14 | "github.com/connet-dev/connet/selfhosted" 15 | "golang.org/x/sync/errgroup" 16 | ) 17 | 18 | type Server struct { 19 | serverConfig 20 | 21 | control *control.Server 22 | relay *relay.Server 23 | } 24 | 25 | func New(opts ...Option) (*Server, error) { 26 | cfg, err := newServerConfig(opts) 27 | if err != nil { 28 | return nil, err 29 | } 30 | 31 | relayRootCert, err := certc.NewRoot() 32 | if err != nil { 33 | return nil, fmt.Errorf("generate relays root cert: %w", err) 34 | } 35 | 36 | relaysAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:19189") 37 | if err != nil { 38 | return nil, fmt.Errorf("resolve relays address: %w", err) 39 | } 40 | relaysCert, err := relayRootCert.NewServer(certc.CertOpts{ 41 | IPs: []net.IP{relaysAddr.IP}, 42 | }) 43 | if err != nil { 44 | return nil, fmt.Errorf("generate relays cert: %w", err) 45 | } 46 | relaysCAs, err := relaysCert.CertPool() 47 | if err != nil { 48 | return nil, fmt.Errorf("get relays CAs: %w", err) 49 | } 50 | relaysTLSCert, err := relaysCert.TLSCert() 51 | if err != nil { 52 | return nil, fmt.Errorf("get relays TLS cert: %w", err) 53 | } 54 | 55 | relayAuth := selfhosted.RelayAuthentication{ 56 | Token: netc.GenDomainName("relay"), 57 | } 58 | 59 | control, err := control.NewServer(control.Config{ 60 | ClientsIngress: cfg.clientsIngresses, 61 | ClientsAuth: cfg.clientsAuth, 62 | 63 | RelaysIngress: []control.Ingress{{ 64 | Addr: relaysAddr, 65 | TLS: &tls.Config{ 66 | Certificates: []tls.Certificate{relaysTLSCert}, 67 | }, 68 | }}, 69 | RelaysAuth: selfhosted.NewRelayAuthenticator(relayAuth), 70 | 71 | Stores: control.NewFileStores(filepath.Join(cfg.dir, "control")), 72 | Logger: cfg.logger, 73 | }) 74 | if err != nil { 75 | return nil, fmt.Errorf("create control server: %w", err) 76 | } 77 | 78 | relay, err := relay.NewServer(relay.Config{ 79 | ControlAddr: relaysAddr, 80 | ControlHost: relaysTLSCert.Leaf.IPAddresses[0].String(), 81 | ControlToken: relayAuth.Token, 82 | ControlCAs: relaysCAs, 83 | 84 | Ingress: cfg.relayIngresses, 85 | 86 | Stores: relay.NewFileStores(filepath.Join(cfg.dir, "relay")), 87 | Logger: cfg.logger, 88 | }) 89 | if err != nil { 90 | return nil, fmt.Errorf("create relay server: %w", err) 91 | } 92 | 93 | return &Server{ 94 | serverConfig: *cfg, 95 | 96 | control: control, 97 | relay: relay, 98 | }, nil 99 | } 100 | 101 | func (s *Server) Run(ctx context.Context) error { 102 | g, ctx := errgroup.WithContext(ctx) 103 | g.Go(func() error { return s.control.Run(ctx) }) 104 | g.Go(func() error { return s.relay.Run(ctx) }) 105 | return g.Wait() 106 | } 107 | 108 | func (s *Server) Status(ctx context.Context) (ServerStatus, error) { 109 | control, err := s.control.Status(ctx) 110 | if err != nil { 111 | return ServerStatus{}, err 112 | } 113 | 114 | relay, err := s.relay.Status(ctx) 115 | if err != nil { 116 | return ServerStatus{}, err 117 | } 118 | 119 | return ServerStatus{control, relay}, nil 120 | } 121 | 122 | type ServerStatus struct { 123 | Control control.Status `json:"control"` 124 | Relay relay.Status `json:"relay"` 125 | } 126 | -------------------------------------------------------------------------------- /control/secrets.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/binary" 6 | "errors" 7 | "fmt" 8 | "io" 9 | 10 | "golang.org/x/crypto/nacl/secretbox" 11 | ) 12 | 13 | var errEncryptedDataMissing = errors.New("encrypted data missing") 14 | var errSecretboxOpen = errors.New("secretbox open failed") 15 | 16 | type reconnectToken struct { 17 | secretKey [32]byte 18 | } 19 | 20 | func (s *reconnectToken) seal(data []byte) ([]byte, error) { 21 | var nonce [24]byte 22 | if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil { 23 | return nil, fmt.Errorf("generate rand: %w", err) 24 | } 25 | 26 | return secretbox.Seal(nonce[:], data, &nonce, &s.secretKey), nil 27 | } 28 | 29 | func (s *reconnectToken) open(encrypted []byte) ([]byte, error) { 30 | if len(encrypted) < 24 { 31 | return nil, errEncryptedDataMissing 32 | } 33 | 34 | var decryptNonce [24]byte 35 | copy(decryptNonce[:], encrypted[:24]) 36 | data, ok := secretbox.Open(nil, encrypted[24:], &decryptNonce, &s.secretKey) 37 | if !ok { 38 | return nil, errSecretboxOpen 39 | } 40 | return data, nil 41 | } 42 | 43 | func (s *reconnectToken) sealClientID(id ClientID) ([]byte, error) { 44 | return s.seal([]byte(id.string)) 45 | } 46 | 47 | func (s *reconnectToken) openClientID(encryptedID []byte) (ClientID, error) { 48 | data, err := s.open(encryptedID) 49 | if err != nil { 50 | return ClientIDNil, err 51 | } 52 | if len(data) == 20 { 53 | return ClientID{formatBase62(data)}, nil 54 | } 55 | return ClientID{string(data)}, nil 56 | } 57 | 58 | func (s *reconnectToken) sealRelayID(id RelayID) ([]byte, error) { 59 | return s.seal([]byte(id.string)) 60 | } 61 | 62 | func (s *reconnectToken) openRelayID(encryptedID []byte) (RelayID, error) { 63 | data, err := s.open(encryptedID) 64 | if err != nil { 65 | return RelayIDNil, err 66 | } 67 | if len(data) == 20 { 68 | return RelayID{formatBase62(data)}, nil 69 | } 70 | return RelayID{string(data)}, nil 71 | } 72 | 73 | // TODO copied from ksuid, remove in v0.11.0 74 | const base62Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 75 | const zeroString = "000000000000000000000000000" 76 | 77 | func formatBase62(src []byte) string { 78 | var dst = make([]byte, 27) 79 | const srcBase = 4294967296 80 | const dstBase = 62 81 | 82 | // Split src into 5 4-byte words, this is where most of the efficiency comes 83 | // from because this is a O(N^2) algorithm, and we make N = N / 4 by working 84 | // on 32 bits at a time. 85 | parts := [5]uint32{ 86 | binary.BigEndian.Uint32(src[0:4]), 87 | binary.BigEndian.Uint32(src[4:8]), 88 | binary.BigEndian.Uint32(src[8:12]), 89 | binary.BigEndian.Uint32(src[12:16]), 90 | binary.BigEndian.Uint32(src[16:20]), 91 | } 92 | 93 | n := len(dst) 94 | bp := parts[:] 95 | bq := [5]uint32{} 96 | 97 | for len(bp) != 0 { 98 | quotient := bq[:0] 99 | remainder := uint64(0) 100 | 101 | for _, c := range bp { 102 | value := uint64(c) + uint64(remainder)*srcBase 103 | digit := value / dstBase 104 | remainder = value % dstBase 105 | 106 | if len(quotient) != 0 || digit != 0 { 107 | quotient = append(quotient, uint32(digit)) 108 | } 109 | } 110 | 111 | // Writes at the end of the destination buffer because we computed the 112 | // lowest bits first. 113 | n-- 114 | dst[n] = base62Characters[remainder] 115 | bp = quotient 116 | } 117 | 118 | // Add padding at the head of the destination buffer for all bytes that were 119 | // not set. 120 | copy(dst[:n], zeroString) 121 | return string(dst) 122 | } 123 | -------------------------------------------------------------------------------- /control/server.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log/slog" 7 | 8 | "github.com/connet-dev/connet/iterc" 9 | "github.com/connet-dev/connet/logc" 10 | "github.com/connet-dev/connet/model" 11 | "github.com/connet-dev/connet/reliable" 12 | ) 13 | 14 | type Config struct { 15 | ClientsIngress []Ingress 16 | ClientsAuth ClientAuthenticator 17 | 18 | RelaysIngress []Ingress 19 | RelaysAuth RelayAuthenticator 20 | 21 | Stores Stores 22 | 23 | Logger *slog.Logger 24 | } 25 | 26 | func NewServer(cfg Config) (*Server, error) { 27 | configStore, err := cfg.Stores.Config() 28 | if err != nil { 29 | return nil, fmt.Errorf("config store open: %w", err) 30 | } 31 | 32 | relays, err := newRelayServer(cfg.RelaysIngress, cfg.RelaysAuth, configStore, cfg.Stores, cfg.Logger) 33 | if err != nil { 34 | return nil, fmt.Errorf("create relay server: %w", err) 35 | } 36 | 37 | clients, err := newClientServer(cfg.ClientsIngress, cfg.ClientsAuth, relays, configStore, cfg.Stores, cfg.Logger) 38 | if err != nil { 39 | return nil, fmt.Errorf("create client server: %w", err) 40 | } 41 | 42 | return &Server{ 43 | clients: clients, 44 | relays: relays, 45 | 46 | config: configStore, 47 | }, nil 48 | } 49 | 50 | type Server struct { 51 | clients *clientServer 52 | relays *relayServer 53 | 54 | config logc.KV[ConfigKey, ConfigValue] 55 | } 56 | 57 | func (s *Server) Run(ctx context.Context) error { 58 | return reliable.RunGroup(ctx, 59 | s.relays.run, 60 | s.clients.run, 61 | logc.ScheduleCompact(s.config), 62 | ) 63 | } 64 | 65 | func (s *Server) Status(ctx context.Context) (Status, error) { 66 | clients, err := s.getClients() 67 | if err != nil { 68 | return Status{}, err 69 | } 70 | 71 | peers, err := s.getPeers() 72 | if err != nil { 73 | return Status{}, err 74 | } 75 | 76 | relays, err := s.getRelays() 77 | if err != nil { 78 | return Status{}, err 79 | } 80 | 81 | return Status{ 82 | ServerID: s.relays.id, 83 | Clients: clients, 84 | Peers: peers, 85 | Relays: relays, 86 | }, nil 87 | } 88 | 89 | func (s *Server) getClients() ([]StatusClient, error) { 90 | clientMsgs, _, err := s.clients.conns.Snapshot() 91 | if err != nil { 92 | return nil, err 93 | } 94 | 95 | var clients []StatusClient 96 | for _, msg := range clientMsgs { 97 | clients = append(clients, StatusClient{ 98 | ID: msg.Key.ID, 99 | Addr: msg.Value.Addr, 100 | }) 101 | } 102 | 103 | return clients, nil 104 | } 105 | 106 | func (s *Server) getPeers() ([]StatusPeer, error) { 107 | peerMsgs, _, err := s.clients.peers.Snapshot() 108 | if err != nil { 109 | return nil, err 110 | } 111 | 112 | var peers []StatusPeer 113 | for _, msg := range peerMsgs { 114 | peers = append(peers, StatusPeer{ 115 | ID: msg.Key.ID, 116 | Role: msg.Key.Role, 117 | Endpoint: msg.Key.Endpoint, 118 | }) 119 | } 120 | 121 | return peers, nil 122 | } 123 | 124 | func (s *Server) getRelays() ([]StatusRelay, error) { 125 | msgs, _, err := s.relays.conns.Snapshot() 126 | if err != nil { 127 | return nil, err 128 | } 129 | 130 | var relays []StatusRelay 131 | for _, msg := range msgs { 132 | relays = append(relays, StatusRelay{ 133 | ID: msg.Key.ID, 134 | Hostports: iterc.MapSlice(msg.Value.Hostports, model.HostPort.String), 135 | }) 136 | } 137 | 138 | return relays, nil 139 | } 140 | 141 | type Status struct { 142 | ServerID string `json:"server_id"` 143 | Clients []StatusClient `json:"clients"` 144 | Peers []StatusPeer `json:"peers"` 145 | Relays []StatusRelay `json:"relays"` 146 | } 147 | 148 | type StatusClient struct { 149 | ID ClientID `json:"id"` 150 | Addr string `json:"addr"` 151 | } 152 | 153 | type StatusPeer struct { 154 | ID ClientID `json:"id"` 155 | Role model.Role `json:"role"` 156 | Endpoint model.Endpoint `json:"endpoint"` 157 | } 158 | 159 | type StatusRelay struct { 160 | ID RelayID `json:"id"` 161 | Hostports []string `json:"hostport"` 162 | } 163 | -------------------------------------------------------------------------------- /relay/store.go: -------------------------------------------------------------------------------- 1 | package relay 2 | 3 | import ( 4 | "crypto/x509" 5 | "encoding/json" 6 | "path/filepath" 7 | 8 | "github.com/connet-dev/connet/certc" 9 | "github.com/connet-dev/connet/logc" 10 | "github.com/connet-dev/connet/model" 11 | ) 12 | 13 | type Stores interface { 14 | Config() (logc.KV[ConfigKey, ConfigValue], error) 15 | Clients() (logc.KV[ClientKey, ClientValue], error) 16 | Servers() (logc.KV[ServerKey, ServerValue], error) 17 | } 18 | 19 | func NewFileStores(dir string) Stores { 20 | return &fileStores{dir} 21 | } 22 | 23 | type fileStores struct { 24 | dir string 25 | } 26 | 27 | func (f *fileStores) Config() (logc.KV[ConfigKey, ConfigValue], error) { 28 | return logc.NewKV[ConfigKey, ConfigValue](filepath.Join(f.dir, "config")) 29 | } 30 | 31 | func (f *fileStores) Clients() (logc.KV[ClientKey, ClientValue], error) { 32 | return logc.NewKV[ClientKey, ClientValue](filepath.Join(f.dir, "clients")) 33 | } 34 | 35 | func (f *fileStores) Servers() (logc.KV[ServerKey, ServerValue], error) { 36 | return logc.NewKV[ServerKey, ServerValue](filepath.Join(f.dir, "servers")) 37 | } 38 | 39 | type ConfigKey string 40 | 41 | var ( 42 | configStatelessReset ConfigKey = "stateless-reset" 43 | configControlID ConfigKey = "control-id" 44 | configControlReconnect ConfigKey = "control-reconnect" 45 | configClientsStreamOffset ConfigKey = "clients-stream-offset" 46 | configClientsLogOffset ConfigKey = "clients-log-offset" 47 | ) 48 | 49 | type ConfigValue struct { 50 | Int64 int64 `json:"int64,omitempty"` 51 | String string `json:"string,omitempty"` 52 | Bytes []byte `json:"bytes,omitempty"` 53 | } 54 | 55 | type ClientKey struct { 56 | Endpoint model.Endpoint `json:"endpoint"` 57 | Role model.Role `json:"role"` 58 | Key model.Key `json:"key"` 59 | } 60 | 61 | type ClientValue struct { 62 | Cert *x509.Certificate `json:"cert"` 63 | } 64 | 65 | func (v ClientValue) MarshalJSON() ([]byte, error) { 66 | return certc.MarshalJSONCert(v.Cert) 67 | } 68 | 69 | func (v *ClientValue) UnmarshalJSON(b []byte) error { 70 | cert, err := certc.UnmarshalJSONCert(b) 71 | if err != nil { 72 | return err 73 | } 74 | 75 | *v = ClientValue{cert} 76 | return nil 77 | } 78 | 79 | type ServerKey struct { 80 | Endpoint model.Endpoint `json:"endpoint"` 81 | } 82 | 83 | type ServerValue struct { 84 | Name string `json:"name"` 85 | Cert *certc.Cert `json:"cert"` 86 | Clients map[serverClientKey]ClientValue `json:"clients"` 87 | } 88 | 89 | func (v ServerValue) MarshalJSON() ([]byte, error) { 90 | cert, key, err := v.Cert.EncodeToMemory() 91 | if err != nil { 92 | return nil, err 93 | } 94 | 95 | s := struct { 96 | Name string `json:"name"` 97 | Cert []byte `json:"cert"` 98 | CertKey []byte `json:"cert_key"` 99 | Clients []serverClientValue `json:"clients"` 100 | }{ 101 | Name: v.Name, 102 | Cert: cert, 103 | CertKey: key, 104 | } 105 | 106 | for k, v := range v.Clients { 107 | s.Clients = append(s.Clients, serverClientValue{ 108 | Role: k.Role, 109 | Value: v, 110 | }) 111 | } 112 | 113 | return json.Marshal(s) 114 | } 115 | 116 | func (v *ServerValue) UnmarshalJSON(b []byte) error { 117 | s := struct { 118 | Name string `json:"name"` 119 | Cert []byte `json:"cert"` 120 | CertKey []byte `json:"cert_key"` 121 | Clients []serverClientValue `json:"clients"` 122 | }{} 123 | if err := json.Unmarshal(b, &s); err != nil { 124 | return err 125 | } 126 | 127 | cert, err := certc.DecodeFromMemory(s.Cert, s.CertKey) 128 | if err != nil { 129 | return err 130 | } 131 | 132 | sv := ServerValue{ 133 | Name: s.Name, 134 | Cert: cert, 135 | Clients: map[serverClientKey]ClientValue{}, 136 | } 137 | 138 | for _, cl := range s.Clients { 139 | sv.Clients[serverClientKey{cl.Role, model.NewKey(cl.Value.Cert)}] = cl.Value 140 | } 141 | 142 | *v = sv 143 | return nil 144 | } 145 | 146 | type serverClientKey struct { 147 | Role model.Role `json:"role"` 148 | Key model.Key `json:"key"` 149 | } 150 | 151 | type serverClientValue struct { 152 | Role model.Role `json:"role"` 153 | Value ClientValue `json:"value"` 154 | } 155 | -------------------------------------------------------------------------------- /server/config.go: -------------------------------------------------------------------------------- 1 | package server 2 | 3 | import ( 4 | "fmt" 5 | "log/slog" 6 | "net" 7 | "os" 8 | 9 | "github.com/connet-dev/connet/control" 10 | "github.com/connet-dev/connet/model" 11 | "github.com/connet-dev/connet/relay" 12 | "github.com/connet-dev/connet/selfhosted" 13 | ) 14 | 15 | type serverConfig struct { 16 | clientsIngresses []control.Ingress 17 | clientsAuth control.ClientAuthenticator 18 | 19 | relayIngresses []relay.Ingress 20 | 21 | dir string 22 | logger *slog.Logger 23 | } 24 | 25 | func newServerConfig(opts []Option) (*serverConfig, error) { 26 | cfg := &serverConfig{ 27 | logger: slog.Default(), 28 | } 29 | for _, opt := range opts { 30 | if err := opt(cfg); err != nil { 31 | return nil, err 32 | } 33 | } 34 | 35 | if len(cfg.clientsIngresses) == 0 { 36 | addr, err := net.ResolveUDPAddr("udp", ":19190") 37 | if err != nil { 38 | return nil, fmt.Errorf("resolve clients address: %w", err) 39 | } 40 | if err := ClientsIngress(control.Ingress{Addr: addr})(cfg); err != nil { 41 | return nil, fmt.Errorf("default clients address: %w", err) 42 | } 43 | } 44 | 45 | for i, ingress := range cfg.clientsIngresses { 46 | if ingress.TLS == nil { 47 | return nil, fmt.Errorf("ingress at %d is missing tls config", i) 48 | } 49 | } 50 | 51 | if len(cfg.relayIngresses) == 0 { 52 | addr, err := net.ResolveUDPAddr("udp", ":19191") 53 | if err != nil { 54 | return nil, fmt.Errorf("resolve clients relay address: %w", err) 55 | } 56 | hps := []model.HostPort{{Host: "localhost", Port: 19191}} 57 | if err := RelayIngress(relay.Ingress{Addr: addr, Hostports: hps})(cfg); err != nil { 58 | return nil, fmt.Errorf("default clients relay address: %w", err) 59 | } 60 | } 61 | 62 | if cfg.dir == "" { 63 | if err := StoreDirFromEnv()(cfg); err != nil { 64 | return nil, fmt.Errorf("default store dir: %w", err) 65 | } 66 | cfg.logger.Info("using default store directory", "dir", cfg.dir) 67 | } 68 | 69 | return cfg, nil 70 | } 71 | 72 | type Option func(*serverConfig) error 73 | 74 | func ClientsIngress(icfg control.Ingress) Option { 75 | return func(cfg *serverConfig) error { 76 | cfg.clientsIngresses = append(cfg.clientsIngresses, icfg) 77 | 78 | return nil 79 | } 80 | } 81 | 82 | func ClientsTokens(tokens ...string) Option { 83 | return func(cfg *serverConfig) error { 84 | auths := make([]selfhosted.ClientAuthentication, len(tokens)) 85 | for i, t := range tokens { 86 | auths[i] = selfhosted.ClientAuthentication{Token: t} 87 | } 88 | 89 | cfg.clientsAuth = selfhosted.NewClientAuthenticator(auths...) 90 | 91 | return nil 92 | } 93 | } 94 | 95 | func ClientsAuthenticator(clientsAuth control.ClientAuthenticator) Option { 96 | return func(cfg *serverConfig) error { 97 | cfg.clientsAuth = clientsAuth 98 | 99 | return nil 100 | } 101 | } 102 | 103 | func RelayIngress(icfg relay.Ingress) Option { 104 | return func(cfg *serverConfig) error { 105 | cfg.relayIngresses = append(cfg.relayIngresses, icfg) 106 | 107 | return nil 108 | } 109 | } 110 | 111 | func StoreDir(dir string) Option { 112 | return func(cfg *serverConfig) error { 113 | cfg.dir = dir 114 | return nil 115 | } 116 | } 117 | 118 | func StoreDirFromEnv() Option { 119 | return func(cfg *serverConfig) error { 120 | stateDir, err := StoreDirFromEnvPrefixed("connet-server-") 121 | if err != nil { 122 | return err 123 | } 124 | cfg.dir = stateDir 125 | return nil 126 | } 127 | } 128 | 129 | func Logger(logger *slog.Logger) Option { 130 | return func(cfg *serverConfig) error { 131 | cfg.logger = logger 132 | return nil 133 | } 134 | } 135 | 136 | func StoreDirFromEnvPrefixed(prefix string) (string, error) { 137 | if stateDir := os.Getenv("CONNET_STATE_DIR"); stateDir != "" { 138 | // Support direct override if necessary, currently used in docker 139 | return stateDir, nil 140 | } else if stateDir := os.Getenv("STATE_DIRECTORY"); stateDir != "" { 141 | // Supports setting up the state directory via systemd. For reference 142 | // https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html#RuntimeDirectory= 143 | return stateDir, nil 144 | } 145 | tmpDir, err := os.MkdirTemp("", prefix) 146 | if err != nil { 147 | return "", fmt.Errorf("create /tmp dir: %w", err) 148 | } 149 | return tmpDir, nil 150 | } 151 | -------------------------------------------------------------------------------- /relay/server.go: -------------------------------------------------------------------------------- 1 | package relay 2 | 3 | import ( 4 | "context" 5 | "crypto/rand" 6 | "crypto/x509" 7 | "fmt" 8 | "io" 9 | "log/slog" 10 | "maps" 11 | "net" 12 | "slices" 13 | 14 | "github.com/connet-dev/connet/iterc" 15 | "github.com/connet-dev/connet/model" 16 | "github.com/connet-dev/connet/notify" 17 | "github.com/connet-dev/connet/statusc" 18 | "github.com/quic-go/quic-go" 19 | "golang.org/x/sync/errgroup" 20 | ) 21 | 22 | type Config struct { 23 | ControlAddr *net.UDPAddr 24 | ControlHost string 25 | ControlToken string 26 | ControlCAs *x509.CertPool 27 | 28 | Ingress []Ingress 29 | 30 | Stores Stores 31 | 32 | Logger *slog.Logger 33 | } 34 | 35 | func NewServer(cfg Config) (*Server, error) { 36 | if len(cfg.Ingress) == 0 { 37 | return nil, fmt.Errorf("relay server is missing ingresses") 38 | } 39 | 40 | configStore, err := cfg.Stores.Config() 41 | if err != nil { 42 | return nil, fmt.Errorf("relay stores: %w", err) 43 | } 44 | 45 | statelessResetVal, err := configStore.GetOrInit(configStatelessReset, func(ck ConfigKey) (ConfigValue, error) { 46 | var key quic.StatelessResetKey 47 | if _, err := io.ReadFull(rand.Reader, key[:]); err != nil { 48 | return ConfigValue{}, fmt.Errorf("generate rand: %w", err) 49 | } 50 | return ConfigValue{Bytes: key[:]}, nil 51 | }) 52 | if err != nil { 53 | return nil, fmt.Errorf("relay stateless reset key: %w", err) 54 | } 55 | var statelessResetKey quic.StatelessResetKey 56 | copy(statelessResetKey[:], statelessResetVal.Bytes) 57 | 58 | control, err := newControlClient(cfg, configStore) 59 | if err != nil { 60 | return nil, fmt.Errorf("relay control client: %w", err) 61 | } 62 | 63 | clients := newClientsServer(cfg, control.tlsAuthenticate, control.authenticate) 64 | 65 | return &Server{ 66 | ingress: cfg.Ingress, 67 | statelessResetKey: &statelessResetKey, 68 | 69 | control: control, 70 | clients: clients, 71 | }, nil 72 | } 73 | 74 | type Server struct { 75 | ingress []Ingress 76 | statelessResetKey *quic.StatelessResetKey 77 | 78 | control *controlClient 79 | clients *clientsServer 80 | } 81 | 82 | func (s *Server) Run(ctx context.Context) error { 83 | g, ctx := errgroup.WithContext(ctx) 84 | 85 | transports := notify.NewEmpty[[]*quic.Transport]() 86 | 87 | for _, ingress := range s.ingress { 88 | g.Go(func() error { 89 | return s.clients.run(ctx, clientsServerCfg{ 90 | ingress: ingress, 91 | statelessResetKey: s.statelessResetKey, 92 | addedTransport: func(t *quic.Transport) { 93 | notify.SliceAppend(transports, t) 94 | }, 95 | removeTransport: func(t *quic.Transport) { 96 | notify.SliceRemove(transports, t) 97 | }, 98 | }) 99 | }) 100 | } 101 | 102 | g.Go(func() error { 103 | return s.control.run(ctx, func(ctx context.Context) ([]*quic.Transport, error) { 104 | t, _, err := transports.GetAny(ctx) 105 | return t, err 106 | }) 107 | }) 108 | 109 | return g.Wait() 110 | } 111 | 112 | type Status struct { 113 | Status statusc.Status `json:"status"` 114 | Hostports []string `json:"hostports"` 115 | ControlServerAddr string `json:"control_server_addr"` 116 | ControlServerID string `json:"control_server_id"` 117 | Endpoints []model.Endpoint `json:"endpoints"` 118 | } 119 | 120 | func (s *Server) Status(ctx context.Context) (Status, error) { 121 | stat := s.control.connStatus.Load().(statusc.Status) 122 | 123 | controlID, err := s.getControlID() 124 | if err != nil { 125 | return Status{}, err 126 | } 127 | 128 | eps := s.getEndpoints() 129 | 130 | return Status{ 131 | Status: stat, 132 | Hostports: iterc.MapSliceStrings(s.control.hostports), 133 | ControlServerAddr: s.control.controlAddr.String(), 134 | ControlServerID: controlID, 135 | Endpoints: eps, 136 | }, nil 137 | } 138 | 139 | func (s *Server) getControlID() (string, error) { 140 | controlIDConfig, err := s.control.config.GetOrDefault(configControlID, ConfigValue{}) 141 | if err != nil { 142 | return "", err 143 | } 144 | return controlIDConfig.String, nil 145 | } 146 | 147 | func (s *Server) getEndpoints() []model.Endpoint { 148 | s.clients.endpointsMu.RLock() 149 | defer s.clients.endpointsMu.RUnlock() 150 | 151 | return slices.Collect(maps.Keys(s.clients.endpoints)) 152 | } 153 | -------------------------------------------------------------------------------- /relay/ingress.go: -------------------------------------------------------------------------------- 1 | package relay 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "strconv" 7 | "strings" 8 | 9 | "github.com/connet-dev/connet/model" 10 | "github.com/connet-dev/connet/restr" 11 | ) 12 | 13 | type Ingress struct { 14 | Addr *net.UDPAddr 15 | Hostports []model.HostPort 16 | Restr restr.IP 17 | } 18 | 19 | type IngressBuilder struct { 20 | ingress Ingress 21 | err error 22 | } 23 | 24 | func NewIngressBuilder() *IngressBuilder { return &IngressBuilder{} } 25 | 26 | func (b *IngressBuilder) WithAddr(addr *net.UDPAddr) *IngressBuilder { 27 | if b.err != nil { 28 | return b 29 | } 30 | b.ingress.Addr = addr 31 | return b 32 | } 33 | 34 | func (b *IngressBuilder) WithAddrFrom(addrStr string) *IngressBuilder { 35 | if b.err != nil { 36 | return b 37 | } 38 | 39 | addr, err := net.ResolveUDPAddr("udp", addrStr) 40 | if err != nil { 41 | b.err = fmt.Errorf("resolve udp address: %w", err) 42 | return b 43 | } 44 | return b.WithAddr(addr) 45 | } 46 | 47 | func (b *IngressBuilder) WithHostports(hps []model.HostPort) *IngressBuilder { 48 | if b.err != nil { 49 | return b 50 | } 51 | b.ingress.Hostports = hps 52 | return b 53 | } 54 | 55 | func (b *IngressBuilder) WithHostport(hp model.HostPort) *IngressBuilder { 56 | if b.err != nil { 57 | return b 58 | } 59 | b.ingress.Hostports = append(b.ingress.Hostports, hp) 60 | return b 61 | } 62 | 63 | func (b *IngressBuilder) WithHostportFrom(hostport string) *IngressBuilder { 64 | if b.err != nil { 65 | return b 66 | } 67 | 68 | if strings.HasPrefix(hostport, "[") { 69 | closeBracket := strings.LastIndex(hostport, "]") 70 | if closeBracket < 0 { 71 | b.err = fmt.Errorf("cannot parse hostport, missing ]") 72 | return b 73 | } 74 | colonPort := hostport[closeBracket+1:] 75 | if len(colonPort) > 0 { 76 | if colonPort[0] != ':' { 77 | b.err = fmt.Errorf("cannot parse hostport, missing ':'") 78 | return b 79 | } 80 | portStr := hostport[1:] 81 | if len(portStr) == 0 { 82 | b.err = fmt.Errorf("cannot parse hostport, missing port") 83 | return b 84 | } 85 | port, err := strconv.ParseInt(portStr, 10, 16) 86 | if err != nil { 87 | b.err = fmt.Errorf("cannot parse port: %w", err) 88 | return b 89 | } 90 | return b.WithHostport(model.HostPort{Host: hostport[:closeBracket+1], Port: uint16(port)}) 91 | } 92 | } else if colonIndex := strings.LastIndex(hostport, ":"); colonIndex != -1 { 93 | portStr := hostport[colonIndex+1:] 94 | if len(portStr) == 0 { 95 | b.err = fmt.Errorf("cannot parse hostport, missing port") 96 | return b 97 | } 98 | port, err := strconv.ParseInt(portStr, 10, 16) 99 | if err != nil { 100 | b.err = fmt.Errorf("cannot parse port: %w", err) 101 | return b 102 | } 103 | return b.WithHostport(model.HostPort{Host: hostport[:colonIndex], Port: uint16(port)}) 104 | } 105 | 106 | return b.WithHostport(model.HostPort{Host: hostport}) 107 | } 108 | 109 | func (b *IngressBuilder) WithRestr(iprestr restr.IP) *IngressBuilder { 110 | if b.err != nil { 111 | return b 112 | } 113 | 114 | b.ingress.Restr = iprestr 115 | return b 116 | } 117 | 118 | func (b *IngressBuilder) WithRestrFrom(allows []string, denies []string) *IngressBuilder { 119 | if b.err != nil { 120 | return b 121 | } 122 | 123 | iprestr, err := restr.ParseIP(allows, denies) 124 | if err != nil { 125 | b.err = fmt.Errorf("parse restrictions: %w", err) 126 | return b 127 | } 128 | return b.WithRestr(iprestr) 129 | } 130 | 131 | func (b *IngressBuilder) Error() error { 132 | return b.err 133 | } 134 | 135 | func (b *IngressBuilder) Ingress() (Ingress, error) { 136 | if b.err != nil { 137 | return b.ingress, b.err 138 | } 139 | 140 | for i, hp := range b.ingress.Hostports { 141 | if hp.Host == "" { 142 | switch { 143 | case b.ingress.Addr == nil: 144 | hp.Host = "localhost" 145 | case len(b.ingress.Addr.IP) == 0: 146 | hp.Host = "localhost" 147 | default: 148 | hp.Host = b.ingress.Addr.IP.String() 149 | } 150 | } 151 | if hp.Port == 0 { 152 | switch { 153 | case b.ingress.Addr == nil: 154 | hp.Port = 19191 155 | case b.ingress.Addr.Port == 0: 156 | hp.Port = 19191 // TODO maybe an error, it might be a random port 157 | default: 158 | hp.Port = uint16(b.ingress.Addr.Port) 159 | } 160 | } 161 | 162 | b.ingress.Hostports[i] = hp 163 | } 164 | 165 | return b.ingress, b.err 166 | } 167 | -------------------------------------------------------------------------------- /cryptoc/stream.go: -------------------------------------------------------------------------------- 1 | package cryptoc 2 | 3 | import ( 4 | "crypto/cipher" 5 | "encoding/binary" 6 | "io" 7 | "net" 8 | "slices" 9 | "sync" 10 | "sync/atomic" 11 | "time" 12 | ) 13 | 14 | type asymStream struct { 15 | stream io.ReadWriter 16 | reader cipher.AEAD 17 | writer cipher.AEAD 18 | 19 | readMu sync.Mutex 20 | readBuffLen []byte 21 | readBuff []byte 22 | readNonce []byte 23 | 24 | readPlainBuff []byte 25 | readPlainBegin int 26 | readPlainEnd int 27 | 28 | writeMu sync.Mutex 29 | writeBuff []byte 30 | writeNonce []byte 31 | writePlainMax int 32 | 33 | closed atomic.Bool 34 | } 35 | 36 | const maxBuff = 65535 37 | 38 | func NewStream(stream io.ReadWriter, reader cipher.AEAD, writer cipher.AEAD) net.Conn { 39 | return &asymStream{ 40 | stream: stream, 41 | reader: reader, 42 | writer: writer, 43 | 44 | readBuffLen: make([]byte, 2), 45 | readBuff: make([]byte, maxBuff), 46 | readNonce: make([]byte, reader.NonceSize()), 47 | 48 | readPlainBuff: make([]byte, maxBuff-reader.Overhead()), 49 | readPlainBegin: 0, 50 | readPlainEnd: 0, 51 | 52 | writeBuff: make([]byte, maxBuff), 53 | writeNonce: make([]byte, writer.NonceSize()), 54 | writePlainMax: maxBuff - writer.Overhead() - 2, 55 | } 56 | } 57 | 58 | func (s *asymStream) Read(p []byte) (int, error) { 59 | if s.closed.Load() { 60 | return 0, io.ErrClosedPipe 61 | } 62 | 63 | s.readMu.Lock() 64 | defer s.readMu.Unlock() 65 | 66 | var err error 67 | if s.readPlainBegin >= s.readPlainEnd { 68 | if _, err := io.ReadFull(s.stream, s.readBuffLen); err != nil { 69 | return 0, err 70 | } 71 | 72 | readLen := int(binary.BigEndian.Uint16(s.readBuffLen)) 73 | if n, err := io.ReadFull(s.stream, s.readBuff[:readLen]); err != nil { 74 | return 0, err 75 | } else { 76 | s.readBuff = s.readBuff[:n] 77 | } 78 | 79 | s.readPlainBuff = s.readPlainBuff[:cap(s.readPlainBuff)] 80 | s.readPlainBuff, err = s.reader.Open(s.readPlainBuff[:0], s.readNonce, s.readBuff, nil) 81 | if err != nil { 82 | return 0, err 83 | } 84 | 85 | incrementNonce(s.readNonce) 86 | 87 | s.readPlainBegin = 0 88 | s.readPlainEnd = len(s.readPlainBuff) 89 | } 90 | 91 | n := copy(p, s.readPlainBuff[s.readPlainBegin:s.readPlainEnd]) 92 | s.readPlainBegin += n 93 | 94 | return n, nil 95 | } 96 | 97 | func (s *asymStream) Write(p []byte) (int, error) { 98 | if s.closed.Load() { 99 | return 0, io.ErrClosedPipe 100 | } 101 | 102 | s.writeMu.Lock() 103 | defer s.writeMu.Unlock() 104 | 105 | var written int 106 | for chunk := range slices.Chunk(p, s.writePlainMax) { 107 | s.writeBuff = s.writeBuff[:cap(s.writeBuff)] 108 | 109 | out := s.writer.Seal(s.writeBuff[2:2], s.writeNonce, chunk, nil) 110 | s.writeBuff = s.writeBuff[:2+len(out)] 111 | 112 | incrementNonce(s.writeNonce) 113 | 114 | binary.BigEndian.PutUint16(s.writeBuff, uint16(len(out))) 115 | if _, err := s.stream.Write(s.writeBuff); err != nil { 116 | return written, err 117 | } 118 | 119 | written += len(chunk) 120 | } 121 | 122 | return written, nil 123 | } 124 | 125 | func (s *asymStream) Close() error { 126 | if s.closed.CompareAndSwap(false, true) { 127 | if stream, ok := s.stream.(io.Closer); ok { 128 | return stream.Close() 129 | } 130 | } 131 | 132 | return nil 133 | } 134 | 135 | func (s *asymStream) LocalAddr() net.Addr { 136 | if stream, ok := s.stream.(interface{ LocalAddr() net.Addr }); ok { 137 | return stream.LocalAddr() 138 | } 139 | return nil 140 | } 141 | 142 | func (s *asymStream) RemoteAddr() net.Addr { 143 | if stream, ok := s.stream.(interface{ RemoteAddr() net.Addr }); ok { 144 | return stream.RemoteAddr() 145 | } 146 | return nil 147 | } 148 | 149 | func (s *asymStream) SetDeadline(t time.Time) error { 150 | if stream, ok := s.stream.(interface{ SetDeadline(t time.Time) error }); ok { 151 | return stream.SetDeadline(t) 152 | } 153 | return nil 154 | } 155 | 156 | func (s *asymStream) SetReadDeadline(t time.Time) error { 157 | if stream, ok := s.stream.(interface{ SetReadDeadline(t time.Time) error }); ok { 158 | return stream.SetReadDeadline(t) 159 | } 160 | return nil 161 | } 162 | 163 | func (s *asymStream) SetWriteDeadline(t time.Time) error { 164 | if stream, ok := s.stream.(interface{ SetWriteDeadline(t time.Time) error }); ok { 165 | return stream.SetWriteDeadline(t) 166 | } 167 | return nil 168 | } 169 | 170 | func incrementNonce(nonce []byte) { 171 | for i := len(nonce) - 1; i >= 0; i-- { 172 | nonce[i]++ 173 | if nonce[i] > 0 { 174 | break 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /relay.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "errors" 7 | "fmt" 8 | "log/slog" 9 | "net" 10 | "sync/atomic" 11 | "time" 12 | 13 | "github.com/connet-dev/connet/model" 14 | "github.com/connet-dev/connet/proto" 15 | "github.com/connet-dev/connet/proto/pbconnect" 16 | "github.com/connet-dev/connet/proto/pberror" 17 | "github.com/connet-dev/connet/quicc" 18 | "github.com/connet-dev/connet/reliable" 19 | "github.com/connet-dev/connet/slogc" 20 | "github.com/quic-go/quic-go" 21 | "golang.org/x/sync/errgroup" 22 | ) 23 | 24 | type relayID string 25 | 26 | type relay struct { 27 | local *peer 28 | 29 | serverID relayID 30 | serverHostports []model.HostPort 31 | serverConf atomic.Pointer[serverTLSConfig] 32 | 33 | closer chan struct{} 34 | 35 | logger *slog.Logger 36 | } 37 | 38 | func newRelay(local *peer, id relayID, hps []model.HostPort, serverConf *serverTLSConfig, logger *slog.Logger) *relay { 39 | r := &relay{ 40 | local: local, 41 | serverID: id, 42 | serverHostports: hps, 43 | closer: make(chan struct{}), 44 | logger: logger.With("relay", id, "addrs", hps), 45 | } 46 | r.serverConf.Store(serverConf) 47 | return r 48 | } 49 | 50 | func (r *relay) run(ctx context.Context) { 51 | g, ctx := errgroup.WithContext(ctx) 52 | 53 | g.Go(func() error { return r.runConn(ctx) }) 54 | g.Go(func() error { 55 | <-r.closer 56 | return errPeeringStop 57 | }) 58 | 59 | if err := g.Wait(); err != nil { 60 | r.logger.Debug("error while running relaying", "err", err) 61 | } 62 | } 63 | 64 | func (r *relay) runConn(ctx context.Context) error { 65 | boff := reliable.MinBackoff 66 | for { 67 | conn, err := r.connectAny(ctx) 68 | if err != nil { 69 | r.logger.Debug("could not connect relay", "err", err) 70 | if errors.Is(err, context.Canceled) { 71 | return err 72 | } 73 | 74 | select { 75 | case <-ctx.Done(): 76 | return ctx.Err() 77 | case <-time.After(boff): 78 | boff = reliable.NextBackoff(boff) 79 | } 80 | continue 81 | } 82 | boff = reliable.MinBackoff 83 | 84 | if err := r.keepalive(ctx, conn); err != nil { 85 | r.logger.Debug("disconnected relay", "err", err) 86 | } 87 | } 88 | } 89 | 90 | func (r *relay) connectAny(ctx context.Context) (*quic.Conn, error) { 91 | for _, hp := range r.serverHostports { 92 | if conn, err := r.connect(ctx, hp); err != nil { 93 | r.logger.Debug("cannot connet relay", "hostport", hp, "err", err) 94 | } else { 95 | return conn, nil 96 | } 97 | } 98 | return nil, fmt.Errorf("cannot connect to relay: %s", r.serverID) 99 | } 100 | 101 | func (r *relay) connect(ctx context.Context, hp model.HostPort) (*quic.Conn, error) { 102 | addr, err := net.ResolveUDPAddr("udp", hp.String()) 103 | if err != nil { 104 | return nil, err 105 | } 106 | 107 | cfg := r.serverConf.Load() 108 | r.logger.Debug("dialing relay", "addr", addr, "server", cfg.name, "cert", cfg.key) 109 | conn, err := r.local.direct.transport.Dial(ctx, addr, &tls.Config{ 110 | Certificates: []tls.Certificate{r.local.clientCert}, 111 | RootCAs: cfg.cas, 112 | ServerName: cfg.name, 113 | NextProtos: model.ConnectRelayNextProtos, 114 | }, quicc.StdConfig) 115 | if err != nil { 116 | return nil, err 117 | } 118 | 119 | if err := r.check(ctx, conn); err != nil { 120 | cerr := conn.CloseWithError(quic.ApplicationErrorCode(pberror.Code_ConnectionCheckFailed), "connection check failed") 121 | return nil, errors.Join(err, cerr) 122 | } 123 | return conn, nil 124 | } 125 | 126 | func (r *relay) check(ctx context.Context, conn *quic.Conn) error { 127 | stream, err := conn.OpenStreamSync(ctx) 128 | if err != nil { 129 | return err 130 | } 131 | defer func() { 132 | if err := stream.Close(); err != nil { 133 | slogc.Fine(r.logger, "error closing check stream", "err", err) 134 | } 135 | }() 136 | 137 | if err := proto.Write(stream, &pbconnect.Request{}); err != nil { 138 | return err 139 | } 140 | if _, err := pbconnect.ReadResponse(stream); err != nil { 141 | return err 142 | } 143 | 144 | return nil 145 | } 146 | 147 | func (r *relay) keepalive(ctx context.Context, conn *quic.Conn) error { 148 | defer func() { 149 | if err := conn.CloseWithError(quic.ApplicationErrorCode(pberror.Code_RelayKeepaliveClosed), "keepalive closed"); err != nil { 150 | slogc.Fine(r.logger, "error closing connection", "err", err) 151 | } 152 | }() 153 | 154 | r.local.addRelayConn(r.serverID, conn) 155 | defer r.local.removeRelayConn(r.serverID) 156 | 157 | quicc.LogRTTStats(conn, r.logger) 158 | for { 159 | select { 160 | case <-ctx.Done(): 161 | return context.Cause(ctx) 162 | case <-conn.Context().Done(): 163 | return context.Cause(conn.Context()) 164 | case <-time.After(30 * time.Second): 165 | quicc.LogRTTStats(conn, r.logger) 166 | } 167 | } 168 | } 169 | 170 | func (r *relay) stop() { 171 | close(r.closer) 172 | } 173 | -------------------------------------------------------------------------------- /direct.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "crypto/x509" 7 | "fmt" 8 | "log/slog" 9 | "sync" 10 | "sync/atomic" 11 | 12 | "github.com/connet-dev/connet/model" 13 | "github.com/connet-dev/connet/proto/pberror" 14 | "github.com/connet-dev/connet/quicc" 15 | "github.com/connet-dev/connet/slogc" 16 | "github.com/quic-go/quic-go" 17 | ) 18 | 19 | type directServer struct { 20 | transport *quic.Transport 21 | logger *slog.Logger 22 | 23 | servers map[string]*vServer 24 | serversMu sync.RWMutex 25 | } 26 | 27 | func newDirectServer(transport *quic.Transport, logger *slog.Logger) (*directServer, error) { 28 | return &directServer{ 29 | transport: transport, 30 | logger: logger.With("component", "direct-server"), 31 | 32 | servers: map[string]*vServer{}, 33 | }, nil 34 | } 35 | 36 | type vServer struct { 37 | serverName string 38 | serverCert tls.Certificate 39 | clients map[model.Key]*vClient 40 | clientCA atomic.Pointer[x509.CertPool] 41 | mu sync.RWMutex 42 | } 43 | 44 | type vClient struct { 45 | cert *x509.Certificate 46 | ch chan *quic.Conn 47 | } 48 | 49 | func (s *vServer) dequeue(key model.Key, cert *x509.Certificate) *vClient { 50 | s.mu.Lock() 51 | defer s.mu.Unlock() 52 | 53 | if exp, ok := s.clients[key]; ok && exp.cert.Equal(cert) { 54 | delete(s.clients, key) 55 | return exp 56 | } 57 | 58 | return nil 59 | } 60 | 61 | func (s *vServer) updateClientCA() { 62 | s.mu.RLock() 63 | defer s.mu.RUnlock() 64 | 65 | clientCA := x509.NewCertPool() 66 | for _, exp := range s.clients { 67 | clientCA.AddCert(exp.cert) 68 | } 69 | s.clientCA.Store(clientCA) 70 | } 71 | 72 | func (s *directServer) addServerCert(cert tls.Certificate) { 73 | serverName := cert.Leaf.DNSNames[0] 74 | 75 | s.serversMu.Lock() 76 | defer s.serversMu.Unlock() 77 | 78 | s.logger.Debug("add server cert", "server", serverName, "cert", model.NewKey(cert.Leaf)) 79 | s.servers[serverName] = &vServer{ 80 | serverName: serverName, 81 | serverCert: cert, 82 | clients: map[model.Key]*vClient{}, 83 | } 84 | } 85 | 86 | func (s *directServer) getServer(serverName string) *vServer { 87 | s.serversMu.RLock() 88 | defer s.serversMu.RUnlock() 89 | 90 | return s.servers[serverName] 91 | } 92 | 93 | func (s *directServer) expect(serverCert tls.Certificate, cert *x509.Certificate) (chan *quic.Conn, func()) { 94 | key := model.NewKey(cert) 95 | srv := s.getServer(serverCert.Leaf.DNSNames[0]) 96 | 97 | defer srv.updateClientCA() 98 | 99 | srv.mu.Lock() 100 | defer srv.mu.Unlock() 101 | 102 | s.logger.Debug("expect client", "server", srv.serverName, "cert", key) 103 | cl := &vClient{cert: cert, ch: make(chan *quic.Conn)} 104 | srv.clients[key] = cl 105 | return cl.ch, func() { 106 | close(cl.ch) 107 | 108 | srv.mu.Lock() 109 | defer srv.mu.Unlock() 110 | 111 | if exp, ok := srv.clients[key]; ok && exp == cl { 112 | s.logger.Debug("unexpect client", "server", srv.serverName, "cert", key) 113 | delete(srv.clients, key) 114 | } 115 | } 116 | } 117 | 118 | func (s *directServer) Run(ctx context.Context) error { 119 | tlsConf := &tls.Config{ 120 | ClientAuth: tls.RequireAndVerifyClientCert, 121 | NextProtos: model.ConnectDirectNextProtos, 122 | } 123 | tlsConf.GetConfigForClient = func(chi *tls.ClientHelloInfo) (*tls.Config, error) { 124 | srv := s.getServer(chi.ServerName) 125 | if srv == nil { 126 | return nil, fmt.Errorf("server not found: %s", chi.ServerName) 127 | } 128 | conf := tlsConf.Clone() 129 | conf.Certificates = []tls.Certificate{srv.serverCert} 130 | conf.ClientCAs = srv.clientCA.Load() 131 | return conf, nil 132 | } 133 | 134 | l, err := s.transport.Listen(tlsConf, quicc.StdConfig) 135 | if err != nil { 136 | return err 137 | } 138 | defer func() { 139 | if err := l.Close(); err != nil { 140 | slogc.Fine(s.logger, "close listener error", "err", err) 141 | } 142 | }() 143 | 144 | s.logger.Debug("listening for conns") 145 | for { 146 | conn, err := l.Accept(ctx) 147 | if err != nil { 148 | s.logger.Debug("accept error", "err", err) 149 | return fmt.Errorf("accept: %w", err) 150 | } 151 | go s.runConn(conn) 152 | } 153 | } 154 | 155 | func (s *directServer) runConn(conn *quic.Conn) { 156 | srv := s.getServer(conn.ConnectionState().TLS.ServerName) 157 | if srv == nil { 158 | if err := conn.CloseWithError(quic.ApplicationErrorCode(pberror.Code_AuthenticationFailed), "unknown server"); err != nil { 159 | slogc.Fine(s.logger, "error closing connection", "err", err) 160 | } 161 | return 162 | } 163 | 164 | cert := conn.ConnectionState().TLS.PeerCertificates[0] 165 | key := model.NewKey(cert) 166 | s.logger.Debug("accepted conn", "server", srv.serverName, "cert", key, "remote", conn.RemoteAddr()) 167 | 168 | exp := srv.dequeue(key, cert) 169 | if exp == nil { 170 | if err := conn.CloseWithError(quic.ApplicationErrorCode(pberror.Code_AuthenticationFailed), "unknown client"); err != nil { 171 | slogc.Fine(s.logger, "error closing connection", "err", err) 172 | } 173 | return 174 | } 175 | 176 | s.logger.Debug("accept client", "server", srv.serverName, "cert", key) 177 | exp.ch <- conn 178 | close(exp.ch) 179 | 180 | srv.updateClientCA() 181 | } 182 | -------------------------------------------------------------------------------- /logc/log.go: -------------------------------------------------------------------------------- 1 | package logc 2 | 3 | import ( 4 | "cmp" 5 | "context" 6 | "errors" 7 | "fmt" 8 | "maps" 9 | "slices" 10 | "time" 11 | 12 | "github.com/connet-dev/connet/reliable" 13 | "github.com/klev-dev/klevdb" 14 | "github.com/klev-dev/klevdb/compact" 15 | ) 16 | 17 | const ( 18 | OffsetInvalid = klevdb.OffsetInvalid 19 | OffsetOldest = klevdb.OffsetOldest 20 | OffsetNewest = klevdb.OffsetNewest 21 | ) 22 | 23 | var ErrNotFound = klevdb.ErrNotFound 24 | 25 | type Message[K comparable, V any] struct { 26 | Offset int64 27 | Key K 28 | Value V 29 | Delete bool 30 | } 31 | 32 | type KV[K comparable, V any] interface { 33 | Put(k K, v V) error 34 | Del(k K) error 35 | 36 | Get(k K) (V, error) 37 | GetOrDefault(k K, v V) (V, error) 38 | GetOrInit(k K, fn func(K) (V, error)) (V, error) 39 | 40 | Consume(ctx context.Context, offset int64) ([]Message[K, V], int64, error) 41 | Snapshot() ([]Message[K, V], int64, error) // TODO this could possible return too much data 42 | 43 | Compact(ctx context.Context) error 44 | Close() error 45 | } 46 | 47 | func NewKV[K comparable, V any](dir string) (KV[K, V], error) { 48 | log, err := klevdb.OpenTBlocking(dir, klevdb.Options{ 49 | CreateDirs: true, 50 | KeyIndex: true, 51 | AutoSync: true, 52 | Check: true, 53 | }, klevdb.JsonCodec[K]{}, klevdb.JsonCodec[V]{}) 54 | if err != nil { 55 | return nil, fmt.Errorf("log open: %w", err) 56 | } 57 | return &kv[K, V]{log}, nil 58 | } 59 | 60 | type kv[K comparable, V any] struct { 61 | log klevdb.TBlockingLog[K, V] 62 | } 63 | 64 | func (l *kv[K, V]) Put(k K, v V) error { 65 | _, err := l.log.Publish([]klevdb.TMessage[K, V]{{ 66 | Key: k, 67 | Value: v, 68 | }}) 69 | return err 70 | } 71 | 72 | func (l *kv[K, V]) Del(k K) error { 73 | _, err := l.log.Publish([]klevdb.TMessage[K, V]{{ 74 | Key: k, 75 | ValueEmpty: true, 76 | }}) 77 | return err 78 | } 79 | 80 | func (l *kv[K, V]) Get(k K) (V, error) { 81 | msg, err := l.log.GetByKey(k, false) 82 | if err != nil { 83 | var v V 84 | return v, err 85 | } 86 | if msg.ValueEmpty { 87 | var v V 88 | return v, fmt.Errorf("key not found: %w", ErrNotFound) 89 | } 90 | return msg.Value, nil 91 | } 92 | 93 | func (l *kv[K, V]) GetOrDefault(k K, dv V) (V, error) { 94 | switch v, err := l.Get(k); { 95 | case err == nil: 96 | return v, nil 97 | case errors.Is(err, ErrNotFound): 98 | return dv, nil 99 | default: 100 | return v, err 101 | } 102 | } 103 | 104 | func (l *kv[K, V]) GetOrInit(k K, fn func(K) (V, error)) (V, error) { 105 | switch v, err := l.Get(k); { 106 | case err == nil: 107 | return v, nil 108 | case errors.Is(err, ErrNotFound): 109 | nv, err := fn(k) 110 | if err != nil { 111 | return v, err 112 | } 113 | if err := l.Put(k, nv); err != nil { 114 | return v, err 115 | } 116 | return nv, nil 117 | default: 118 | return v, err 119 | } 120 | } 121 | 122 | func (l *kv[K, V]) Consume(ctx context.Context, offset int64) ([]Message[K, V], int64, error) { 123 | nextOffset, msgs, err := l.log.ConsumeBlocking(ctx, offset, 32) 124 | if err != nil { 125 | return nil, OffsetInvalid, err 126 | } 127 | nmsgs := make([]Message[K, V], len(msgs)) 128 | for i, msg := range msgs { 129 | nmsgs[i] = Message[K, V]{ 130 | Offset: msg.Offset, 131 | Key: msg.Key, 132 | Value: msg.Value, 133 | Delete: msg.ValueEmpty, 134 | } 135 | } 136 | return nmsgs, nextOffset, nil 137 | } 138 | 139 | func (l *kv[K, V]) Snapshot() ([]Message[K, V], int64, error) { 140 | maxOffset, err := l.log.NextOffset() 141 | if err != nil { 142 | return nil, OffsetInvalid, err 143 | } 144 | 145 | sum := map[K]Message[K, V]{} 146 | for offset := OffsetOldest; offset < maxOffset; { 147 | nextOffset, msgs, err := l.log.Consume(offset, 32) 148 | if err != nil { 149 | return nil, OffsetInvalid, err 150 | } 151 | offset = nextOffset 152 | 153 | for _, msg := range msgs { 154 | if msg.ValueEmpty { 155 | delete(sum, msg.Key) 156 | } else { 157 | sum[msg.Key] = Message[K, V]{ 158 | Offset: msg.Offset, 159 | Key: msg.Key, 160 | Value: msg.Value, 161 | } 162 | } 163 | } 164 | } 165 | 166 | return slices.SortedFunc(maps.Values(sum), func(l, r Message[K, V]) int { 167 | return cmp.Compare(l.Offset, r.Offset) 168 | }), maxOffset, nil 169 | } 170 | 171 | func (l *kv[K, V]) Compact(ctx context.Context) error { 172 | updatesBefore := time.Now().Add(-6 * time.Hour) 173 | if _, _, err := compact.UpdatesMulti(ctx, l.log.Raw(), updatesBefore, compactBackoff); err != nil { 174 | return err 175 | } 176 | deletesBefore := time.Now().Add(-12 * time.Hour) 177 | if _, _, err := compact.DeletesMulti(ctx, l.log.Raw(), deletesBefore, compactBackoff); err != nil { 178 | return err 179 | } 180 | return l.log.GC(0) 181 | } 182 | 183 | func (l *kv[K, V]) Close() error { 184 | return l.log.Close() 185 | } 186 | 187 | func compactBackoff(ctx context.Context) error { 188 | return reliable.WaitDeline(ctx, time.Second) 189 | } 190 | 191 | func ScheduleCompact[K comparable, V any](l KV[K, V]) reliable.RunFn { 192 | return reliable.ScheduleDelayed(5*time.Minute, time.Hour, l.Compact) 193 | } 194 | 195 | func ScheduleCompactAcc[K comparable, V any](l KV[K, V]) reliable.RunFn { 196 | return reliable.ScheduleDelayed(1*time.Minute, time.Hour, l.Compact) 197 | } 198 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw= 5 | github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0= 6 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 7 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 8 | github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= 9 | github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= 10 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 11 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 12 | github.com/jackpal/gateway v1.1.1 h1:UXXXkJGIHFsStms9ZBgGpoaFEJP7oJtFn5vplIT68E8= 13 | github.com/jackpal/gateway v1.1.1/go.mod h1:Tl1vZVtUaXx5j6P5HFmv45alhEi4yHHLfT4PRbB7eyw= 14 | github.com/klev-dev/klevdb v0.10.1 h1:52o6fHQwu/XA1b/p3IKvTCTuJ9+3FX2v/b8iyE5FCps= 15 | github.com/klev-dev/klevdb v0.10.1/go.mod h1:r3Y2pB4BNqD4ZOCBH2qe0JqCctvN7HcNCagn36qugAM= 16 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= 17 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= 18 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 19 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 20 | github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= 21 | github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= 22 | github.com/pires/go-proxyproto v0.8.1 h1:9KEixbdJfhrbtjpz/ZwCdWDD2Xem0NZ38qMYaASJgp0= 23 | github.com/pires/go-proxyproto v0.8.1/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU= 24 | github.com/plar/go-adaptive-radix-tree/v2 v2.0.4 h1:Viv/uI+PUSY+nXF6uNUYeVjw/6grZG+ngVGGFixjX+U= 25 | github.com/plar/go-adaptive-radix-tree/v2 v2.0.4/go.mod h1:8yf9K81YK94H4gKh/K3hCBeC2s4JA/PYgqMkkOadwvk= 26 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 27 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 28 | github.com/quic-go/quic-go v0.57.1 h1:25KAAR9QR8KZrCZRThWMKVAwGoiHIrNbT72ULHTuI10= 29 | github.com/quic-go/quic-go v0.57.1/go.mod h1:ly4QBAjHA2VhdnxhojRsCUOeJwKYg+taDlos92xb1+s= 30 | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= 31 | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= 32 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 33 | github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= 34 | github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= 35 | github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 36 | github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= 37 | github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 38 | github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= 39 | github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= 40 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= 41 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= 42 | go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= 43 | go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= 44 | go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= 45 | golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= 46 | golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= 47 | golang.org/x/exp v0.0.0-20251125195548-87e1e737ad39 h1:DHNhtq3sNNzrvduZZIiFyXWOL9IWaDPHqTnLJp+rCBY= 48 | golang.org/x/exp v0.0.0-20251125195548-87e1e737ad39/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0= 49 | golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= 50 | golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= 51 | golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I= 52 | golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= 53 | golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= 54 | golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 55 | golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= 56 | golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= 57 | google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= 58 | google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= 59 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 60 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 61 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 62 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 63 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 64 | -------------------------------------------------------------------------------- /nix/module.nix: -------------------------------------------------------------------------------- 1 | { role, ports, hasCerts ? false, hasStorage ? false, config, lib, pkgs, ... }: 2 | let 3 | cfg = config.services."connet-${role}"; 4 | settingsFormat = pkgs.formats.toml { }; 5 | portFromPath = { path, default }: lib.trivial.pipe cfg.settings [ 6 | (lib.attrByPath path default) 7 | (lib.splitString ":") 8 | lib.last 9 | lib.toInt 10 | ]; 11 | usesACME = hasCerts && builtins.isString cfg.useACMEHost; 12 | noStorageSpec = hasStorage && builtins.isNull (lib.attrByPath [ role "store-dir" ] null cfg.settings); 13 | in 14 | { 15 | options.services."connet-${role}" = { 16 | enable = lib.mkEnableOption "connet ${role}"; 17 | 18 | package = lib.mkOption { 19 | default = pkgs.callPackage ./package.nix { }; 20 | type = lib.types.package; 21 | }; 22 | 23 | user = lib.mkOption { 24 | default = "connet"; 25 | type = lib.types.str; 26 | description = '' 27 | User account under which connet runs. 28 | 29 | ::: {.note} 30 | If left as the default value this user will automatically be created 31 | on system activation, otherwise you are responsible for 32 | ensuring the user exists before the connet service starts. 33 | ::: 34 | ''; 35 | }; 36 | 37 | group = lib.mkOption { 38 | default = "connet"; 39 | type = lib.types.str; 40 | description = '' 41 | Group under which connet runs. 42 | 43 | ::: {.note} 44 | If left as the default value this group will automatically be created 45 | on system activation, otherwise you are responsible for 46 | ensuring the group exists before the connet service starts. 47 | ::: 48 | ''; 49 | }; 50 | 51 | settings = lib.mkOption { 52 | description = "See docs at https://github.com/connet-dev/connet?tab=readme-ov-file#configuration"; 53 | default = { }; 54 | type = lib.types.submodule { 55 | freeformType = settingsFormat.type; 56 | }; 57 | }; 58 | 59 | openFirewall = lib.mkOption { 60 | default = false; 61 | type = lib.types.bool; 62 | description = "Whether to open the firewall for the specified port."; 63 | }; 64 | } // lib.optionalAttrs hasCerts { 65 | useACMEHost = lib.mkOption { 66 | default = null; 67 | type = lib.types.nullOr lib.types.str; 68 | description = '' 69 | A host of an existing ACME certificate to use. 70 | *Note that this option does not create any certificates, nor 71 | does it add subdomains to existing ones – you will need to create them 72 | manually using [](#opt-security.acme.certs).* 73 | ''; 74 | example = "example.com"; 75 | }; 76 | }; 77 | 78 | config = lib.mkIf cfg.enable { 79 | warnings = lib.flatten [ 80 | (lib.optionals 81 | (usesACME && builtins.isString (lib.attrByPath [ role "cert-file" ] null cfg.settings)) 82 | [ "ACME config for ${cfg.useACMEHost} overrides `${role}.cert-file`" ]) 83 | (lib.optionals 84 | (usesACME && builtins.isString (lib.attrByPath [ role "key-file" ] null cfg.settings)) 85 | [ "ACME config for ${cfg.useACMEHost} overrides `${role}.key-file`" ]) 86 | ]; 87 | 88 | boot.kernel.sysctl."net.core.rmem_max" = lib.mkDefault 7500000; 89 | boot.kernel.sysctl."net.core.wmem_max" = lib.mkDefault 7500000; 90 | 91 | users.users = lib.optionalAttrs (cfg.user == "connet") { 92 | connet = { 93 | isSystemUser = true; 94 | group = cfg.group; 95 | }; 96 | }; 97 | 98 | users.groups = lib.optionalAttrs (cfg.group == "connet") { 99 | connet = { }; 100 | }; 101 | 102 | networking.firewall.allowedUDPPorts = lib.mkIf cfg.openFirewall (builtins.map portFromPath ports); 103 | 104 | environment.etc."connet-${role}.toml" = { 105 | user = cfg.user; 106 | group = cfg.group; 107 | source = settingsFormat.generate "connet-config-${role}.toml" (lib.recursiveUpdate 108 | cfg.settings 109 | (lib.recursiveUpdate 110 | (lib.optionalAttrs usesACME ( 111 | let 112 | sslCertDir = config.security.acme.certs.${cfg.useACMEHost}.directory; 113 | in 114 | { 115 | ${role} = { 116 | cert-file = "${sslCertDir}/cert.pem"; 117 | key-file = "${sslCertDir}/key.pem"; 118 | }; 119 | } 120 | )) 121 | (lib.optionalAttrs noStorageSpec { 122 | ${role} = { "store-dir" = "/var/lib/connet-${role}"; }; 123 | }))); 124 | }; 125 | 126 | systemd.packages = [ cfg.package ]; 127 | systemd.services."connet-${role}" = { 128 | description = "connet ${role}"; 129 | after = [ "network.target" "network-online.target" ]; 130 | requires = [ "network-online.target" ] ++ lib.optionals usesACME [ "acme-finished-${cfg.useACMEHost}.target" ]; 131 | wantedBy = [ "multi-user.target" ]; 132 | restartTriggers = [ config.environment.etc."connet-${role}.toml".source ]; 133 | serviceConfig = { 134 | User = cfg.user; 135 | Group = cfg.group; 136 | ExecStart = "${cfg.package}/bin/connet ${if role == "client" then "" else "${role} "} --config /etc/connet-${role}.toml"; 137 | Restart = "on-failure"; 138 | CacheDirectory = "connet-${role}"; 139 | CacheDirectoryMode = "0700"; 140 | } // lib.optionalAttrs noStorageSpec { 141 | StateDirectory = "connet-${role}"; 142 | StateDirectoryMode = "0700"; 143 | }; 144 | }; 145 | }; 146 | } 147 | -------------------------------------------------------------------------------- /certc/cert.go: -------------------------------------------------------------------------------- 1 | package certc 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ed25519" 6 | "crypto/rand" 7 | "crypto/tls" 8 | "crypto/x509" 9 | "crypto/x509/pkix" 10 | "encoding/pem" 11 | "fmt" 12 | "math/big" 13 | "net" 14 | "time" 15 | ) 16 | 17 | var SharedSubject = pkix.Name{ 18 | CommonName: "connet", 19 | } 20 | 21 | type Cert struct { 22 | der []byte 23 | sk crypto.PrivateKey 24 | } 25 | 26 | func NewRoot() (*Cert, error) { 27 | _, sk, err := ed25519.GenerateKey(rand.Reader) 28 | if err != nil { 29 | return nil, err 30 | } 31 | 32 | template := &x509.Certificate{ 33 | SerialNumber: big.NewInt(time.Now().UnixMicro()), 34 | 35 | NotBefore: time.Now(), 36 | NotAfter: time.Now().AddDate(100, 0, 0), 37 | 38 | Subject: SharedSubject, 39 | 40 | BasicConstraintsValid: true, 41 | IsCA: true, 42 | 43 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign | x509.KeyUsageCRLSign, 44 | ExtKeyUsage: []x509.ExtKeyUsage{}, 45 | } 46 | 47 | der, err := x509.CreateCertificate(rand.Reader, template, template, sk.Public(), sk) 48 | if err != nil { 49 | return nil, err 50 | } 51 | return &Cert{der, sk}, nil 52 | } 53 | 54 | type CertOpts struct { 55 | Domains []string 56 | IPs []net.IP 57 | } 58 | 59 | func (opts CertOpts) subject() (pkix.Name, error) { 60 | if len(opts.Domains) > 0 { 61 | return pkix.Name{CommonName: opts.Domains[0]}, nil 62 | } else if len(opts.IPs) > 0 { 63 | return pkix.Name{CommonName: opts.IPs[0].String()}, nil 64 | } 65 | 66 | return pkix.Name{}, fmt.Errorf("missing common name") 67 | } 68 | 69 | func (c *Cert) NewServer(opts CertOpts) (*Cert, error) { 70 | parent, err := x509.ParseCertificate(c.der) 71 | if err != nil { 72 | return nil, err 73 | } 74 | 75 | pk, sk, err := ed25519.GenerateKey(rand.Reader) 76 | if err != nil { 77 | return nil, err 78 | } 79 | 80 | subject, err := opts.subject() 81 | if err != nil { 82 | return nil, err 83 | } 84 | 85 | certTemplate := &x509.Certificate{ 86 | SerialNumber: big.NewInt(time.Now().UnixMicro()), 87 | 88 | NotBefore: time.Now(), 89 | NotAfter: time.Now().AddDate(2, 0, 0), 90 | 91 | Issuer: parent.Subject, 92 | Subject: subject, 93 | 94 | DNSNames: opts.Domains, 95 | IPAddresses: opts.IPs, 96 | 97 | BasicConstraintsValid: false, 98 | IsCA: false, 99 | 100 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageContentCommitment, 101 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, 102 | } 103 | 104 | der, err := x509.CreateCertificate(rand.Reader, certTemplate, parent, pk, c.sk) 105 | if err != nil { 106 | return nil, err 107 | } 108 | 109 | return &Cert{der, sk}, nil 110 | } 111 | 112 | func (c *Cert) NewClient() (*Cert, error) { 113 | parent, err := x509.ParseCertificate(c.der) 114 | if err != nil { 115 | return nil, err 116 | } 117 | 118 | pk, sk, err := ed25519.GenerateKey(rand.Reader) 119 | if err != nil { 120 | return nil, err 121 | } 122 | 123 | certTemplate := &x509.Certificate{ 124 | SerialNumber: big.NewInt(time.Now().UnixMicro()), 125 | 126 | NotBefore: time.Now(), 127 | NotAfter: time.Now().AddDate(2, 0, 0), 128 | 129 | Issuer: parent.Subject, 130 | Subject: SharedSubject, 131 | 132 | BasicConstraintsValid: false, 133 | IsCA: false, 134 | 135 | KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement | x509.KeyUsageContentCommitment, 136 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, 137 | } 138 | 139 | der, err := x509.CreateCertificate(rand.Reader, certTemplate, parent, pk, c.sk) 140 | if err != nil { 141 | return nil, err 142 | } 143 | 144 | return &Cert{der, sk}, nil 145 | } 146 | 147 | func (c *Cert) Cert() (*x509.Certificate, error) { 148 | return x509.ParseCertificate(c.der) 149 | } 150 | 151 | func (c *Cert) Raw() []byte { 152 | return c.der 153 | } 154 | 155 | func (c *Cert) CertPool() (*x509.CertPool, error) { 156 | cert, err := c.Cert() 157 | if err != nil { 158 | return nil, err 159 | } 160 | 161 | pool := x509.NewCertPool() 162 | pool.AddCert(cert) 163 | return pool, nil 164 | } 165 | 166 | func (c *Cert) TLSCert() (tls.Certificate, error) { 167 | cert, err := c.Cert() 168 | if err != nil { 169 | return tls.Certificate{}, err 170 | } 171 | return tls.Certificate{ 172 | Certificate: [][]byte{c.der}, 173 | PrivateKey: c.sk, 174 | Leaf: cert, 175 | }, nil 176 | } 177 | 178 | func (c *Cert) EncodeToMemory() ([]byte, []byte, error) { 179 | certPEM := pem.EncodeToMemory(&pem.Block{ 180 | Type: "CERTIFICATE", 181 | Bytes: c.der, 182 | }) 183 | 184 | keyData, err := x509.MarshalPKCS8PrivateKey(c.sk) 185 | if err != nil { 186 | return nil, nil, fmt.Errorf("mem key marshal: %w", err) 187 | } 188 | keyPEM := pem.EncodeToMemory(&pem.Block{ 189 | Type: "PRIVATE KEY", 190 | Bytes: keyData, 191 | }) 192 | return certPEM, keyPEM, nil 193 | } 194 | 195 | func DecodeFromMemory(cert, key []byte) (*Cert, error) { 196 | certDER, _ := pem.Decode(cert) 197 | if certDER == nil { 198 | return nil, fmt.Errorf("cert: no pem block") 199 | } 200 | if certDER.Type != "CERTIFICATE" { 201 | return nil, fmt.Errorf("cert type: %s", certDER.Type) 202 | } 203 | 204 | keyDER, _ := pem.Decode(key) 205 | if keyDER == nil { 206 | return nil, fmt.Errorf("cert key: no pem block") 207 | } 208 | if keyDER.Type != "PRIVATE KEY" { 209 | return nil, fmt.Errorf("cert key type: %s", keyDER.Type) 210 | } 211 | 212 | keyValue, err := x509.ParsePKCS8PrivateKey(keyDER.Bytes) 213 | if err != nil { 214 | return nil, fmt.Errorf("cert parse key: %w", err) 215 | } 216 | 217 | return &Cert{der: certDER.Bytes, sk: keyValue}, nil 218 | } 219 | -------------------------------------------------------------------------------- /notify/value.go: -------------------------------------------------------------------------------- 1 | package notify 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "maps" 7 | "slices" 8 | "sync/atomic" 9 | 10 | "github.com/connet-dev/connet/iterc" 11 | ) 12 | 13 | var errNotifyClosed = errors.New("notify already closed") 14 | var errNotifyEmpty = errors.New("no value") 15 | 16 | type V[T any] struct { 17 | value atomic.Pointer[value[T]] 18 | barrier chan *version[T] 19 | } 20 | 21 | type value[T any] struct { 22 | value T 23 | version uint64 24 | } 25 | 26 | type version[T any] struct { 27 | value T 28 | version uint64 29 | waiter chan struct{} 30 | } 31 | 32 | func NewEmpty[T any]() *V[T] { 33 | v := &V[T]{ 34 | barrier: make(chan *version[T], 1), 35 | } 36 | v.barrier <- &version[T]{waiter: make(chan struct{})} 37 | return v 38 | } 39 | 40 | func New[T any](t T) *V[T] { 41 | v := &V[T]{ 42 | barrier: make(chan *version[T], 1), 43 | } 44 | v.barrier <- &version[T]{waiter: make(chan struct{})} 45 | v.value.Store(&value[T]{t, 0}) 46 | return v 47 | } 48 | 49 | func (v *V[T]) Get(ctx context.Context, version uint64) (T, uint64, error) { 50 | if current := v.value.Load(); current != nil && current.version > version { 51 | return current.value, current.version, nil 52 | } 53 | 54 | next, ok := <-v.barrier 55 | if !ok { 56 | var t T 57 | return t, 0, errNotifyClosed 58 | } 59 | 60 | current := v.value.Load() 61 | 62 | v.barrier <- next 63 | 64 | if current != nil && current.version > version { 65 | return current.value, current.version, nil 66 | } 67 | 68 | select { 69 | case <-next.waiter: 70 | return next.value, next.version, nil 71 | case <-ctx.Done(): 72 | var t T 73 | return t, 0, ctx.Err() 74 | } 75 | } 76 | 77 | func (v *V[T]) GetAny(ctx context.Context) (T, uint64, error) { 78 | if current := v.value.Load(); current != nil { 79 | return current.value, current.version, nil 80 | } 81 | 82 | next, ok := <-v.barrier 83 | if !ok { 84 | var t T 85 | return t, 0, errNotifyClosed 86 | } 87 | 88 | current := v.value.Load() 89 | 90 | v.barrier <- next 91 | 92 | if current != nil { 93 | return current.value, current.version, nil 94 | } 95 | 96 | select { 97 | case <-next.waiter: 98 | return next.value, next.version, nil 99 | case <-ctx.Done(): 100 | var t T 101 | return t, 0, ctx.Err() 102 | } 103 | } 104 | 105 | func (v *V[T]) Peek() (T, error) { 106 | if current := v.value.Load(); current != nil { 107 | return current.value, nil 108 | } 109 | var t T 110 | return t, errNotifyEmpty 111 | } 112 | 113 | func (v *V[T]) Sync(f func()) { 114 | next, ok := <-v.barrier 115 | if !ok { 116 | return 117 | } 118 | defer func() { 119 | v.barrier <- next 120 | }() 121 | 122 | f() 123 | } 124 | 125 | func (v *V[T]) Set(t T) { 126 | v.UpdateOpt(func(_ T) (T, bool) { 127 | return t, true 128 | }) 129 | } 130 | 131 | func (v *V[T]) Update(f func(t T) T) { 132 | v.UpdateOpt(func(t T) (T, bool) { 133 | return f(t), true 134 | }) 135 | } 136 | 137 | func (v *V[T]) UpdateOpt(f func(t T) (T, bool)) bool { 138 | next, ok := <-v.barrier 139 | if !ok { 140 | return false 141 | } 142 | 143 | if current := v.value.Load(); current != nil { 144 | if value, updated := f(current.value); updated { 145 | next.value = value 146 | next.version = current.version + 1 147 | } else { 148 | return false 149 | } 150 | } else { 151 | var t T 152 | if value, updated := f(t); updated { 153 | next.value = value 154 | next.version = 0 155 | } else { 156 | return false 157 | } 158 | } 159 | v.value.Store(&value[T]{next.value, next.version}) 160 | 161 | close(next.waiter) 162 | 163 | v.barrier <- &version[T]{waiter: make(chan struct{})} 164 | 165 | return true 166 | } 167 | 168 | func (v *V[T]) Listen(ctx context.Context, f func(t T) error) error { 169 | t, ver, err := v.GetAny(ctx) 170 | if err != nil { 171 | return err 172 | } 173 | if err := f(t); err != nil { 174 | return err 175 | } 176 | for { 177 | t, ver, err = v.Get(ctx, ver) 178 | if err != nil { 179 | return err 180 | } 181 | if err := f(t); err != nil { 182 | return err 183 | } 184 | } 185 | } 186 | 187 | func (v *V[T]) Notify(ctx context.Context) <-chan T { 188 | ch := make(chan T, 1) 189 | go func() { 190 | defer close(ch) 191 | _ = v.Listen(ctx, func(t T) error { 192 | ch <- t 193 | return nil 194 | }) 195 | }() 196 | return ch 197 | } 198 | 199 | func SliceAppend[S []T, T any](v *V[S], val T) { 200 | v.Update(func(t S) S { 201 | return append(slices.Clone(t), val) 202 | }) 203 | } 204 | 205 | func SliceRemove[S []T, T comparable](v *V[S], val T) { 206 | v.Update(func(t S) S { 207 | return iterc.FilterSlice(t, func(el T) bool { return el != val }) 208 | }) 209 | } 210 | 211 | func MapPut[M ~map[K]T, K comparable, T any](m *V[M], k K, v T) { 212 | m.Update(func(t M) M { 213 | t = maps.Clone(t) 214 | t[k] = v 215 | return t 216 | }) 217 | } 218 | 219 | func MapDelete[M ~map[K]T, K comparable, T any](m *V[M], k K) { 220 | m.Update(func(t M) M { 221 | t = maps.Clone(t) 222 | delete(t, k) 223 | return t 224 | }) 225 | } 226 | 227 | func MapDeleteFunc[M ~map[K]T, K comparable, T any](m *V[M], del func(K, T) bool) { 228 | m.Update(func(t M) M { 229 | t = maps.Clone(t) 230 | maps.DeleteFunc(t, del) 231 | return t 232 | }) 233 | } 234 | 235 | func ListenMulti[L any, R any](ctx context.Context, nl *V[L], nr *V[R], fn func(context.Context, L, R) error) error { 236 | var l L 237 | var r R 238 | 239 | cl := nl.Notify(ctx) 240 | cr := nr.Notify(ctx) 241 | 242 | for { 243 | select { 244 | case l = <-cl: 245 | if err := fn(ctx, l, r); err != nil { 246 | return err 247 | } 248 | case r = <-cr: 249 | if err := fn(ctx, l, r); err != nil { 250 | return err 251 | } 252 | case <-ctx.Done(): 253 | return ctx.Err() 254 | } 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_run: 3 | workflows: [ci] 4 | types: [completed] 5 | branches: [main] 6 | workflow_dispatch: 7 | inputs: 8 | version: 9 | description: "Version to release (format: vX.Y.Z)" 10 | required: true 11 | upload: 12 | description: "Upload final artifacts to github" 13 | default: false 14 | workflow_call: 15 | inputs: 16 | version: 17 | required: true 18 | type: string 19 | push: 20 | tags: 21 | - "v[0-9]+.[0-9]+.[0-9]+" 22 | 23 | concurrency: 24 | group: ${{ github.workflow }}-release 25 | cancel-in-progress: false 26 | 27 | permissions: 28 | contents: write 29 | packages: write 30 | id-token: write 31 | 32 | jobs: 33 | setup: 34 | name: Setup 35 | runs-on: ubuntu-latest 36 | outputs: 37 | version: ${{ steps.extract_version.outputs.version }} 38 | publish: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.upload == 'true' || github.event_name == 'push' }} 39 | steps: 40 | - name: Exract the Version 41 | id: extract_version 42 | run: | 43 | if [[ "${{ github.event_name }}" == "push" ]]; then 44 | IN_VERSION=${{ inputs.version }} 45 | # Remove the leading 'v' from the tag 46 | GIT_VERSION=${GITHUB_REF#refs/tags/v} 47 | VERSION=${IN_VERSION:-$GIT_VERSION} 48 | echo "version=$VERSION" >> $GITHUB_OUTPUT 49 | elif [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then 50 | VERSION=${{ github.event.inputs.version }} 51 | VERSION=${VERSION#v} 52 | echo "version=$VERSION" >> $GITHUB_OUTPUT 53 | else 54 | echo "Error: Unsupported event type." 55 | exit 1 56 | fi 57 | 58 | binary: 59 | name: Binaries 60 | runs-on: ubuntu-latest 61 | needs: [setup] 62 | env: 63 | CONNET_VERSION: ${{ needs.setup.outputs.version }} 64 | steps: 65 | - uses: actions/checkout@v4 66 | - uses: DeterminateSystems/nix-installer-action@main 67 | with: 68 | determinate: true 69 | github-token: ${{ secrets.GITHUB_TOKEN }} 70 | - uses: DeterminateSystems/flakehub-cache-action@main 71 | - name: Build release 72 | run: nix develop --command make release 73 | - name: Upload release 74 | uses: softprops/action-gh-release@v2 75 | if: ${{ needs.setup.outputs.publish }} 76 | with: 77 | tag_name: v${{ env.CONNET_VERSION }} 78 | files: | 79 | dist/archive/connet-${{ env.CONNET_VERSION }}-*.tar.gz 80 | dist/archive/connet-${{ env.CONNET_VERSION }}-*.zip 81 | 82 | docker-x86: 83 | name: Docker x86 84 | runs-on: ubuntu-latest 85 | needs: [setup] 86 | env: 87 | CONNET_VERSION: ${{ needs.setup.outputs.version }} 88 | steps: 89 | - uses: actions/checkout@v4 90 | - uses: DeterminateSystems/nix-installer-action@main 91 | with: 92 | determinate: true 93 | github-token: ${{ secrets.GITHUB_TOKEN }} 94 | - uses: DeterminateSystems/flakehub-cache-action@main 95 | - name: Docker build 96 | run: nix build .#docker 97 | - name: Docker login 98 | uses: docker/login-action@v3 99 | with: 100 | registry: ghcr.io 101 | username: ${{ github.actor }} 102 | password: ${{ secrets.GITHUB_TOKEN }} 103 | - name: Docker push 104 | if: ${{ needs.setup.outputs.publish }} 105 | run: nix develop --command skopeo copy "docker-archive:result" "docker://ghcr.io/connet-dev/connet:${CONNET_VERSION}-amd64" 106 | 107 | docker-arm: 108 | name: Docker arm 109 | runs-on: ubuntu-latest 110 | needs: [setup] 111 | env: 112 | CONNET_VERSION: ${{ needs.setup.outputs.version }} 113 | steps: 114 | - uses: actions/checkout@v4 115 | - uses: docker/setup-qemu-action@v3 116 | - uses: DeterminateSystems/nix-installer-action@main 117 | with: 118 | determinate: true 119 | github-token: ${{ secrets.GITHUB_TOKEN }} 120 | extra-conf: system = aarch64-linux 121 | - uses: DeterminateSystems/flakehub-cache-action@main 122 | - name: Docker build 123 | run: nix build .#docker 124 | - name: Docker login 125 | uses: docker/login-action@v3 126 | with: 127 | registry: ghcr.io 128 | username: ${{ github.actor }} 129 | password: ${{ secrets.GITHUB_TOKEN }} 130 | - name: Docker push 131 | if: ${{ needs.setup.outputs.publish }} 132 | run: nix develop --command skopeo copy "docker-archive:result" "docker://ghcr.io/connet-dev/connet:${CONNET_VERSION}-arm64" 133 | 134 | docker-multiarch: 135 | name: Tag multi-arch 136 | runs-on: ubuntu-latest 137 | needs: [setup, docker-x86, docker-arm] 138 | env: 139 | CONNET_VERSION: ${{ needs.setup.outputs.version }} 140 | steps: 141 | - uses: actions/checkout@v4 142 | - uses: DeterminateSystems/nix-installer-action@main 143 | with: 144 | determinate: true 145 | github-token: ${{ secrets.GITHUB_TOKEN }} 146 | - uses: DeterminateSystems/flakehub-cache-action@main 147 | - name: Docker login 148 | uses: docker/login-action@v3 149 | with: 150 | registry: ghcr.io 151 | username: ${{ github.actor }} 152 | password: ${{ secrets.GITHUB_TOKEN }} 153 | - name: Docker tag 154 | if: ${{ needs.setup.outputs.publish }} 155 | run: nix develop --command manifest-tool push from-args --platforms linux/amd64,linux/arm64 --template ghcr.io/connet-dev/connet:${CONNET_VERSION}-ARCHVARIANT --target ghcr.io/connet-dev/connet:${CONNET_VERSION} 156 | -------------------------------------------------------------------------------- /destinations.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "context" 5 | "crypto/tls" 6 | "crypto/x509" 7 | "log/slog" 8 | "net" 9 | "net/http" 10 | "net/http/httputil" 11 | "net/url" 12 | "time" 13 | 14 | "github.com/connet-dev/connet/netc" 15 | "github.com/connet-dev/connet/slogc" 16 | ) 17 | 18 | // DestinationTCP creates a new destination which connects to a downstream TCP server 19 | func (c *Client) DestinationTCP(ctx context.Context, cfg DestinationConfig, addr string) error { 20 | dst, err := c.Destination(ctx, cfg) 21 | if err != nil { 22 | return err 23 | } 24 | go func() { 25 | dstSrv := NewTCPDestination(dst, addr, cfg.DialTimeout, c.logger) 26 | if err := dstSrv.Run(ctx); err != nil { 27 | c.logger.Info("shutting down destination tcp", "err", err) 28 | } 29 | }() 30 | return nil 31 | } 32 | 33 | // DestinationTLS creates a new destination which connects to a downstream TLS server 34 | func (c *Client) DestinationTLS(ctx context.Context, cfg DestinationConfig, addr string, cas *x509.CertPool) error { 35 | dst, err := c.Destination(ctx, cfg) 36 | if err != nil { 37 | return err 38 | } 39 | go func() { 40 | dstSrv := NewTLSDestination(dst, addr, &tls.Config{RootCAs: cas}, cfg.DialTimeout, c.logger) 41 | if err := dstSrv.Run(ctx); err != nil { 42 | c.logger.Info("shutting down destination tls", "err", err) 43 | } 44 | }() 45 | return nil 46 | } 47 | 48 | // DestinationHTTP creates a new destination which exposes an HTTP server for a given [http.Handler] 49 | func (c *Client) DestinationHTTP(ctx context.Context, cfg DestinationConfig, handler http.Handler) error { 50 | dst, err := c.Destination(ctx, cfg) 51 | if err != nil { 52 | return err 53 | } 54 | go func() { 55 | dstSrv := NewHTTPDestination(dst, handler) 56 | if err := dstSrv.Run(ctx); err != nil { 57 | c.logger.Info("shutting down destination http", "err", err) 58 | } 59 | }() 60 | return nil 61 | } 62 | 63 | // DestinationHTTPProxy creates a new destination which exposes an HTTP proxy server to another HTTP server 64 | func (c *Client) DestinationHTTPProxy(ctx context.Context, cfg DestinationConfig, dstUrl *url.URL) error { 65 | dst, err := c.Destination(ctx, cfg) 66 | if err != nil { 67 | return err 68 | } 69 | go func() { 70 | dstSrv := NewHTTPProxyDestination(dst, dstUrl, nil, cfg.DialTimeout) 71 | if err := dstSrv.Run(ctx); err != nil { 72 | c.logger.Info("shutting down destination http", "err", err) 73 | } 74 | }() 75 | return nil 76 | } 77 | 78 | // DestinationHTTPSProxy creates a new destination which exposes an HTTP proxy server to another HTTPS server 79 | func (c *Client) DestinationHTTPSProxy(ctx context.Context, cfg DestinationConfig, dstUrl *url.URL, cas *x509.CertPool) error { 80 | dst, err := c.Destination(ctx, cfg) 81 | if err != nil { 82 | return err 83 | } 84 | go func() { 85 | dstSrv := NewHTTPProxyDestination(dst, dstUrl, &tls.Config{RootCAs: cas}, cfg.DialTimeout) 86 | if err := dstSrv.Run(ctx); err != nil { 87 | c.logger.Info("shutting down destination http", "err", err) 88 | } 89 | }() 90 | return nil 91 | } 92 | 93 | type dialer interface { 94 | DialContext(ctx context.Context, network, address string) (net.Conn, error) 95 | } 96 | 97 | type TCPDestination struct { 98 | dst *Destination 99 | dialer dialer 100 | addr string 101 | logger *slog.Logger 102 | } 103 | 104 | func newTCPDestination(dst *Destination, d dialer, addr string, logger *slog.Logger) *TCPDestination { 105 | return &TCPDestination{ 106 | dst: dst, 107 | addr: addr, 108 | dialer: d, 109 | logger: logger.With("destination", dst.Config().Endpoint, "addr", addr), 110 | } 111 | } 112 | 113 | func NewTCPDestination(dst *Destination, addr string, timeout time.Duration, logger *slog.Logger) *TCPDestination { 114 | return newTCPDestination(dst, &net.Dialer{Timeout: timeout}, addr, logger) 115 | } 116 | 117 | func NewTLSDestination(dst *Destination, addr string, cfg *tls.Config, timeout time.Duration, logger *slog.Logger) *TCPDestination { 118 | return newTCPDestination(dst, &tls.Dialer{NetDialer: &net.Dialer{Timeout: timeout}, Config: cfg}, addr, logger) 119 | } 120 | 121 | func (d *TCPDestination) Run(ctx context.Context) error { 122 | return (&netc.Joiner{ 123 | Accept: func(ctx context.Context) (net.Conn, error) { 124 | conn, err := d.dst.AcceptContext(ctx) 125 | d.logger.Debug("destination accept", "err", err) 126 | return conn, err 127 | }, 128 | Dial: func(ctx context.Context) (net.Conn, error) { 129 | conn, err := d.dialer.DialContext(ctx, "tcp", d.addr) 130 | d.logger.Debug("destination dial", "err", err) 131 | return conn, err 132 | }, 133 | Join: func(ctx context.Context, acceptConn, dialConn net.Conn) { 134 | err := netc.Join(acceptConn, dialConn) 135 | d.logger.Debug("destination disconnected", "err", err) 136 | }, 137 | }).Run(ctx) 138 | } 139 | 140 | type HTTPDestination struct { 141 | dst *Destination 142 | 143 | handler http.Handler 144 | } 145 | 146 | func NewHTTPDestination(dst *Destination, handler http.Handler) *HTTPDestination { 147 | return &HTTPDestination{dst, handler} 148 | } 149 | 150 | func NewHTTPFileDestination(dst *Destination, root string) *HTTPDestination { 151 | mux := http.NewServeMux() 152 | mux.Handle("/", http.FileServer(http.Dir(root))) 153 | return NewHTTPDestination(dst, mux) 154 | } 155 | 156 | func NewHTTPProxyDestination(dst *Destination, dstURL *url.URL, cfg *tls.Config, timeout time.Duration) *HTTPDestination { 157 | return NewHTTPDestination(dst, &httputil.ReverseProxy{ 158 | Rewrite: func(pr *httputil.ProxyRequest) { 159 | pr.SetURL(dstURL) 160 | pr.SetXForwarded() 161 | }, 162 | Transport: &http.Transport{ 163 | TLSClientConfig: cfg, 164 | DialContext: (&net.Dialer{ 165 | Timeout: timeout, 166 | KeepAlive: 30 * time.Second, 167 | }).DialContext, 168 | }, 169 | }) 170 | } 171 | 172 | func (d *HTTPDestination) Run(ctx context.Context) error { 173 | srv := &http.Server{ 174 | Handler: d.handler, 175 | } 176 | 177 | go func() { 178 | <-ctx.Done() 179 | if err := srv.Close(); err != nil { 180 | slogc.FineDefault("error closing destination http server", "err", err) 181 | } 182 | }() 183 | 184 | return srv.Serve(d.dst) 185 | } 186 | -------------------------------------------------------------------------------- /cmd/connet/server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log/slog" 7 | "net" 8 | 9 | "github.com/connet-dev/connet/server" 10 | "github.com/spf13/cobra" 11 | ) 12 | 13 | type ServerConfig struct { 14 | Ingresses []ControlIngress `toml:"ingress"` 15 | 16 | TokensFile string `toml:"tokens-file"` 17 | Tokens []string `toml:"tokens"` 18 | TokenRestrictions []TokenRestriction `toml:"token-restriction"` 19 | 20 | RelayIngresses []RelayIngress `toml:"relay-ingress"` 21 | 22 | StatusAddr string `toml:"status-addr"` 23 | StoreDir string `toml:"store-dir"` 24 | } 25 | 26 | func serverCmd() *cobra.Command { 27 | cmd := &cobra.Command{ 28 | Use: "server", 29 | Short: "Run a connet server (control and relay server as one)", 30 | } 31 | cmd.Flags().SortFlags = false 32 | 33 | filenames := addConfigsFlag(cmd) 34 | 35 | var flagsConfig Config 36 | flagsConfig.addLogFlags(cmd) 37 | 38 | cmd.Flags().StringVar(&flagsConfig.Server.TokensFile, "tokens-file", "", "file containing list of client auth tokens (token per line)") 39 | cmd.Flags().StringArrayVar(&flagsConfig.Server.Tokens, "tokens", nil, "list of client auth tokens (fallback 'tokens-file' is not specified)") 40 | 41 | var clientIngress ControlIngress 42 | cmd.Flags().StringVar(&clientIngress.Addr, "addr", "", "clients server address to listen for connection (UDP/QUIC, [host]:port) (defaults to ':19190')") 43 | cmd.Flags().StringVar(&clientIngress.Cert, "cert-file", "", "clients server TLS certificate file (pem format)") 44 | cmd.Flags().StringVar(&clientIngress.Key, "key-file", "", "clients server TLS certificate private key file (pem format)") 45 | cmd.Flags().StringArrayVar(&clientIngress.AllowCIDRs, "allow-cidr", nil, "list of allowed networks for client connections (CIDR format)") 46 | cmd.Flags().StringArrayVar(&clientIngress.DenyCIDRs, "deny-cidr", nil, "list of denied networks for client connections (CIDR format)") 47 | 48 | var relayIngress RelayIngress 49 | cmd.Flags().StringVar(&relayIngress.Addr, "relay-addr", "", "relay clients server address (UDP/QUIC, [host]:port) (defaults to ':19191')") 50 | cmd.Flags().StringArrayVar(&relayIngress.Hostports, "relay-hostport", nil, `list of host[:port]s advertised by the control server for clients to connect to this relay 51 | defaults to 'localhost:', if port is not set will use the addr's port`) 52 | cmd.Flags().StringArrayVar(&relayIngress.AllowCIDRs, "relay-allow-cidr", nil, "list of allowed networks for relay client connections (CIDR format)") 53 | cmd.Flags().StringArrayVar(&relayIngress.DenyCIDRs, "relay-deny-cidr", nil, "list of denied networks for relay client connections (CIDR format)") 54 | 55 | addStatusAddrFlag(cmd, &flagsConfig.Server.StatusAddr) 56 | addStoreDirFlag(cmd, &flagsConfig.Server.StoreDir) 57 | 58 | cmd.RunE = wrapErr("run connet server", func(cmd *cobra.Command, _ []string) error { 59 | cfg, err := loadConfigs(*filenames) 60 | if err != nil { 61 | return fmt.Errorf("load config: %w", err) 62 | } 63 | 64 | if !clientIngress.isZero() { 65 | flagsConfig.Server.Ingresses = append(flagsConfig.Server.Ingresses, clientIngress) 66 | } 67 | if !relayIngress.isZero() { 68 | flagsConfig.Server.RelayIngresses = append(flagsConfig.Server.RelayIngresses, relayIngress) 69 | } 70 | cfg.merge(flagsConfig) 71 | 72 | logger, err := logger(cfg) 73 | if err != nil { 74 | return fmt.Errorf("configure logger: %w", err) 75 | } 76 | 77 | return serverRun(cmd.Context(), cfg.Server, logger) 78 | }) 79 | 80 | return cmd 81 | } 82 | 83 | func addStoreDirFlag(cmd *cobra.Command, ref *string) { 84 | cmd.Flags().StringVar(ref, "store-dir", "", `directory to store persistent state 85 | when empty will try the following environment variables: CONNET_STATE_DIR, STATE_DIRECTORY 86 | if still empty, it will try to create a subdirectory in the current system TMPDIR directory`) 87 | } 88 | 89 | func serverRun(ctx context.Context, cfg ServerConfig, logger *slog.Logger) error { 90 | var opts []server.Option 91 | 92 | var usedClientDefault bool 93 | for ix, ingressCfg := range cfg.Ingresses { 94 | if ingressCfg.Addr == "" && !usedClientDefault { 95 | ingressCfg.Addr = ":19190" 96 | usedClientDefault = true 97 | } 98 | if ingress, err := ingressCfg.parse(); err != nil { 99 | return fmt.Errorf("parse ingress at %d: %w", ix, err) 100 | } else { 101 | opts = append(opts, server.ClientsIngress(ingress)) 102 | } 103 | } 104 | 105 | var err error 106 | tokens := cfg.Tokens 107 | if cfg.TokensFile != "" { 108 | tokens, err = loadTokens(cfg.TokensFile) 109 | if err != nil { 110 | return err 111 | } 112 | } 113 | clientAuth, err := parseClientAuth(tokens, cfg.TokenRestrictions) 114 | if err != nil { 115 | return err 116 | } 117 | opts = append(opts, server.ClientsAuthenticator(clientAuth)) 118 | 119 | var usedRelayDefault bool 120 | for ix, ingressCfg := range cfg.RelayIngresses { 121 | if ingressCfg.Addr == "" && !usedRelayDefault { 122 | ingressCfg.Addr = ":19191" 123 | usedRelayDefault = true 124 | } 125 | if ingress, err := ingressCfg.parse(); err != nil { 126 | return fmt.Errorf("parse ingress at %d: %w", ix, err) 127 | } else { 128 | opts = append(opts, server.RelayIngress(ingress)) 129 | } 130 | } 131 | 132 | var statusAddr *net.TCPAddr 133 | if cfg.StatusAddr != "" { 134 | addr, err := net.ResolveTCPAddr("tcp", cfg.StatusAddr) 135 | if err != nil { 136 | return fmt.Errorf("resolve status address: %w", err) 137 | } 138 | statusAddr = addr 139 | } 140 | 141 | if cfg.StoreDir != "" { 142 | opts = append(opts, server.StoreDir(cfg.StoreDir)) 143 | } 144 | 145 | opts = append(opts, server.Logger(logger)) 146 | 147 | srv, err := server.New(opts...) 148 | if err != nil { 149 | return fmt.Errorf("create server: %w", err) 150 | } 151 | return runWithStatus(ctx, srv, statusAddr, logger) 152 | } 153 | 154 | func (c *ServerConfig) merge(o ServerConfig) { 155 | c.Ingresses = mergeSlices(c.Ingresses, o.Ingresses) 156 | if len(o.Tokens) > 0 || o.TokensFile != "" { // new config completely overrides tokens 157 | c.Tokens = o.Tokens 158 | c.TokensFile = o.TokensFile 159 | } 160 | c.TokenRestrictions = mergeSlices(c.TokenRestrictions, o.TokenRestrictions) 161 | 162 | c.RelayIngresses = mergeSlices(c.RelayIngresses, o.RelayIngresses) 163 | 164 | c.StatusAddr = override(c.StatusAddr, o.StatusAddr) 165 | c.StoreDir = override(c.StoreDir, o.StoreDir) 166 | } 167 | -------------------------------------------------------------------------------- /cmd/connet/relay.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/x509" 6 | "fmt" 7 | "log/slog" 8 | "net" 9 | "os" 10 | 11 | "github.com/connet-dev/connet/relay" 12 | "github.com/connet-dev/connet/server" 13 | "github.com/spf13/cobra" 14 | ) 15 | 16 | type RelayConfig struct { 17 | TokenFile string `toml:"token-file"` 18 | Token string `toml:"token"` 19 | 20 | Ingresses []RelayIngress `toml:"ingress"` 21 | 22 | ControlAddr string `toml:"control-addr"` 23 | ControlCAsFile string `toml:"control-cas-file"` 24 | 25 | StatusAddr string `toml:"status-addr"` 26 | StoreDir string `toml:"store-dir"` 27 | } 28 | 29 | type RelayIngress struct { 30 | Addr string `toml:"addr"` 31 | Hostports []string `toml:"hostports"` 32 | IPRestriction 33 | } 34 | 35 | func relayCmd() *cobra.Command { 36 | cmd := &cobra.Command{ 37 | Use: "relay", 38 | Short: "Run a connet relay server", 39 | } 40 | cmd.Flags().SortFlags = false 41 | 42 | filenames := addConfigsFlag(cmd) 43 | 44 | var flagsConfig Config 45 | flagsConfig.addLogFlags(cmd) 46 | 47 | cmd.Flags().StringVar(&flagsConfig.Relay.TokenFile, "token-file", "", "file that contains the auth token for the control server") 48 | cmd.Flags().StringVar(&flagsConfig.Relay.Token, "token", "", "auth token for the control server (fallback when 'token-file' is not specified)") 49 | 50 | var ingress RelayIngress 51 | cmd.Flags().StringVar(&ingress.Addr, "addr", "", "clients server address to listen for connections (UDP/QUIC, [host]:port) (defaults to ':19191')") 52 | cmd.Flags().StringArrayVar(&ingress.Hostports, "hostport", nil, `list of host[:port]s advertised by the control server for clients to connect to this relay 53 | defaults to 'localhost:', if port is not set will use the addr's port`) 54 | cmd.Flags().StringArrayVar(&ingress.AllowCIDRs, "allow-cidr", nil, "list of allowed networks for client connections (CIDR format) ") 55 | cmd.Flags().StringArrayVar(&ingress.DenyCIDRs, "deny-cidr", nil, "list of denied networks for client connections (CIDR format) ") 56 | 57 | cmd.Flags().StringVar(&flagsConfig.Relay.ControlAddr, "control-addr", "", "control server address (UDP/QUIC, host:port) (defaults to '127.0.0.1:19189')") 58 | cmd.Flags().StringVar(&flagsConfig.Relay.ControlCAsFile, "control-cas-file", "", "control server TLS certificate authorities file, when not using public CAs") 59 | 60 | addStatusAddrFlag(cmd, &flagsConfig.Relay.StatusAddr) 61 | addStoreDirFlag(cmd, &flagsConfig.Relay.StoreDir) 62 | 63 | cmd.RunE = wrapErr("run connet relay server", func(cmd *cobra.Command, _ []string) error { 64 | cfg, err := loadConfigs(*filenames) 65 | if err != nil { 66 | return fmt.Errorf("load config: %w", err) 67 | } 68 | 69 | if !ingress.isZero() { 70 | flagsConfig.Relay.Ingresses = append(flagsConfig.Relay.Ingresses, ingress) 71 | } 72 | cfg.merge(flagsConfig) 73 | 74 | logger, err := logger(cfg) 75 | if err != nil { 76 | return fmt.Errorf("configure logger: %w", err) 77 | } 78 | 79 | return relayRun(cmd.Context(), cfg.Relay, logger) 80 | }) 81 | 82 | return cmd 83 | } 84 | 85 | func relayRun(ctx context.Context, cfg RelayConfig, logger *slog.Logger) error { 86 | relayCfg := relay.Config{ 87 | Logger: logger, 88 | } 89 | 90 | if cfg.TokenFile != "" { 91 | tokens, err := loadTokens(cfg.TokenFile) 92 | if err != nil { 93 | return err 94 | } 95 | relayCfg.ControlToken = tokens[0] 96 | } else { 97 | relayCfg.ControlToken = cfg.Token 98 | } 99 | 100 | if len(cfg.Ingresses) == 0 { 101 | cfg.Ingresses = append(cfg.Ingresses, RelayIngress{}) 102 | } 103 | 104 | var usedDefault bool 105 | for ix, ingressCfg := range cfg.Ingresses { 106 | if ingressCfg.Addr == "" && !usedDefault { 107 | ingressCfg.Addr = ":19191" 108 | usedDefault = true 109 | } 110 | if ingress, err := ingressCfg.parse(); err != nil { 111 | return fmt.Errorf("parse ingress at %d: %w", ix, err) 112 | } else { 113 | relayCfg.Ingress = append(relayCfg.Ingress, ingress) 114 | } 115 | } 116 | 117 | if cfg.ControlAddr == "" { 118 | cfg.ControlAddr = "localhost:19189" 119 | } 120 | controlAddr, err := net.ResolveUDPAddr("udp", cfg.ControlAddr) 121 | if err != nil { 122 | return fmt.Errorf("resolve control address: %w", err) 123 | } 124 | relayCfg.ControlAddr = controlAddr 125 | 126 | controlCAs := cfg.ControlCAsFile 127 | if controlCAs != "" { 128 | casData, err := os.ReadFile(controlCAs) 129 | if err != nil { 130 | return fmt.Errorf("read server CAs: %w", err) 131 | } 132 | 133 | cas := x509.NewCertPool() 134 | if !cas.AppendCertsFromPEM(casData) { 135 | return fmt.Errorf("missing server CA certificate in %s", controlCAs) 136 | } 137 | relayCfg.ControlCAs = cas 138 | } 139 | 140 | controlHost, _, err := net.SplitHostPort(cfg.ControlAddr) 141 | if err != nil { 142 | return fmt.Errorf("split control address: %w", err) 143 | } 144 | relayCfg.ControlHost = controlHost 145 | 146 | var statusAddr *net.TCPAddr 147 | if cfg.StatusAddr != "" { 148 | addr, err := net.ResolveTCPAddr("tcp", cfg.StatusAddr) 149 | if err != nil { 150 | return fmt.Errorf("resolve status address: %w", err) 151 | } 152 | statusAddr = addr 153 | } 154 | 155 | if cfg.StoreDir == "" { 156 | dir, err := server.StoreDirFromEnvPrefixed("connet-relay-") 157 | if err != nil { 158 | return fmt.Errorf("store dir from env: %w", err) 159 | } 160 | logger.Info("using default store directory", "dir", dir) 161 | cfg.StoreDir = dir 162 | } 163 | relayCfg.Stores = relay.NewFileStores(cfg.StoreDir) 164 | 165 | srv, err := relay.NewServer(relayCfg) 166 | if err != nil { 167 | return fmt.Errorf("create relay server: %w", err) 168 | } 169 | return runWithStatus(ctx, srv, statusAddr, logger) 170 | } 171 | 172 | func (cfg RelayIngress) parse() (relay.Ingress, error) { 173 | bldr := relay.NewIngressBuilder(). 174 | WithAddrFrom(cfg.Addr).WithRestrFrom(cfg.AllowCIDRs, cfg.DenyCIDRs) 175 | 176 | for ix, hp := range cfg.Hostports { 177 | bldr = bldr.WithHostportFrom(hp) 178 | if bldr.Error() != nil { 179 | return relay.Ingress{}, fmt.Errorf("parse hostport at %d: %w", ix, bldr.Error()) 180 | } 181 | } 182 | 183 | return bldr.Ingress() 184 | } 185 | 186 | func (c *RelayConfig) merge(o RelayConfig) { 187 | if o.Token != "" || o.TokenFile != "" { // new config completely overrides token 188 | c.Token = o.Token 189 | c.TokenFile = o.TokenFile 190 | } 191 | 192 | c.Ingresses = mergeSlices(c.Ingresses, o.Ingresses) 193 | 194 | c.ControlAddr = override(c.ControlAddr, o.ControlAddr) 195 | c.ControlCAsFile = override(c.ControlCAsFile, o.ControlCAsFile) 196 | 197 | c.StatusAddr = override(c.StatusAddr, o.StatusAddr) 198 | c.StoreDir = override(c.StoreDir, o.StoreDir) 199 | } 200 | 201 | func (c RelayIngress) merge(o RelayIngress) RelayIngress { 202 | return RelayIngress{ 203 | Addr: override(c.Addr, o.Addr), 204 | Hostports: overrides(c.Hostports, o.Hostports), 205 | IPRestriction: c.IPRestriction.merge(o.IPRestriction), 206 | } 207 | } 208 | 209 | func (s RelayIngress) isZero() bool { 210 | return s.Addr == "" && len(s.Hostports) == 0 && len(s.AllowCIDRs) == 0 && len(s.DenyCIDRs) == 0 211 | } 212 | 213 | var _ = RelayIngress.merge 214 | -------------------------------------------------------------------------------- /control/store.go: -------------------------------------------------------------------------------- 1 | package control 2 | 3 | import ( 4 | "crypto/x509" 5 | "encoding/json" 6 | "path/filepath" 7 | 8 | "github.com/connet-dev/connet/certc" 9 | "github.com/connet-dev/connet/logc" 10 | "github.com/connet-dev/connet/model" 11 | "github.com/connet-dev/connet/proto/pbclient" 12 | ) 13 | 14 | type Stores interface { 15 | Config() (logc.KV[ConfigKey, ConfigValue], error) 16 | 17 | ClientConns() (logc.KV[ClientConnKey, ClientConnValue], error) 18 | ClientPeers() (logc.KV[ClientPeerKey, ClientPeerValue], error) 19 | 20 | RelayConns() (logc.KV[RelayConnKey, RelayConnValue], error) 21 | RelayClients() (logc.KV[RelayClientKey, RelayClientValue], error) 22 | RelayEndpoints(id RelayID) (logc.KV[RelayEndpointKey, RelayEndpointValue], error) 23 | RelayServers() (logc.KV[RelayServerKey, RelayServerValue], error) 24 | RelayServerOffsets() (logc.KV[RelayConnKey, int64], error) 25 | } 26 | 27 | func NewFileStores(dir string) Stores { 28 | return &fileStores{dir} 29 | } 30 | 31 | type fileStores struct { 32 | dir string 33 | } 34 | 35 | func (f *fileStores) Config() (logc.KV[ConfigKey, ConfigValue], error) { 36 | return logc.NewKV[ConfigKey, ConfigValue](filepath.Join(f.dir, "config")) 37 | } 38 | 39 | func (f *fileStores) ClientConns() (logc.KV[ClientConnKey, ClientConnValue], error) { 40 | return logc.NewKV[ClientConnKey, ClientConnValue](filepath.Join(f.dir, "client-conns")) 41 | } 42 | 43 | func (f *fileStores) ClientPeers() (logc.KV[ClientPeerKey, ClientPeerValue], error) { 44 | return logc.NewKV[ClientPeerKey, ClientPeerValue](filepath.Join(f.dir, "client-peers")) 45 | } 46 | 47 | func (f *fileStores) RelayConns() (logc.KV[RelayConnKey, RelayConnValue], error) { 48 | return logc.NewKV[RelayConnKey, RelayConnValue](filepath.Join(f.dir, "relay-conns")) 49 | } 50 | 51 | func (f *fileStores) RelayClients() (logc.KV[RelayClientKey, RelayClientValue], error) { 52 | return logc.NewKV[RelayClientKey, RelayClientValue](filepath.Join(f.dir, "relay-clients")) 53 | } 54 | 55 | func (f *fileStores) RelayEndpoints(id RelayID) (logc.KV[RelayEndpointKey, RelayEndpointValue], error) { 56 | return logc.NewKV[RelayEndpointKey, RelayEndpointValue](filepath.Join(f.dir, "relay-endpoints", id.string)) 57 | } 58 | 59 | func (f *fileStores) RelayServers() (logc.KV[RelayServerKey, RelayServerValue], error) { 60 | return logc.NewKV[RelayServerKey, RelayServerValue](filepath.Join(f.dir, "relay-servers")) 61 | } 62 | 63 | func (f *fileStores) RelayServerOffsets() (logc.KV[RelayConnKey, int64], error) { 64 | return logc.NewKV[RelayConnKey, int64](filepath.Join(f.dir, "relay-server-offsets")) 65 | } 66 | 67 | type ConfigKey string 68 | 69 | var ( 70 | configClientStatelessReset ConfigKey = "client-stateless-reset" 71 | configRelayStatelessReset ConfigKey = "relay-stateless-reset" 72 | configServerID ConfigKey = "server-id" 73 | configServerClientSecret ConfigKey = "server-client-secret" 74 | configServerRelaySecret ConfigKey = "server-relay-secret" 75 | ) 76 | 77 | type ConfigValue struct { 78 | Int64 int64 `json:"int64,omitempty"` 79 | String string `json:"string,omitempty"` 80 | Bytes []byte `json:"bytes,omitempty"` 81 | } 82 | 83 | type ClientConnKey struct { 84 | ID ClientID `json:"id"` 85 | } 86 | 87 | type ClientConnValue struct { 88 | Authentication ClientAuthentication `json:"authentication"` 89 | Addr string `json:"addr"` 90 | } 91 | 92 | type ClientPeerKey struct { 93 | Endpoint model.Endpoint `json:"endpoint"` 94 | Role model.Role `json:"role"` 95 | ID ClientID `json:"id"` // TODO consider using the server cert key or peer id 96 | } 97 | 98 | type ClientPeerValue struct { 99 | Peer *pbclient.Peer `json:"peer"` 100 | } 101 | 102 | type cacheKey struct { 103 | endpoint model.Endpoint 104 | role model.Role 105 | } 106 | 107 | type RelayConnKey struct { 108 | ID RelayID `json:"id"` 109 | } 110 | 111 | type RelayConnValue struct { 112 | Authentication RelayAuthentication `json:"authentication"` 113 | Hostport model.HostPort `json:"hostport"` 114 | Hostports []model.HostPort `json:"hostports"` 115 | } 116 | 117 | type RelayClientKey struct { 118 | Endpoint model.Endpoint `json:"endpoint"` 119 | Role model.Role `json:"role"` 120 | Key model.Key `json:"key"` 121 | } 122 | 123 | type RelayClientValue struct { 124 | Cert *x509.Certificate `json:"cert"` 125 | Authentication ClientAuthentication `json:"authentication"` 126 | } 127 | 128 | func (v RelayClientValue) MarshalJSON() ([]byte, error) { 129 | s := struct { 130 | Cert []byte `json:"cert"` 131 | Authentication []byte `json:"authentication"` 132 | }{ 133 | Cert: v.Cert.Raw, 134 | Authentication: v.Authentication, 135 | } 136 | return json.Marshal(s) 137 | } 138 | 139 | func (v *RelayClientValue) UnmarshalJSON(b []byte) error { 140 | s := struct { 141 | Cert []byte `json:"cert"` 142 | Authentication []byte `json:"authentication"` 143 | }{} 144 | 145 | if err := json.Unmarshal(b, &s); err != nil { 146 | return err 147 | } 148 | 149 | cert, err := x509.ParseCertificate(s.Cert) 150 | if err != nil { 151 | return err 152 | } 153 | 154 | *v = RelayClientValue{cert, s.Authentication} 155 | return nil 156 | } 157 | 158 | type RelayEndpointKey struct { 159 | Endpoint model.Endpoint `json:"endpoint"` 160 | } 161 | 162 | type RelayEndpointValue struct { 163 | Cert *x509.Certificate `json:"cert"` 164 | } 165 | 166 | func (v RelayEndpointValue) MarshalJSON() ([]byte, error) { 167 | return certc.MarshalJSONCert(v.Cert) 168 | } 169 | 170 | func (v *RelayEndpointValue) UnmarshalJSON(b []byte) error { 171 | cert, err := certc.UnmarshalJSONCert(b) 172 | if err != nil { 173 | return err 174 | } 175 | 176 | *v = RelayEndpointValue{cert} 177 | return nil 178 | } 179 | 180 | type RelayServerKey struct { 181 | Endpoint model.Endpoint `json:"endpoint"` 182 | RelayID RelayID `json:"relay_id"` 183 | } 184 | 185 | type RelayServerValue struct { 186 | Hostport model.HostPort `json:"hostport"` 187 | Hostports []model.HostPort `json:"hostports"` 188 | Cert *x509.Certificate `json:"cert"` 189 | } 190 | 191 | func (v RelayServerValue) MarshalJSON() ([]byte, error) { 192 | s := struct { 193 | Hostport model.HostPort `json:"hostport"` 194 | Hostports []model.HostPort `json:"hostports"` 195 | Cert []byte `json:"cert"` 196 | }{ 197 | Hostport: v.Hostport, 198 | Hostports: v.Hostports, 199 | Cert: v.Cert.Raw, 200 | } 201 | return json.Marshal(s) 202 | } 203 | 204 | func (v *RelayServerValue) UnmarshalJSON(b []byte) error { 205 | s := struct { 206 | Hostport model.HostPort `json:"hostport"` 207 | Hostports []model.HostPort `json:"hostports"` 208 | Cert []byte `json:"cert"` 209 | }{} 210 | 211 | if err := json.Unmarshal(b, &s); err != nil { 212 | return err 213 | } 214 | 215 | cert, err := x509.ParseCertificate(s.Cert) 216 | if err != nil { 217 | return err 218 | } 219 | 220 | *v = RelayServerValue{Hostport: s.Hostport, Hostports: s.Hostports, Cert: cert} 221 | return nil 222 | } 223 | 224 | type relayCacheValue struct { 225 | Hostports []model.HostPort 226 | Cert *x509.Certificate 227 | } 228 | -------------------------------------------------------------------------------- /endpoint.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "fmt" 7 | "log/slog" 8 | "net" 9 | "sync" 10 | "sync/atomic" 11 | 12 | "github.com/connet-dev/connet/model" 13 | "github.com/connet-dev/connet/proto" 14 | "github.com/connet-dev/connet/proto/pbclient" 15 | "github.com/connet-dev/connet/reliable" 16 | "github.com/connet-dev/connet/slogc" 17 | "github.com/connet-dev/connet/statusc" 18 | "github.com/quic-go/quic-go" 19 | "golang.org/x/sync/errgroup" 20 | ) 21 | 22 | type endpointStatus struct { 23 | Status statusc.Status 24 | StatusPeer 25 | } 26 | 27 | type endpointConfig struct { 28 | endpoint model.Endpoint 29 | role model.Role 30 | route model.RouteOption 31 | } 32 | 33 | type endpoint struct { 34 | client *Client 35 | cfg endpointConfig 36 | peer *peer 37 | 38 | ctx context.Context 39 | ctxCancel context.CancelCauseFunc 40 | closer chan struct{} 41 | 42 | onlineReport func(err error) 43 | connStatus atomic.Value 44 | 45 | logger *slog.Logger 46 | } 47 | 48 | // a client endpoint could close when: 49 | // - the user cancels the incomming context. This could happen while setting up the endpoint too. 50 | // - the user calls Close explicitly. 51 | // - the parent client is closing, so it calls close on the endpoint too. Session might be closing at the same time. 52 | // - an error happens in runPeer 53 | // - a terminal error happens in runAnnounce 54 | func newEndpoint(ctx context.Context, cl *Client, cfg endpointConfig, logger *slog.Logger) (*endpoint, error) { 55 | p, err := newPeer(cl.directServer, cl.addrs, cfg.route.AllowDirect(), logger) 56 | if err != nil { 57 | return nil, err 58 | } 59 | 60 | ctx, ctxCancel := context.WithCancelCause(ctx) 61 | ep := &endpoint{ 62 | client: cl, 63 | cfg: cfg, 64 | peer: p, 65 | 66 | ctx: ctx, 67 | ctxCancel: ctxCancel, 68 | closer: make(chan struct{}), 69 | 70 | logger: logger, 71 | } 72 | ep.connStatus.Store(statusc.NotConnected) 73 | context.AfterFunc(ctx, ep.cleanup) 74 | 75 | errCh := make(chan error) 76 | var reportOnce sync.Once 77 | ep.onlineReport = func(err error) { 78 | if err == nil { 79 | ep.connStatus.Store(statusc.Connected) 80 | } 81 | reportOnce.Do(func() { 82 | if err != nil { 83 | errCh <- err 84 | } 85 | close(errCh) 86 | }) 87 | } 88 | 89 | go ep.runPeer(ctx) 90 | go ep.runSession(ctx) 91 | 92 | select { 93 | case <-ctx.Done(): 94 | ep.ctxCancel(ctx.Err()) 95 | return nil, ctx.Err() 96 | case err := <-errCh: 97 | if err != nil { 98 | ep.ctxCancel(err) 99 | return nil, err 100 | } 101 | } 102 | 103 | return ep, nil 104 | } 105 | 106 | func (ep *endpoint) status() (endpointStatus, error) { 107 | peerStatus, err := ep.peer.status() 108 | if err != nil { 109 | return endpointStatus{}, err 110 | } 111 | return endpointStatus{ 112 | Status: ep.connStatus.Load().(statusc.Status), 113 | StatusPeer: peerStatus, 114 | }, nil 115 | } 116 | 117 | func (ep *endpoint) close() error { 118 | ep.ctxCancel(net.ErrClosed) 119 | <-ep.closer 120 | return nil 121 | } 122 | 123 | func (ep *endpoint) runPeer(ctx context.Context) { 124 | if err := ep.peer.run(ctx); err != nil { 125 | ep.ctxCancel(err) 126 | } 127 | } 128 | 129 | func (ep *endpoint) runSession(ctx context.Context) { 130 | err := ep.client.currentSession.Listen(ctx, func(sess *session) error { 131 | if sess != nil { 132 | go ep.runSessionAnnounce(ctx, sess) 133 | } 134 | return nil 135 | }) 136 | if err != nil { 137 | ep.ctxCancel(err) 138 | } 139 | } 140 | 141 | func (ep *endpoint) runSessionAnnounce(ctx context.Context, sess *session) { 142 | for { 143 | err := ep.runSessionAnnounceErr(ctx, sess) 144 | ep.connStatus.CompareAndSwap(statusc.Connected, statusc.Reconnecting) 145 | 146 | switch { 147 | case err == nil: 148 | case errors.Is(err, context.Canceled): 149 | return 150 | case sess.conn.Context().Err() != nil: 151 | return 152 | default: 153 | ep.logger.Debug("announce stopped", "err", err) 154 | } 155 | } 156 | } 157 | 158 | func (ep *endpoint) runSessionAnnounceErr(ctx context.Context, sess *session) error { 159 | if ep.cfg.route.AllowRelay() { 160 | g := reliable.NewGroup(ctx) 161 | g.Go(reliable.Bind(sess.conn, ep.runAnnounce)) 162 | g.Go(reliable.Bind(sess.conn, ep.runRelay)) 163 | return g.Wait() 164 | } 165 | 166 | return ep.runAnnounce(ctx, sess.conn) 167 | } 168 | 169 | func (ep *endpoint) runAnnounce(ctx context.Context, conn *quic.Conn) error { 170 | stream, err := conn.OpenStreamSync(ctx) 171 | if err != nil { 172 | return fmt.Errorf("announce open stream: %w", err) 173 | } 174 | defer func() { 175 | if err := stream.Close(); err != nil { 176 | slogc.Fine(ep.logger, "error closing announce stream", "err", err) 177 | } 178 | }() 179 | 180 | g, ctx := errgroup.WithContext(ctx) 181 | 182 | g.Go(func() error { 183 | <-ctx.Done() 184 | stream.CancelRead(0) 185 | return nil 186 | }) 187 | 188 | g.Go(func() error { 189 | defer ep.logger.Debug("completed announce notify") 190 | return ep.peer.selfListen(ctx, func(peer *pbclient.Peer) error { 191 | ep.logger.Debug("updated announce", "direct", len(peer.Directs), "relays", len(peer.RelayIds)) 192 | return proto.Write(stream, &pbclient.Request{ 193 | Announce: &pbclient.Request_Announce{ 194 | Endpoint: ep.cfg.endpoint.PB(), 195 | Role: ep.cfg.role.PB(), 196 | Peer: peer, 197 | }, 198 | }) 199 | }) 200 | }) 201 | 202 | g.Go(func() error { 203 | for { 204 | resp, err := pbclient.ReadResponse(stream) 205 | ep.onlineReport(err) 206 | if err != nil { 207 | return err 208 | } 209 | if resp.Announce == nil { 210 | return fmt.Errorf("announce unexpected response") 211 | } 212 | 213 | // TODO on server restart peers is reset and client loses active peers 214 | // only for them to come back at the next tick, with different ID 215 | ep.peer.setPeers(resp.Announce.Peers) 216 | } 217 | }) 218 | 219 | return g.Wait() 220 | } 221 | 222 | func (ep *endpoint) runRelay(ctx context.Context, conn *quic.Conn) error { 223 | stream, err := conn.OpenStreamSync(ctx) 224 | if err != nil { 225 | return fmt.Errorf("relay open stream: %w", err) 226 | } 227 | defer func() { 228 | if err := stream.Close(); err != nil { 229 | slogc.Fine(ep.logger, "error closing relay stream", "err", err) 230 | } 231 | }() 232 | 233 | if err := proto.Write(stream, &pbclient.Request{ 234 | Relay: &pbclient.Request_Relay{ 235 | Endpoint: ep.cfg.endpoint.PB(), 236 | Role: ep.cfg.role.PB(), 237 | ClientCertificate: ep.peer.clientCert.Leaf.Raw, 238 | }, 239 | }); err != nil { 240 | return err 241 | } 242 | 243 | g, ctx := errgroup.WithContext(ctx) 244 | 245 | g.Go(func() error { 246 | <-ctx.Done() 247 | stream.CancelRead(0) 248 | return nil 249 | }) 250 | 251 | g.Go(func() error { 252 | for { 253 | resp, err := pbclient.ReadResponse(stream) 254 | if err != nil { 255 | ep.onlineReport(err) 256 | return err 257 | } 258 | if resp.Relay == nil { 259 | return fmt.Errorf("relay unexpected response") 260 | } 261 | 262 | ep.peer.setRelays(resp.Relay.Relays) 263 | } 264 | }) 265 | 266 | return g.Wait() 267 | } 268 | 269 | func (ep *endpoint) cleanup() { 270 | defer close(ep.closer) 271 | defer ep.connStatus.Store(statusc.Disconnected) 272 | 273 | switch ep.cfg.role { 274 | case model.Destination: 275 | ep.client.removeDestination(ep.cfg.endpoint) 276 | case model.Source: 277 | ep.client.removeSource(ep.cfg.endpoint) 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /cmd/connet/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "context" 6 | "crypto/ed25519" 7 | "crypto/rand" 8 | "errors" 9 | "fmt" 10 | "io" 11 | "log/slog" 12 | "net" 13 | "os" 14 | "os/signal" 15 | "strings" 16 | "syscall" 17 | 18 | "github.com/connet-dev/connet/model" 19 | "github.com/connet-dev/connet/netc" 20 | "github.com/connet-dev/connet/slogc" 21 | "github.com/connet-dev/connet/statusc" 22 | "github.com/pelletier/go-toml/v2" 23 | "github.com/spf13/cobra" 24 | "golang.org/x/sync/errgroup" 25 | ) 26 | 27 | type Config struct { 28 | LogLevel string `toml:"log-level"` 29 | LogFormat string `toml:"log-format"` 30 | 31 | Client ClientConfig `toml:"client"` 32 | Server ServerConfig `toml:"server"` 33 | 34 | Control ControlConfig `toml:"control"` 35 | Relay RelayConfig `toml:"relay"` 36 | } 37 | 38 | func main() { 39 | ctx, cancel := signal.NotifyContext(context.Background(), 40 | syscall.SIGINT, syscall.SIGTERM) 41 | defer cancel() 42 | 43 | rootCmd := clientCmd() 44 | rootCmd.AddCommand(serverCmd()) 45 | rootCmd.AddCommand(controlCmd()) 46 | rootCmd.AddCommand(relayCmd()) 47 | rootCmd.AddCommand(checkCmd()) 48 | rootCmd.AddCommand(generateKey()) 49 | rootCmd.AddCommand(versionCmd()) 50 | 51 | if err := rootCmd.ExecuteContext(ctx); err != nil { 52 | if cerr := context.Cause(ctx); errors.Is(cerr, context.Canceled) { 53 | return 54 | } 55 | printError(err, 0) 56 | os.Exit(1) 57 | } 58 | } 59 | 60 | func printError(err error, level int) { 61 | errStr := err.Error() 62 | 63 | nextErr := errors.Unwrap(err) 64 | if nextErr != nil { 65 | errStr = strings.TrimSuffix(errStr, nextErr.Error()) 66 | errStr = strings.TrimSuffix(errStr, ": ") 67 | } 68 | 69 | fmt.Fprintf(os.Stderr, "error: %s%s\n", strings.Repeat(" ", level*2), errStr) 70 | if nextErr != nil { 71 | printError(nextErr, level+1) 72 | } 73 | } 74 | 75 | type cobraRunE = func(cmd *cobra.Command, args []string) error 76 | 77 | func wrapErr(ws string, runErr cobraRunE) cobraRunE { 78 | return func(cmd *cobra.Command, args []string) error { 79 | if err := runErr(cmd, args); err != nil { 80 | return fmt.Errorf("%s: %w", ws, err) 81 | } 82 | return nil 83 | } 84 | } 85 | 86 | func checkCmd() *cobra.Command { 87 | cmd := &cobra.Command{ 88 | Use: "check ", 89 | Short: "Check a configuration file", 90 | Args: cobra.ExactArgs(1), 91 | } 92 | 93 | cmd.RunE = wrapErr("run configuration check", func(_ *cobra.Command, args []string) error { 94 | cfg, err := loadConfigFrom(args[0]) 95 | if err != nil { 96 | return err 97 | } 98 | 99 | if _, err := logger(cfg); err != nil { 100 | return err 101 | } 102 | 103 | return nil 104 | }) 105 | 106 | return cmd 107 | } 108 | 109 | func generateKey() *cobra.Command { 110 | cmd := &cobra.Command{ 111 | Use: "gen-key", 112 | Short: "Generates ed25519 private/public key", 113 | } 114 | 115 | cmd.RunE = wrapErr("generate key", func(_ *cobra.Command, args []string) error { 116 | seed := make([]byte, ed25519.SeedSize) 117 | n, err := io.ReadFull(rand.Reader, seed) 118 | switch { 119 | case err != nil: 120 | return fmt.Errorf("rand read: %w", err) 121 | case n != ed25519.SeedSize: 122 | return fmt.Errorf("not enough data") 123 | } 124 | 125 | priv := ed25519.NewKeyFromSeed(seed) 126 | pub := priv.Public().(ed25519.PublicKey) 127 | fmt.Println("PRIVATE: ", netc.DNSSECEncoding.EncodeToString(seed)) 128 | fmt.Println("PUBLIC: ", netc.DNSSECEncoding.EncodeToString(pub)) 129 | return nil 130 | }) 131 | 132 | return cmd 133 | } 134 | 135 | func versionCmd() *cobra.Command { 136 | cmd := &cobra.Command{ 137 | Use: "version", 138 | Short: "Print version information", 139 | } 140 | 141 | cmd.RunE = wrapErr("print version", func(_ *cobra.Command, args []string) error { 142 | fmt.Println(model.BuildVersion()) 143 | return nil 144 | }) 145 | 146 | return cmd 147 | } 148 | 149 | func addConfigsFlag(cmd *cobra.Command) *[]string { 150 | return cmd.Flags().StringArray("config", nil, `configuration file(s) to load, merged when passed multiple times 151 | any explicit flags are merged last and override values from the configuration files`) 152 | } 153 | 154 | func (cfg *Config) addLogFlags(cmd *cobra.Command) { 155 | cmd.Flags().StringVar(&cfg.LogLevel, "log-level", "", "log level, one of [fine, debug, info, warn, error] (defaults to 'info')") 156 | cmd.Flags().StringVar(&cfg.LogFormat, "log-format", "", "log formatter, one of [text, json] (defaults to 'text')") 157 | } 158 | 159 | func loadConfigs(files []string) (Config, error) { 160 | var merged Config 161 | 162 | for _, f := range files { 163 | cfg, err := loadConfigFrom(f) 164 | if err != nil { 165 | return Config{}, fmt.Errorf("load config %s: %w", f, err) 166 | } 167 | merged.merge(cfg) 168 | } 169 | 170 | return merged, nil 171 | } 172 | 173 | func loadConfigFrom(file string) (Config, error) { 174 | var cfg Config 175 | 176 | f, err := os.Open(file) 177 | if err != nil { 178 | return cfg, err 179 | } 180 | 181 | dec := toml.NewDecoder(f) 182 | dec = dec.DisallowUnknownFields() 183 | err = dec.Decode(&cfg) 184 | if err != nil { 185 | var serr *toml.StrictMissingError 186 | var derr *toml.DecodeError 187 | if errors.As(err, &serr) { 188 | fmt.Println(serr.String()) 189 | } else if errors.As(err, &derr) { 190 | fmt.Println(derr.String()) 191 | } 192 | } 193 | return cfg, err 194 | } 195 | 196 | func logger(cfg Config) (*slog.Logger, error) { 197 | logger, err := slogc.New(cfg.LogLevel, cfg.LogFormat) 198 | if err != nil { 199 | return nil, err 200 | } 201 | slog.SetDefault(logger) 202 | return logger, nil 203 | } 204 | 205 | func loadTokens(tokensFile string) ([]string, error) { 206 | f, err := os.Open(tokensFile) 207 | if err != nil { 208 | return nil, fmt.Errorf("open tokens file: %w", err) 209 | } 210 | 211 | var tokens []string 212 | scanner := bufio.NewScanner(f) 213 | for scanner.Scan() { 214 | tokens = append(tokens, scanner.Text()) 215 | } 216 | if err := scanner.Err(); err != nil { 217 | return nil, fmt.Errorf("read tokens file: %w", err) 218 | } 219 | return tokens, nil 220 | } 221 | 222 | func (c *Config) merge(o Config) { 223 | c.LogLevel = override(c.LogLevel, o.LogLevel) 224 | c.LogFormat = override(c.LogFormat, o.LogFormat) 225 | 226 | c.Server.merge(o.Server) 227 | c.Client.merge(o.Client) 228 | 229 | c.Control.merge(o.Control) 230 | c.Relay.merge(o.Relay) 231 | } 232 | 233 | func override[T comparable](s, o T) (result T) { 234 | if o != result { 235 | return o 236 | } 237 | return s 238 | } 239 | 240 | func overrides[T any](s, o []T) []T { 241 | if len(o) > 0 { 242 | return o 243 | } 244 | return s 245 | } 246 | 247 | func mergeSlices[S ~[]T, T interface{ merge(T) T }](c S, o S) S { 248 | if len(c) == len(o) { 249 | for i := range c { 250 | c[i] = c[i].merge(o[i]) 251 | } 252 | } else if len(o) > 0 { 253 | return o 254 | } 255 | return c 256 | } 257 | 258 | func addStatusAddrFlag(cmd *cobra.Command, ref *string) { 259 | cmd.Flags().StringVar(ref, "status-addr", "", "status server address to listen for connections (TCP/HTTP, [host]:port) (disabled by default)") 260 | } 261 | 262 | type withStatus[T any] interface { 263 | Run(context.Context) error 264 | Status(context.Context) (T, error) 265 | } 266 | 267 | func runWithStatus[T any](ctx context.Context, srv withStatus[T], statusAddr *net.TCPAddr, logger *slog.Logger) error { 268 | if statusAddr == nil { 269 | return srv.Run(ctx) 270 | } 271 | 272 | g, ctx := errgroup.WithContext(ctx) 273 | g.Go(func() error { return srv.Run(ctx) }) 274 | g.Go(func() error { 275 | logger.Debug("running status server", "addr", statusAddr) 276 | return statusc.Run(ctx, statusAddr, srv.Status) 277 | }) 278 | return g.Wait() 279 | } 280 | -------------------------------------------------------------------------------- /config.go: -------------------------------------------------------------------------------- 1 | package connet 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/x509" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "log/slog" 10 | "net" 11 | "os" 12 | "path/filepath" 13 | "strings" 14 | 15 | "github.com/connet-dev/connet/nat" 16 | "github.com/quic-go/quic-go" 17 | ) 18 | 19 | type config struct { 20 | token string 21 | 22 | controlAddr *net.UDPAddr 23 | controlHost string 24 | controlCAs *x509.CertPool 25 | 26 | directAddr *net.UDPAddr 27 | directResetKey *quic.StatelessResetKey 28 | 29 | natPMP nat.PMPConfig 30 | 31 | logger *slog.Logger 32 | } 33 | 34 | func newConfig(opts []Option) (*config, error) { 35 | cfg := &config{ 36 | natPMP: nat.PMPConfig{ 37 | LocalResolver: nat.LocalIPSystemResolver(), 38 | GatewayResolver: nat.GatewayIPSystemResolver(), 39 | }, 40 | logger: slog.Default(), 41 | } 42 | for _, opt := range opts { 43 | if err := opt(cfg); err != nil { 44 | return nil, err 45 | } 46 | } 47 | 48 | if cfg.token == "" { 49 | if err := TokenFromEnv()(cfg); err != nil { 50 | return nil, fmt.Errorf("default token: %w", err) 51 | } 52 | } 53 | 54 | if cfg.controlAddr == nil { 55 | if err := ControlAddress("127.0.0.1:19190")(cfg); err != nil { 56 | return nil, fmt.Errorf("default control address: %w", err) 57 | } 58 | } 59 | 60 | if cfg.directAddr == nil { 61 | if err := DirectAddress(":19192")(cfg); err != nil { 62 | return nil, fmt.Errorf("default direct address: %w", err) 63 | } 64 | } 65 | 66 | if cfg.directResetKey == nil { 67 | if err := DirectStatelessResetKeyFromEnv()(cfg); err != nil { 68 | return nil, fmt.Errorf("default stateless reset key: %w", err) 69 | } 70 | if cfg.directResetKey == nil { 71 | cfg.logger.Warn("running without a stateless reset key") 72 | } 73 | } 74 | 75 | return cfg, nil 76 | } 77 | 78 | // Option is a functional option to configure the client 79 | type Option func(cfg *config) error 80 | 81 | // Token configures which token the client will use to connect to the control server 82 | func Token(token string) Option { 83 | return func(cfg *config) error { 84 | cfg.token = token 85 | return nil 86 | } 87 | } 88 | 89 | // TokenFromEnv reads from $CONNET_TOKEN and configures the client token 90 | func TokenFromEnv() Option { 91 | return func(cfg *config) error { 92 | if connetToken := os.Getenv("CONNET_TOKEN"); connetToken != "" { 93 | cfg.token = connetToken 94 | } 95 | return nil 96 | } 97 | } 98 | 99 | // ControlAddress configures the control server address 100 | func ControlAddress(address string) Option { 101 | return func(cfg *config) error { 102 | if i := strings.LastIndex(address, ":"); i < 0 { 103 | // missing :port, lets give it the default 104 | address = fmt.Sprintf("%s:%d", address, 19190) 105 | } 106 | addr, err := net.ResolveUDPAddr("udp", address) 107 | if err != nil { 108 | return fmt.Errorf("resolve control address: %w", err) 109 | } 110 | host, _, err := net.SplitHostPort(address) 111 | if err != nil { 112 | return fmt.Errorf("split control address: %w", err) 113 | } 114 | 115 | cfg.controlAddr = addr 116 | cfg.controlHost = host 117 | 118 | return nil 119 | } 120 | } 121 | 122 | // ControlCAsFile reads from a file and configures the control server CAs. Used in cases where control server is not using PKIX. 123 | func ControlCAsFile(certFile string) Option { 124 | return func(cfg *config) error { 125 | casData, err := os.ReadFile(certFile) 126 | if err != nil { 127 | return fmt.Errorf("read server CAs: %w", err) 128 | } 129 | 130 | cas := x509.NewCertPool() 131 | if !cas.AppendCertsFromPEM(casData) { 132 | return fmt.Errorf("missing server CA certificate in %s", certFile) 133 | } 134 | 135 | cfg.controlCAs = cas 136 | 137 | return nil 138 | } 139 | } 140 | 141 | // ControlCAsFile configures the control server CAs. Used in cases where control server is not using PKIX. 142 | func ControlCAs(cas *x509.CertPool) Option { 143 | return func(cfg *config) error { 144 | cfg.controlCAs = cas 145 | 146 | return nil 147 | } 148 | } 149 | 150 | // DirectAddress configures the address on which this client will listen from peer connections 151 | func DirectAddress(address string) Option { 152 | return func(cfg *config) error { 153 | addr, err := net.ResolveUDPAddr("udp", address) 154 | if err != nil { 155 | return fmt.Errorf("resolve direct address: %w", err) 156 | } 157 | 158 | cfg.directAddr = addr 159 | 160 | return nil 161 | } 162 | } 163 | 164 | // DirectStatelessResetKey configures the stateless reset key for the direct server 165 | func DirectStatelessResetKey(key *quic.StatelessResetKey) Option { 166 | return func(cfg *config) error { 167 | cfg.directResetKey = key 168 | return nil 169 | } 170 | } 171 | 172 | // DirectStatelessResetKeyFile reads from a file and configures the stateless reset key for the direct server 173 | func DirectStatelessResetKeyFile(path string) Option { 174 | return func(cfg *config) error { 175 | keyBytes, err := os.ReadFile(path) 176 | if err != nil { 177 | return fmt.Errorf("read stateless reset key: %w", err) 178 | } 179 | if len(keyBytes) < 32 { 180 | return fmt.Errorf("stateless reset key len %d", len(keyBytes)) 181 | } 182 | 183 | key := quic.StatelessResetKey(keyBytes) 184 | cfg.directResetKey = &key 185 | 186 | return nil 187 | } 188 | } 189 | 190 | // DirectStatelessResetKeyFromEnv reads stateless reset key file from the env and configures it for the direct server 191 | func DirectStatelessResetKeyFromEnv() Option { 192 | return func(cfg *config) error { 193 | var name = fmt.Sprintf("stateless-reset-%s.key", 194 | strings.TrimPrefix(strings.ReplaceAll(cfg.directAddr.String(), ":", "-"), "-")) 195 | 196 | var path string 197 | if connetCacheDir := os.Getenv("CONNET_CACHE_DIR"); connetCacheDir != "" { 198 | // Support direct override if necessary, currently used in docker 199 | path = filepath.Join(connetCacheDir, name) 200 | } else if cacheDir := os.Getenv("CACHE_DIRECTORY"); cacheDir != "" { 201 | // Supports setting up the cache directory via systemd. For reference 202 | // https://www.freedesktop.org/software/systemd/man/latest/systemd.exec.html#RuntimeDirectory= 203 | path = filepath.Join(cacheDir, name) 204 | } else if userCacheDir, err := os.UserCacheDir(); err == nil { 205 | // Look for XDG_CACHE_HOME, fallback to $HOME/.cache 206 | dir := filepath.Join(userCacheDir, "connet") 207 | switch _, err := os.Stat(dir); { 208 | case err == nil: 209 | // the directory is already there, nothing to do 210 | case errors.Is(err, os.ErrNotExist): 211 | if err := os.Mkdir(dir, 0700); err != nil { 212 | return fmt.Errorf("mkdir cache dir: %w", err) 213 | } 214 | default: 215 | return fmt.Errorf("stat cache dir: %w", err) 216 | } 217 | 218 | path = filepath.Join(dir, name) 219 | } else { 220 | return nil 221 | } 222 | 223 | switch _, err := os.Stat(path); { 224 | case err == nil: 225 | keyBytes, err := os.ReadFile(path) 226 | if err != nil { 227 | return fmt.Errorf("read stateless reset key: %w", err) 228 | } 229 | if len(keyBytes) < 32 { 230 | return fmt.Errorf("stateless reset key len %d", len(keyBytes)) 231 | } 232 | key := quic.StatelessResetKey(keyBytes) 233 | cfg.directResetKey = &key 234 | case errors.Is(err, os.ErrNotExist): 235 | var key quic.StatelessResetKey 236 | if _, err := io.ReadFull(rand.Reader, key[:]); err != nil { 237 | return fmt.Errorf("generate stateless reset key: %w", err) 238 | } 239 | if err := os.WriteFile(path, key[:], 0600); err != nil { 240 | return fmt.Errorf("write stateless reset key: %w", err) 241 | } 242 | cfg.directResetKey = &key 243 | default: 244 | return fmt.Errorf("stat stateless reset key file: %w", err) 245 | } 246 | 247 | return nil 248 | } 249 | } 250 | 251 | // NatPMPConfig configures NATPMP behavior 252 | func NatPMPConfig(pmp nat.PMPConfig) Option { 253 | return func(cfg *config) error { 254 | cfg.natPMP = pmp 255 | return nil 256 | } 257 | } 258 | 259 | // Logger configures the root logger for the client 260 | func Logger(logger *slog.Logger) Option { 261 | return func(cfg *config) error { 262 | cfg.logger = logger 263 | return nil 264 | } 265 | } 266 | --------------------------------------------------------------------------------