Skip to content

Commit

Permalink
Merge pull request #20 from libp2p/fix/19
Browse files Browse the repository at this point in the history
Set source port iff using reuseport
  • Loading branch information
Stebalien authored Dec 28, 2017
2 parents 5ec6564 + 69b7572 commit 1d47d21
Showing 1 changed file with 41 additions and 29 deletions.
70 changes: 41 additions & 29 deletions p2p/transport/tcp/tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,6 @@ func (t *TcpTransport) Dialer(laddr ma.Multiaddr, opts ...tpt.DialOpt) (tpt.Dial
if found {
return d, nil
}
var base manet.Dialer

la, err := manet.ToNetAddr(laddr)
if err != nil {
return nil, err // something wrong with laddr.
}
base.Dialer.LocalAddr = la

var doReuse bool
for _, o := range opts {
switch o := o.(type) {
Expand All @@ -68,7 +60,7 @@ func (t *TcpTransport) Dialer(laddr ma.Multiaddr, opts ...tpt.DialOpt) (tpt.Dial
}
}

tcpd, err := t.newTcpDialer(base, laddr, doReuse)
tcpd, err := t.newTcpDialer(laddr, doReuse)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -142,7 +134,25 @@ type tcpDialer struct {

var _ tpt.Dialer = &tcpDialer{}

func (t *TcpTransport) newTcpDialer(base manet.Dialer, laddr ma.Multiaddr, doReuse bool) (*tcpDialer, error) {
func maddrToTcp(addr ma.Multiaddr) (*net.TCPAddr, error) {
la, err := manet.ToNetAddr(addr)
if err != nil {
return nil, err // something wrong with addr.
}
latcp, ok := la.(*net.TCPAddr)
if !ok {
return nil, fmt.Errorf("not a tcp multiaddr: %s", addr)
}
return latcp, nil
}

func (t *TcpTransport) newTcpDialer(laddr ma.Multiaddr, doReuse bool) (*tcpDialer, error) {
// get the local net.Addr manually
la, err := maddrToTcp(laddr)
if err != nil {
return nil, err
}

var pattern mafmt.Pattern
if TCP4.Matches(laddr) {
pattern = TCP4
Expand All @@ -152,28 +162,30 @@ func (t *TcpTransport) newTcpDialer(base manet.Dialer, laddr ma.Multiaddr, doReu
return nil, fmt.Errorf("local addr did not match TCP4 or TCP6: %s", laddr)
}

// Ignore the port when constructing the default (non-reuseport) dialer.
labase := *la
labase.Port = 0

dialer := &tcpDialer{
laddr: laddr,
pattern: pattern,
madialer: manet.Dialer{
Dialer: net.Dialer{
LocalAddr: &labase,
},
},
transport: t,
}

if doReuse && ReuseportIsAvailable() {
rd := reuseport.Dialer{
D: base.Dialer,
dialer.doReuse = true
dialer.rd = reuseport.Dialer{
D: net.Dialer{
LocalAddr: la,
},
}

return &tcpDialer{
doReuse: true,
laddr: laddr,
rd: rd,
madialer: base,
transport: t,
pattern: pattern,
}, nil
}

return &tcpDialer{
doReuse: false,
laddr: laddr,
pattern: pattern,
madialer: base,
transport: t,
}, nil
return dialer, nil
}

func (d *tcpDialer) Dial(raddr ma.Multiaddr) (tpt.Conn, error) {
Expand Down

0 comments on commit 1d47d21

Please sign in to comment.