|
| 1 | +package ping |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + "time" |
| 8 | + |
| 9 | + context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" |
| 10 | + |
| 11 | + host "github.com/ipfs/go-ipfs/p2p/host" |
| 12 | + inet "github.com/ipfs/go-ipfs/p2p/net" |
| 13 | + peer "github.com/ipfs/go-ipfs/p2p/peer" |
| 14 | + eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog" |
| 15 | + u "github.com/ipfs/go-ipfs/util" |
| 16 | +) |
| 17 | + |
| 18 | +var log = eventlog.Logger("ping") |
| 19 | + |
| 20 | +const PingSize = 32 |
| 21 | + |
| 22 | +const ID = "/ipfs/ping" |
| 23 | + |
| 24 | +type PingService struct { |
| 25 | + Host host.Host |
| 26 | +} |
| 27 | + |
| 28 | +func NewPingService(h host.Host) *PingService { |
| 29 | + ps := &PingService{h} |
| 30 | + h.SetStreamHandler(ID, ps.PingHandler) |
| 31 | + return ps |
| 32 | +} |
| 33 | + |
| 34 | +func (p *PingService) PingHandler(s inet.Stream) { |
| 35 | + buf := make([]byte, PingSize) |
| 36 | + |
| 37 | + for { |
| 38 | + _, err := io.ReadFull(s, buf) |
| 39 | + if err != nil { |
| 40 | + log.Debug(err) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + _, err = s.Write(buf) |
| 45 | + if err != nil { |
| 46 | + log.Debug(err) |
| 47 | + return |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func (ps *PingService) Ping(ctx context.Context, p peer.ID) (<-chan time.Duration, error) { |
| 53 | + s, err := ps.Host.NewStream(ID, p) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + |
| 58 | + out := make(chan time.Duration) |
| 59 | + go func() { |
| 60 | + defer close(out) |
| 61 | + for { |
| 62 | + select { |
| 63 | + case <-ctx.Done(): |
| 64 | + return |
| 65 | + default: |
| 66 | + t, err := ping(s) |
| 67 | + if err != nil { |
| 68 | + log.Debugf("ping error: %s", err) |
| 69 | + return |
| 70 | + } |
| 71 | + |
| 72 | + select { |
| 73 | + case out <- t: |
| 74 | + case <-ctx.Done(): |
| 75 | + return |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + }() |
| 80 | + |
| 81 | + return out, nil |
| 82 | +} |
| 83 | + |
| 84 | +func ping(s inet.Stream) (time.Duration, error) { |
| 85 | + buf := make([]byte, PingSize) |
| 86 | + u.NewTimeSeededRand().Read(buf) |
| 87 | + |
| 88 | + before := time.Now() |
| 89 | + _, err := s.Write(buf) |
| 90 | + if err != nil { |
| 91 | + return 0, err |
| 92 | + } |
| 93 | + |
| 94 | + rbuf := make([]byte, PingSize) |
| 95 | + _, err = io.ReadFull(s, rbuf) |
| 96 | + if err != nil { |
| 97 | + return 0, err |
| 98 | + } |
| 99 | + |
| 100 | + if !bytes.Equal(buf, rbuf) { |
| 101 | + return 0, errors.New("ping packet was incorrect!") |
| 102 | + } |
| 103 | + |
| 104 | + return time.Now().Sub(before), nil |
| 105 | +} |
0 commit comments