Skip to content

Commit

Permalink
Use the opened TcpListener/UdpConn in the remote object
Browse files Browse the repository at this point in the history
  • Loading branch information
jrouzierinverse committed Dec 18, 2024
1 parent fc4db88 commit 86a94d3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
23 changes: 14 additions & 9 deletions go/chisel/share/settings/remote.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package settings

import (
"context"
"errors"
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"

"github.com/inverse-inc/packetfence/go/reuseport"
)

// short-hand conversions (see remote_test)
Expand Down Expand Up @@ -163,27 +161,34 @@ func DecodeRemote(s string) (*Remote, error) {

func (r *Remote) setupLocalPort() error {
if r.LocalProto == "tcp" {
l, err := reuseport.ReusePortListenConfig.Listen(context.Background(), "tcp", r.LocalHost+":0")
addr, err := net.ResolveTCPAddr("tcp", r.LocalHost+":"+r.LocalPort)
if err != nil {
return fmt.Errorf("resolve: %w", err)
}

tl, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}

tl := l.(*net.TCPListener)
r.LocalPort = strconv.Itoa(tl.Addr().(*net.TCPAddr).Port)
r.ReusedTcpListener = tl
r.Dynamic = true
return nil
}

if r.LocalProto == "udp" {
l, err := reuseport.ReusePortListenConfig.ListenPacket(context.Background(), "udp", r.LocalHost+":0")
addr, err := net.ResolveUDPAddr("udp", r.Local())
if err != nil {
return err
}

uc := l.(*net.UDPConn)
r.LocalPort = strconv.Itoa(uc.LocalAddr().(*net.UDPAddr).Port)
r.ReusedUdpConn = uc
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return err
}
r.LocalPort = strconv.Itoa(conn.LocalAddr().(*net.UDPAddr).Port)
r.ReusedUdpConn = conn
r.Dynamic = true
return nil
}
Expand Down
8 changes: 8 additions & 0 deletions go/chisel/share/settings/remote_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ func TestLocalTcp(t *testing.T) {
if remote.LocalPort == "0" {
t.Fatalf("The local port was not resolved")
}

if remote.ReusedTcpListener == nil {
t.Fatalf("TCPListener not saved")
}
}

func TestLocalUdp(t *testing.T) {
Expand All @@ -54,4 +58,8 @@ func TestLocalUdp(t *testing.T) {
if remote.LocalPort == "0" {
t.Fatalf("The local port was not resolved")
}

if remote.ReusedUdpConn == nil {
t.Fatalf("UdpConn not saved")
}
}

0 comments on commit 86a94d3

Please sign in to comment.