Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use a random string for the mDNS peer-name #1222

Merged
merged 1 commit into from
Oct 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions p2p/discovery/mdns/mdns.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"io"
"math/rand"
"net"
"strings"
"sync"
Expand Down Expand Up @@ -37,6 +38,7 @@ type Notifee interface {
type mdnsService struct {
host host.Host
serviceName string
peerName string

// The context is canceled when Close() is called.
ctx context.Context
Expand All @@ -55,6 +57,7 @@ func NewMdnsService(host host.Host, serviceName string, notifee Notifee) *mdnsSe
s := &mdnsService{
host: host,
serviceName: serviceName,
peerName: randomString(32 + rand.Intn(32)), // generate a random string between 32 and 63 characters long
mxinden marked this conversation as resolved.
Show resolved Hide resolved
notifee: notifee,
}
s.ctx, s.ctxCancel = context.WithCancel(context.Background())
Expand Down Expand Up @@ -110,10 +113,6 @@ func (s *mdnsService) getIPs(addrs []ma.Multiaddr) ([]string, error) {
return ips, nil
}

func (s *mdnsService) mdnsInstance() string {
return string(s.host.ID())
}

func (s *mdnsService) startServer() error {
interfaceAddrs, err := s.host.Network().InterfaceListenAddresses()
if err != nil {
Expand All @@ -139,11 +138,11 @@ func (s *mdnsService) startServer() error {
}

server, err := zeroconf.RegisterProxy(
s.mdnsInstance(),
s.peerName,
s.serviceName,
mdnsDomain,
4001, // we have to pass in a port number here, but libp2p only uses the TXT records
s.host.ID().Pretty(), // TODO: deals with peer IDs longer than 63 characters
4001, // we have to pass in a port number here, but libp2p only uses the TXT records
s.peerName,
ips,
txts,
nil,
Expand Down Expand Up @@ -193,3 +192,12 @@ func (s *mdnsService) startResolver(ctx context.Context) {
}
}()
}

func randomString(l int) string {
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
s := make([]byte, 0, l)
for i := 0; i < l; i++ {
s = append(s, alphabet[rand.Intn(len(alphabet))])
}
return string(s)
}