callbacks.go | 12 ++++++++++++ client.go | 3 +++ config.go | 2 ++ peerconn.go | 3 +++ diff --git a/callbacks.go b/callbacks.go new file mode 100644 index 0000000000000000000000000000000000000000..e6039971521c07a8298297bc29c457561f58b5ee --- /dev/null +++ b/callbacks.go @@ -0,0 +1,12 @@ +package torrent + +import ( + pp "github.com/anacrolix/torrent/peer_protocol" +) + +// These are called synchronously, and do not pass ownership. The Client and other locks may still +// be held. nil functions are not called. +type Callbacks struct { + CompletedHandshake func(_ *PeerConn, infoHash InfoHash) + ReadMessage func(*PeerConn, *pp.Message) +} diff --git a/client.go b/client.go index fe7786ac4ec96d27d7bda9d4a99e461c0e208ec0..69ef1ef5d3271b855b6153ec517b65f6b2962460 100644 --- a/client.go +++ b/client.go @@ -860,6 +860,9 @@ ret = res.Hash c.PeerExtensionBytes = res.PeerExtensionBits c.PeerID = res.PeerID c.completedHandshake = time.Now() + if cb := cl.config.Callbacks.CompletedHandshake; cb != nil { + cb(c, res.Hash) + } return } diff --git a/config.go b/config.go index ae9b4ea09b1ef6a62f558b88a824244f143f7229..c28ee124560d8e063a16d1e8e39ad19d1f5790d6 100644 --- a/config.go +++ b/config.go @@ -133,6 +133,8 @@ Extensions PeerExtensionBits DisableWebtorrent bool DisableWebseeds bool + + Callbacks Callbacks } func (cfg *ClientConfig) SetListenAddr(addr string) *ClientConfig { diff --git a/peerconn.go b/peerconn.go index 1c2879ee30940daf598c03717102548c4d24f713..aff37ff9c0eb7139346df5cc7e1ef3881d4753db 100644 --- a/peerconn.go +++ b/peerconn.go @@ -1059,6 +1059,9 @@ cl.unlock() defer cl.lock() err = decoder.Decode(&msg) }() + if cb := cl.config.Callbacks.ReadMessage; cb != nil && err == nil { + cb(c, &msg) + } if t.closed.IsSet() || c.closed.IsSet() { return nil }