Skip to content

Commit c654cb0

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

File tree

2 files changed

+43
-6
lines changed

2 files changed

+43
-6
lines changed

core/commands/p2p.go

+39
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,39 @@ 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+
addr := target.String()
209+
var sport string
210+
if strings.Contains(addr, "tcp") {
211+
s, err := target.ValueForProtocol(ma.P_TCP)
212+
if err != nil {
213+
return err
214+
}
215+
sport = s
216+
} else if strings.Contains(addr, "udp") {
217+
s, err := target.ValueForProtocol(ma.P_UDP)
218+
if err != nil {
219+
return err
220+
}
221+
sport = s
222+
} else {
223+
return fmt.Errorf("address does not contain tcp or udp protocol")
224+
}
225+
226+
port, err := strconv.Atoi(sport)
227+
if err != nil {
228+
return err
229+
}
230+
231+
if port == 0 {
232+
return fmt.Errorf("port can't be 0")
233+
}
234+
235+
return nil
236+
}
237+
199238
// forwardRemote forwards libp2p service connections to a manet address
200239
func forwardRemote(ctx context.Context, p *p2p.P2P, proto protocol.ID, target ma.Multiaddr) error {
201240
// 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)