Skip to content

Commit d3e653e

Browse files
committed
fix(p2p): issue ipfs#5523
License: MIT Signed-off-by: Overbool <[email protected]>
1 parent c4398fe commit d3e653e

File tree

2 files changed

+44
-6
lines changed

2 files changed

+44
-6
lines changed

core/commands/p2p.go

+40
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,12 @@ Example:
176176
return
177177
}
178178

179+
// port can't be 0
180+
if err := checkPort(target); err != nil {
181+
res.SetError(err, cmdkit.ErrNormal)
182+
return
183+
}
184+
179185
allowCustom, _, err := req.Option("allow-custom-protocol").Bool()
180186
if err != nil {
181187
res.SetError(err, cmdkit.ErrNormal)
@@ -196,6 +202,40 @@ Example:
196202
},
197203
}
198204

205+
// checkPort checks whether target multiaddr contains tcp or udp protocol
206+
// and whether the port is equal to 0
207+
func checkPort(target ma.Multiaddr) error {
208+
// get tcp or udp port from multiaddr
209+
getPort := func() (string, error) {
210+
sport, _ := target.ValueForProtocol(ma.P_TCP)
211+
if sport != "" {
212+
return sport, nil
213+
}
214+
215+
sport, _ = target.ValueForProtocol(ma.P_UDP)
216+
if sport != "" {
217+
return sport, nil
218+
}
219+
return "", fmt.Errorf("address does not contain tcp or udp protocol")
220+
}
221+
222+
sport, err := getPort()
223+
if err != nil {
224+
return err
225+
}
226+
227+
port, err := strconv.Atoi(sport)
228+
if err != nil {
229+
return err
230+
}
231+
232+
if port == 0 {
233+
return fmt.Errorf("port can't be 0")
234+
}
235+
236+
return nil
237+
}
238+
199239
// forwardRemote forwards libp2p service connections to a manet address
200240
func forwardRemote(ctx context.Context, p *p2p.P2P, proto protocol.ID, target ma.Multiaddr) error {
201241
// TODO: return some info

p2p/local.go

+4-6
Original file line numberDiff line numberDiff line change
@@ -28,21 +28,19 @@ type localListener struct {
2828
// ForwardLocal creates new P2P stream to a remote listener
2929
func (p2p *P2P) ForwardLocal(ctx context.Context, peer peer.ID, proto protocol.ID, bindAddr ma.Multiaddr) (Listener, error) {
3030
listener := &localListener{
31-
ctx: ctx,
32-
33-
p2p: p2p,
34-
31+
ctx: ctx,
32+
p2p: p2p,
3533
proto: proto,
36-
laddr: bindAddr,
3734
peer: peer,
3835
}
3936

40-
maListener, err := manet.Listen(listener.laddr)
37+
maListener, err := manet.Listen(bindAddr)
4138
if err != nil {
4239
return nil, err
4340
}
4441

4542
listener.listener = maListener
43+
listener.laddr = maListener.Multiaddr()
4644

4745
if err := p2p.ListenersLocal.Register(listener); err != nil {
4846
return nil, err

0 commit comments

Comments
 (0)