repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
anacrolix/torrent
metainfo/metainfo.go
UpvertedAnnounceList
func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList { if mi.AnnounceList.OverridesAnnounce(mi.Announce) { return mi.AnnounceList } if mi.Announce != "" { return [][]string{[]string{mi.Announce}} } return nil }
go
func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList { if mi.AnnounceList.OverridesAnnounce(mi.Announce) { return mi.AnnounceList } if mi.Announce != "" { return [][]string{[]string{mi.Announce}} } return nil }
[ "func", "(", "mi", "*", "MetaInfo", ")", "UpvertedAnnounceList", "(", ")", "AnnounceList", "{", "if", "mi", ".", "AnnounceList", ".", "OverridesAnnounce", "(", "mi", ".", "Announce", ")", "{", "return", "mi", ".", "AnnounceList", "\n", "}", "\n", "if", "mi", ".", "Announce", "!=", "\"", "\"", "{", "return", "[", "]", "[", "]", "string", "{", "[", "]", "string", "{", "mi", ".", "Announce", "}", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Returns the announce list converted from the old single announce field if // necessary.
[ "Returns", "the", "announce", "list", "converted", "from", "the", "old", "single", "announce", "field", "if", "necessary", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/metainfo.go#L79-L87
train
anacrolix/torrent
cmd/torrent-pick/main.go
totalBytesEstimate
func totalBytesEstimate(tc *torrent.Client) (ret int64) { var noInfo, hadInfo int64 for _, t := range tc.Torrents() { info := t.Info() if info == nil { noInfo++ continue } ret += info.TotalLength() hadInfo++ } if hadInfo != 0 { // Treat each torrent without info as the average of those with, // rounded up. ret += (noInfo*ret + hadInfo - 1) / hadInfo } return }
go
func totalBytesEstimate(tc *torrent.Client) (ret int64) { var noInfo, hadInfo int64 for _, t := range tc.Torrents() { info := t.Info() if info == nil { noInfo++ continue } ret += info.TotalLength() hadInfo++ } if hadInfo != 0 { // Treat each torrent without info as the average of those with, // rounded up. ret += (noInfo*ret + hadInfo - 1) / hadInfo } return }
[ "func", "totalBytesEstimate", "(", "tc", "*", "torrent", ".", "Client", ")", "(", "ret", "int64", ")", "{", "var", "noInfo", ",", "hadInfo", "int64", "\n", "for", "_", ",", "t", ":=", "range", "tc", ".", "Torrents", "(", ")", "{", "info", ":=", "t", ".", "Info", "(", ")", "\n", "if", "info", "==", "nil", "{", "noInfo", "++", "\n", "continue", "\n", "}", "\n", "ret", "+=", "info", ".", "TotalLength", "(", ")", "\n", "hadInfo", "++", "\n", "}", "\n", "if", "hadInfo", "!=", "0", "{", "// Treat each torrent without info as the average of those with,", "// rounded up.", "ret", "+=", "(", "noInfo", "*", "ret", "+", "hadInfo", "-", "1", ")", "/", "hadInfo", "\n", "}", "\n", "return", "\n", "}" ]
// Returns an estimate of the total bytes for all torrents.
[ "Returns", "an", "estimate", "of", "the", "total", "bytes", "for", "all", "torrents", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/cmd/torrent-pick/main.go#L51-L68
train
anacrolix/torrent
connection.go
ipv6
func (cn *connection) ipv6() bool { ip := cn.remoteAddr.IP if ip.To4() != nil { return false } return len(ip) == net.IPv6len }
go
func (cn *connection) ipv6() bool { ip := cn.remoteAddr.IP if ip.To4() != nil { return false } return len(ip) == net.IPv6len }
[ "func", "(", "cn", "*", "connection", ")", "ipv6", "(", ")", "bool", "{", "ip", ":=", "cn", ".", "remoteAddr", ".", "IP", "\n", "if", "ip", ".", "To4", "(", ")", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "len", "(", "ip", ")", "==", "net", ".", "IPv6len", "\n", "}" ]
// Returns true if the connection is over IPv6.
[ "Returns", "true", "if", "the", "connection", "is", "over", "IPv6", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L137-L143
train
anacrolix/torrent
connection.go
hasPreferredNetworkOver
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) { var ml multiLess ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection()) ml.NextBool(!l.utp(), !r.utp()) ml.NextBool(l.ipv6(), r.ipv6()) return ml.FinalOk() }
go
func (l *connection) hasPreferredNetworkOver(r *connection) (left, ok bool) { var ml multiLess ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection()) ml.NextBool(!l.utp(), !r.utp()) ml.NextBool(l.ipv6(), r.ipv6()) return ml.FinalOk() }
[ "func", "(", "l", "*", "connection", ")", "hasPreferredNetworkOver", "(", "r", "*", "connection", ")", "(", "left", ",", "ok", "bool", ")", "{", "var", "ml", "multiLess", "\n", "ml", ".", "NextBool", "(", "l", ".", "isPreferredDirection", "(", ")", ",", "r", ".", "isPreferredDirection", "(", ")", ")", "\n", "ml", ".", "NextBool", "(", "!", "l", ".", "utp", "(", ")", ",", "!", "r", ".", "utp", "(", ")", ")", "\n", "ml", ".", "NextBool", "(", "l", ".", "ipv6", "(", ")", ",", "r", ".", "ipv6", "(", ")", ")", "\n", "return", "ml", ".", "FinalOk", "(", ")", "\n", "}" ]
// Returns whether the left connection should be preferred over the right one, // considering only their networking properties. If ok is false, we can't // decide.
[ "Returns", "whether", "the", "left", "connection", "should", "be", "preferred", "over", "the", "right", "one", "considering", "only", "their", "networking", "properties", ".", "If", "ok", "is", "false", "we", "can", "t", "decide", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L154-L160
train
anacrolix/torrent
connection.go
bestPeerNumPieces
func (cn *connection) bestPeerNumPieces() pieceIndex { if cn.t.haveInfo() { return cn.t.numPieces() } return cn.peerMinPieces }
go
func (cn *connection) bestPeerNumPieces() pieceIndex { if cn.t.haveInfo() { return cn.t.numPieces() } return cn.peerMinPieces }
[ "func", "(", "cn", "*", "connection", ")", "bestPeerNumPieces", "(", ")", "pieceIndex", "{", "if", "cn", ".", "t", ".", "haveInfo", "(", ")", "{", "return", "cn", ".", "t", ".", "numPieces", "(", ")", "\n", "}", "\n", "return", "cn", ".", "peerMinPieces", "\n", "}" ]
// The best guess at number of pieces in the torrent for this peer.
[ "The", "best", "guess", "at", "number", "of", "pieces", "in", "the", "torrent", "for", "this", "peer", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L194-L199
train
anacrolix/torrent
connection.go
setNumPieces
func (cn *connection) setNumPieces(num pieceIndex) error { cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd) cn.peerPiecesChanged() return nil }
go
func (cn *connection) setNumPieces(num pieceIndex) error { cn.peerPieces.RemoveRange(bitmap.BitIndex(num), bitmap.ToEnd) cn.peerPiecesChanged() return nil }
[ "func", "(", "cn", "*", "connection", ")", "setNumPieces", "(", "num", "pieceIndex", ")", "error", "{", "cn", ".", "peerPieces", ".", "RemoveRange", "(", "bitmap", ".", "BitIndex", "(", "num", ")", ",", "bitmap", ".", "ToEnd", ")", "\n", "cn", ".", "peerPiecesChanged", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Correct the PeerPieces slice length. Return false if the existing slice is // invalid, such as by receiving badly sized BITFIELD, or invalid HAVE // messages.
[ "Correct", "the", "PeerPieces", "slice", "length", ".", "Return", "false", "if", "the", "existing", "slice", "is", "invalid", "such", "as", "by", "receiving", "badly", "sized", "BITFIELD", "or", "invalid", "HAVE", "messages", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L212-L216
train
anacrolix/torrent
connection.go
Post
func (cn *connection) Post(msg pp.Message) { torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1) // We don't need to track bytes here because a connection.w Writer wrapper // takes care of that (although there's some delay between us recording // the message, and the connection writer flushing it out.). cn.writeBuffer.Write(msg.MustMarshalBinary()) // Last I checked only Piece messages affect stats, and we don't post // those. cn.wroteMsg(&msg) cn.tickleWriter() }
go
func (cn *connection) Post(msg pp.Message) { torrent.Add(fmt.Sprintf("messages posted of type %s", msg.Type.String()), 1) // We don't need to track bytes here because a connection.w Writer wrapper // takes care of that (although there's some delay between us recording // the message, and the connection writer flushing it out.). cn.writeBuffer.Write(msg.MustMarshalBinary()) // Last I checked only Piece messages affect stats, and we don't post // those. cn.wroteMsg(&msg) cn.tickleWriter() }
[ "func", "(", "cn", "*", "connection", ")", "Post", "(", "msg", "pp", ".", "Message", ")", "{", "torrent", ".", "Add", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "Type", ".", "String", "(", ")", ")", ",", "1", ")", "\n", "// We don't need to track bytes here because a connection.w Writer wrapper", "// takes care of that (although there's some delay between us recording", "// the message, and the connection writer flushing it out.).", "cn", ".", "writeBuffer", ".", "Write", "(", "msg", ".", "MustMarshalBinary", "(", ")", ")", "\n", "// Last I checked only Piece messages affect stats, and we don't post", "// those.", "cn", ".", "wroteMsg", "(", "&", "msg", ")", "\n", "cn", ".", "tickleWriter", "(", ")", "\n", "}" ]
// Writes a message into the write buffer.
[ "Writes", "a", "message", "into", "the", "write", "buffer", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L330-L340
train
anacrolix/torrent
connection.go
nominalMaxRequests
func (cn *connection) nominalMaxRequests() (ret int) { if cn.t.requestStrategy == 3 { expectingTime := int64(cn.totalExpectingTime()) if expectingTime == 0 { expectingTime = math.MaxInt64 } else { expectingTime *= 2 } return int(clamp( 1, int64(cn.PeerMaxRequests), max( // It makes sense to always pipeline at least one connection, // since latency must be non-zero. 2, // Request only as many as we expect to receive in the // dupliateRequestTimeout window. We are trying to avoid having to // duplicate requests. cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime, ), )) } return int(clamp( 1, int64(cn.PeerMaxRequests), max(64, cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64())))) }
go
func (cn *connection) nominalMaxRequests() (ret int) { if cn.t.requestStrategy == 3 { expectingTime := int64(cn.totalExpectingTime()) if expectingTime == 0 { expectingTime = math.MaxInt64 } else { expectingTime *= 2 } return int(clamp( 1, int64(cn.PeerMaxRequests), max( // It makes sense to always pipeline at least one connection, // since latency must be non-zero. 2, // Request only as many as we expect to receive in the // dupliateRequestTimeout window. We are trying to avoid having to // duplicate requests. cn.chunksReceivedWhileExpecting*int64(cn.t.duplicateRequestTimeout)/expectingTime, ), )) } return int(clamp( 1, int64(cn.PeerMaxRequests), max(64, cn.stats.ChunksReadUseful.Int64()-(cn.stats.ChunksRead.Int64()-cn.stats.ChunksReadUseful.Int64())))) }
[ "func", "(", "cn", "*", "connection", ")", "nominalMaxRequests", "(", ")", "(", "ret", "int", ")", "{", "if", "cn", ".", "t", ".", "requestStrategy", "==", "3", "{", "expectingTime", ":=", "int64", "(", "cn", ".", "totalExpectingTime", "(", ")", ")", "\n", "if", "expectingTime", "==", "0", "{", "expectingTime", "=", "math", ".", "MaxInt64", "\n", "}", "else", "{", "expectingTime", "*=", "2", "\n", "}", "\n", "return", "int", "(", "clamp", "(", "1", ",", "int64", "(", "cn", ".", "PeerMaxRequests", ")", ",", "max", "(", "// It makes sense to always pipeline at least one connection,", "// since latency must be non-zero.", "2", ",", "// Request only as many as we expect to receive in the", "// dupliateRequestTimeout window. We are trying to avoid having to", "// duplicate requests.", "cn", ".", "chunksReceivedWhileExpecting", "*", "int64", "(", "cn", ".", "t", ".", "duplicateRequestTimeout", ")", "/", "expectingTime", ",", ")", ",", ")", ")", "\n", "}", "\n", "return", "int", "(", "clamp", "(", "1", ",", "int64", "(", "cn", ".", "PeerMaxRequests", ")", ",", "max", "(", "64", ",", "cn", ".", "stats", ".", "ChunksReadUseful", ".", "Int64", "(", ")", "-", "(", "cn", ".", "stats", ".", "ChunksRead", ".", "Int64", "(", ")", "-", "cn", ".", "stats", ".", "ChunksReadUseful", ".", "Int64", "(", ")", ")", ")", ")", ")", "\n", "}" ]
// The actual value to use as the maximum outbound requests.
[ "The", "actual", "value", "to", "use", "as", "the", "maximum", "outbound", "requests", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L375-L402
train
anacrolix/torrent
connection.go
request
func (cn *connection) request(r request, mw messageWriter) bool { if _, ok := cn.requests[r]; ok { panic("chunk already requested") } if !cn.PeerHasPiece(pieceIndex(r.Index)) { panic("requesting piece peer doesn't have") } if _, ok := cn.t.conns[cn]; !ok { panic("requesting but not in active conns") } if cn.closed.IsSet() { panic("requesting when connection is closed") } if cn.PeerChoked { if cn.peerAllowedFast.Get(int(r.Index)) { torrent.Add("allowed fast requests sent", 1) } else { panic("requesting while choked and not allowed fast") } } if cn.t.hashingPiece(pieceIndex(r.Index)) { panic("piece is being hashed") } if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) { panic("piece is queued for hash") } if cn.requests == nil { cn.requests = make(map[request]struct{}) } cn.requests[r] = struct{}{} if cn.validReceiveChunks == nil { cn.validReceiveChunks = make(map[request]struct{}) } cn.validReceiveChunks[r] = struct{}{} cn.t.pendingRequests[r]++ cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() { torrent.Add("duplicate request timeouts", 1) cn.mu().Lock() defer cn.mu().Unlock() delete(cn.t.lastRequested, r) for cn := range cn.t.conns { if cn.PeerHasPiece(pieceIndex(r.Index)) { cn.updateRequests() } } }) cn.updateExpectingChunks() return mw(pp.Message{ Type: pp.Request, Index: r.Index, Begin: r.Begin, Length: r.Length, }) }
go
func (cn *connection) request(r request, mw messageWriter) bool { if _, ok := cn.requests[r]; ok { panic("chunk already requested") } if !cn.PeerHasPiece(pieceIndex(r.Index)) { panic("requesting piece peer doesn't have") } if _, ok := cn.t.conns[cn]; !ok { panic("requesting but not in active conns") } if cn.closed.IsSet() { panic("requesting when connection is closed") } if cn.PeerChoked { if cn.peerAllowedFast.Get(int(r.Index)) { torrent.Add("allowed fast requests sent", 1) } else { panic("requesting while choked and not allowed fast") } } if cn.t.hashingPiece(pieceIndex(r.Index)) { panic("piece is being hashed") } if cn.t.pieceQueuedForHash(pieceIndex(r.Index)) { panic("piece is queued for hash") } if cn.requests == nil { cn.requests = make(map[request]struct{}) } cn.requests[r] = struct{}{} if cn.validReceiveChunks == nil { cn.validReceiveChunks = make(map[request]struct{}) } cn.validReceiveChunks[r] = struct{}{} cn.t.pendingRequests[r]++ cn.t.lastRequested[r] = time.AfterFunc(cn.t.duplicateRequestTimeout, func() { torrent.Add("duplicate request timeouts", 1) cn.mu().Lock() defer cn.mu().Unlock() delete(cn.t.lastRequested, r) for cn := range cn.t.conns { if cn.PeerHasPiece(pieceIndex(r.Index)) { cn.updateRequests() } } }) cn.updateExpectingChunks() return mw(pp.Message{ Type: pp.Request, Index: r.Index, Begin: r.Begin, Length: r.Length, }) }
[ "func", "(", "cn", "*", "connection", ")", "request", "(", "r", "request", ",", "mw", "messageWriter", ")", "bool", "{", "if", "_", ",", "ok", ":=", "cn", ".", "requests", "[", "r", "]", ";", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "cn", ".", "PeerHasPiece", "(", "pieceIndex", "(", "r", ".", "Index", ")", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "cn", ".", "t", ".", "conns", "[", "cn", "]", ";", "!", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cn", ".", "closed", ".", "IsSet", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cn", ".", "PeerChoked", "{", "if", "cn", ".", "peerAllowedFast", ".", "Get", "(", "int", "(", "r", ".", "Index", ")", ")", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "else", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "cn", ".", "t", ".", "hashingPiece", "(", "pieceIndex", "(", "r", ".", "Index", ")", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cn", ".", "t", ".", "pieceQueuedForHash", "(", "pieceIndex", "(", "r", ".", "Index", ")", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cn", ".", "requests", "==", "nil", "{", "cn", ".", "requests", "=", "make", "(", "map", "[", "request", "]", "struct", "{", "}", ")", "\n", "}", "\n", "cn", ".", "requests", "[", "r", "]", "=", "struct", "{", "}", "{", "}", "\n", "if", "cn", ".", "validReceiveChunks", "==", "nil", "{", "cn", ".", "validReceiveChunks", "=", "make", "(", "map", "[", "request", "]", "struct", "{", "}", ")", "\n", "}", "\n", "cn", ".", "validReceiveChunks", "[", "r", "]", "=", "struct", "{", "}", "{", "}", "\n", "cn", ".", "t", ".", "pendingRequests", "[", "r", "]", "++", "\n", "cn", ".", "t", ".", "lastRequested", "[", "r", "]", "=", "time", ".", "AfterFunc", "(", "cn", ".", "t", ".", "duplicateRequestTimeout", ",", "func", "(", ")", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "cn", ".", "mu", "(", ")", ".", "Lock", "(", ")", "\n", "defer", "cn", ".", "mu", "(", ")", ".", "Unlock", "(", ")", "\n", "delete", "(", "cn", ".", "t", ".", "lastRequested", ",", "r", ")", "\n", "for", "cn", ":=", "range", "cn", ".", "t", ".", "conns", "{", "if", "cn", ".", "PeerHasPiece", "(", "pieceIndex", "(", "r", ".", "Index", ")", ")", "{", "cn", ".", "updateRequests", "(", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "cn", ".", "updateExpectingChunks", "(", ")", "\n", "return", "mw", "(", "pp", ".", "Message", "{", "Type", ":", "pp", ".", "Request", ",", "Index", ":", "r", ".", "Index", ",", "Begin", ":", "r", ".", "Begin", ",", "Length", ":", "r", ".", "Length", ",", "}", ")", "\n", "}" ]
// Proxies the messageWriter's response.
[ "Proxies", "the", "messageWriter", "s", "response", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L482-L535
train
anacrolix/torrent
connection.go
writer
func (cn *connection) writer(keepAliveTimeout time.Duration) { var ( lastWrite time.Time = time.Now() keepAliveTimer *time.Timer ) keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() { cn.mu().Lock() defer cn.mu().Unlock() if time.Since(lastWrite) >= keepAliveTimeout { cn.tickleWriter() } keepAliveTimer.Reset(keepAliveTimeout) }) cn.mu().Lock() defer cn.mu().Unlock() defer cn.Close() defer keepAliveTimer.Stop() frontBuf := new(bytes.Buffer) for { if cn.closed.IsSet() { return } if cn.writeBuffer.Len() == 0 { cn.fillWriteBuffer(func(msg pp.Message) bool { cn.wroteMsg(&msg) cn.writeBuffer.Write(msg.MustMarshalBinary()) torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1) return cn.writeBuffer.Len() < 1<<16 // 64KiB }) } if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout { cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary()) postedKeepalives.Add(1) } if cn.writeBuffer.Len() == 0 { // TODO: Minimize wakeups.... cn.writerCond.Wait() continue } // Flip the buffers. frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf cn.mu().Unlock() n, err := cn.w.Write(frontBuf.Bytes()) cn.mu().Lock() if n != 0 { lastWrite = time.Now() keepAliveTimer.Reset(keepAliveTimeout) } if err != nil { return } if n != frontBuf.Len() { panic("short write") } frontBuf.Reset() } }
go
func (cn *connection) writer(keepAliveTimeout time.Duration) { var ( lastWrite time.Time = time.Now() keepAliveTimer *time.Timer ) keepAliveTimer = time.AfterFunc(keepAliveTimeout, func() { cn.mu().Lock() defer cn.mu().Unlock() if time.Since(lastWrite) >= keepAliveTimeout { cn.tickleWriter() } keepAliveTimer.Reset(keepAliveTimeout) }) cn.mu().Lock() defer cn.mu().Unlock() defer cn.Close() defer keepAliveTimer.Stop() frontBuf := new(bytes.Buffer) for { if cn.closed.IsSet() { return } if cn.writeBuffer.Len() == 0 { cn.fillWriteBuffer(func(msg pp.Message) bool { cn.wroteMsg(&msg) cn.writeBuffer.Write(msg.MustMarshalBinary()) torrent.Add(fmt.Sprintf("messages filled of type %s", msg.Type.String()), 1) return cn.writeBuffer.Len() < 1<<16 // 64KiB }) } if cn.writeBuffer.Len() == 0 && time.Since(lastWrite) >= keepAliveTimeout { cn.writeBuffer.Write(pp.Message{Keepalive: true}.MustMarshalBinary()) postedKeepalives.Add(1) } if cn.writeBuffer.Len() == 0 { // TODO: Minimize wakeups.... cn.writerCond.Wait() continue } // Flip the buffers. frontBuf, cn.writeBuffer = cn.writeBuffer, frontBuf cn.mu().Unlock() n, err := cn.w.Write(frontBuf.Bytes()) cn.mu().Lock() if n != 0 { lastWrite = time.Now() keepAliveTimer.Reset(keepAliveTimeout) } if err != nil { return } if n != frontBuf.Len() { panic("short write") } frontBuf.Reset() } }
[ "func", "(", "cn", "*", "connection", ")", "writer", "(", "keepAliveTimeout", "time", ".", "Duration", ")", "{", "var", "(", "lastWrite", "time", ".", "Time", "=", "time", ".", "Now", "(", ")", "\n", "keepAliveTimer", "*", "time", ".", "Timer", "\n", ")", "\n", "keepAliveTimer", "=", "time", ".", "AfterFunc", "(", "keepAliveTimeout", ",", "func", "(", ")", "{", "cn", ".", "mu", "(", ")", ".", "Lock", "(", ")", "\n", "defer", "cn", ".", "mu", "(", ")", ".", "Unlock", "(", ")", "\n", "if", "time", ".", "Since", "(", "lastWrite", ")", ">=", "keepAliveTimeout", "{", "cn", ".", "tickleWriter", "(", ")", "\n", "}", "\n", "keepAliveTimer", ".", "Reset", "(", "keepAliveTimeout", ")", "\n", "}", ")", "\n", "cn", ".", "mu", "(", ")", ".", "Lock", "(", ")", "\n", "defer", "cn", ".", "mu", "(", ")", ".", "Unlock", "(", ")", "\n", "defer", "cn", ".", "Close", "(", ")", "\n", "defer", "keepAliveTimer", ".", "Stop", "(", ")", "\n", "frontBuf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "for", "{", "if", "cn", ".", "closed", ".", "IsSet", "(", ")", "{", "return", "\n", "}", "\n", "if", "cn", ".", "writeBuffer", ".", "Len", "(", ")", "==", "0", "{", "cn", ".", "fillWriteBuffer", "(", "func", "(", "msg", "pp", ".", "Message", ")", "bool", "{", "cn", ".", "wroteMsg", "(", "&", "msg", ")", "\n", "cn", ".", "writeBuffer", ".", "Write", "(", "msg", ".", "MustMarshalBinary", "(", ")", ")", "\n", "torrent", ".", "Add", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "msg", ".", "Type", ".", "String", "(", ")", ")", ",", "1", ")", "\n", "return", "cn", ".", "writeBuffer", ".", "Len", "(", ")", "<", "1", "<<", "16", "// 64KiB", "\n", "}", ")", "\n", "}", "\n", "if", "cn", ".", "writeBuffer", ".", "Len", "(", ")", "==", "0", "&&", "time", ".", "Since", "(", "lastWrite", ")", ">=", "keepAliveTimeout", "{", "cn", ".", "writeBuffer", ".", "Write", "(", "pp", ".", "Message", "{", "Keepalive", ":", "true", "}", ".", "MustMarshalBinary", "(", ")", ")", "\n", "postedKeepalives", ".", "Add", "(", "1", ")", "\n", "}", "\n", "if", "cn", ".", "writeBuffer", ".", "Len", "(", ")", "==", "0", "{", "// TODO: Minimize wakeups....", "cn", ".", "writerCond", ".", "Wait", "(", ")", "\n", "continue", "\n", "}", "\n", "// Flip the buffers.", "frontBuf", ",", "cn", ".", "writeBuffer", "=", "cn", ".", "writeBuffer", ",", "frontBuf", "\n", "cn", ".", "mu", "(", ")", ".", "Unlock", "(", ")", "\n", "n", ",", "err", ":=", "cn", ".", "w", ".", "Write", "(", "frontBuf", ".", "Bytes", "(", ")", ")", "\n", "cn", ".", "mu", "(", ")", ".", "Lock", "(", ")", "\n", "if", "n", "!=", "0", "{", "lastWrite", "=", "time", ".", "Now", "(", ")", "\n", "keepAliveTimer", ".", "Reset", "(", "keepAliveTimeout", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "n", "!=", "frontBuf", ".", "Len", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "frontBuf", ".", "Reset", "(", ")", "\n", "}", "\n", "}" ]
// Routine that writes to the peer. Some of what to write is buffered by // activity elsewhere in the Client, and some is determined locally when the // connection is writable.
[ "Routine", "that", "writes", "to", "the", "peer", ".", "Some", "of", "what", "to", "write", "is", "buffered", "by", "activity", "elsewhere", "in", "the", "Client", "and", "some", "is", "determined", "locally", "when", "the", "connection", "is", "writable", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L593-L649
train
anacrolix/torrent
connection.go
iterBitmapsDistinct
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func { return func(cb iter.Callback) { for _, bm := range bms { if !iter.All(func(i interface{}) bool { skip.Add(i.(int)) return cb(i) }, bitmap.Sub(bm, *skip).Iter) { return } } } }
go
func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func { return func(cb iter.Callback) { for _, bm := range bms { if !iter.All(func(i interface{}) bool { skip.Add(i.(int)) return cb(i) }, bitmap.Sub(bm, *skip).Iter) { return } } } }
[ "func", "iterBitmapsDistinct", "(", "skip", "*", "bitmap", ".", "Bitmap", ",", "bms", "...", "bitmap", ".", "Bitmap", ")", "iter", ".", "Func", "{", "return", "func", "(", "cb", "iter", ".", "Callback", ")", "{", "for", "_", ",", "bm", ":=", "range", "bms", "{", "if", "!", "iter", ".", "All", "(", "func", "(", "i", "interface", "{", "}", ")", "bool", "{", "skip", ".", "Add", "(", "i", ".", "(", "int", ")", ")", "\n", "return", "cb", "(", "i", ")", "\n", "}", ",", "bitmap", ".", "Sub", "(", "bm", ",", "*", "skip", ")", ".", "Iter", ")", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Emits the indices in the Bitmaps bms in order, never repeating any index. // skip is mutated during execution, and its initial values will never be // emitted.
[ "Emits", "the", "indices", "in", "the", "Bitmaps", "bms", "in", "order", "never", "repeating", "any", "index", ".", "skip", "is", "mutated", "during", "execution", "and", "its", "initial", "values", "will", "never", "be", "emitted", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L684-L695
train
anacrolix/torrent
connection.go
shouldRequestWithoutBias
func (cn *connection) shouldRequestWithoutBias() bool { if cn.t.requestStrategy != 2 { return false } if len(cn.t.readers) == 0 { return false } if len(cn.t.conns) == 1 { return true } if cn == cn.t.fastestConn { return true } return false }
go
func (cn *connection) shouldRequestWithoutBias() bool { if cn.t.requestStrategy != 2 { return false } if len(cn.t.readers) == 0 { return false } if len(cn.t.conns) == 1 { return true } if cn == cn.t.fastestConn { return true } return false }
[ "func", "(", "cn", "*", "connection", ")", "shouldRequestWithoutBias", "(", ")", "bool", "{", "if", "cn", ".", "t", ".", "requestStrategy", "!=", "2", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "cn", ".", "t", ".", "readers", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "if", "len", "(", "cn", ".", "t", ".", "conns", ")", "==", "1", "{", "return", "true", "\n", "}", "\n", "if", "cn", "==", "cn", ".", "t", ".", "fastestConn", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// The connection should download highest priority pieces first, without any // inclination toward avoiding wastage. Generally we might do this if there's // a single connection, or this is the fastest connection, and we have active // readers that signal an ordering preference. It's conceivable that the best // connection should do this, since it's least likely to waste our time if // assigned to the highest priority pieces, and assigning more than one this // role would cause significant wasted bandwidth.
[ "The", "connection", "should", "download", "highest", "priority", "pieces", "first", "without", "any", "inclination", "toward", "avoiding", "wastage", ".", "Generally", "we", "might", "do", "this", "if", "there", "s", "a", "single", "connection", "or", "this", "is", "the", "fastest", "connection", "and", "we", "have", "active", "readers", "that", "signal", "an", "ordering", "preference", ".", "It", "s", "conceivable", "that", "the", "best", "connection", "should", "do", "this", "since", "it", "s", "least", "likely", "to", "waste", "our", "time", "if", "assigned", "to", "the", "highest", "priority", "pieces", "and", "assigning", "more", "than", "one", "this", "role", "would", "cause", "significant", "wasted", "bandwidth", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L738-L752
train
anacrolix/torrent
connection.go
stopRequestingPiece
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool { return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece)) }
go
func (cn *connection) stopRequestingPiece(piece pieceIndex) bool { return cn.pieceRequestOrder.Remove(bitmap.BitIndex(piece)) }
[ "func", "(", "cn", "*", "connection", ")", "stopRequestingPiece", "(", "piece", "pieceIndex", ")", "bool", "{", "return", "cn", ".", "pieceRequestOrder", ".", "Remove", "(", "bitmap", ".", "BitIndex", "(", "piece", ")", ")", "\n", "}" ]
// check callers updaterequests
[ "check", "callers", "updaterequests" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L811-L813
train
anacrolix/torrent
connection.go
updatePiecePriority
func (cn *connection) updatePiecePriority(piece pieceIndex) bool { tpp := cn.t.piecePriority(piece) if !cn.PeerHasPiece(piece) { tpp = PiecePriorityNone } if tpp == PiecePriorityNone { return cn.stopRequestingPiece(piece) } prio := cn.getPieceInclination()[piece] switch cn.t.requestStrategy { case 1: switch tpp { case PiecePriorityNormal: case PiecePriorityReadahead: prio -= int(cn.t.numPieces()) case PiecePriorityNext, PiecePriorityNow: prio -= 2 * int(cn.t.numPieces()) default: panic(tpp) } prio += int(piece / 3) default: } return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias() }
go
func (cn *connection) updatePiecePriority(piece pieceIndex) bool { tpp := cn.t.piecePriority(piece) if !cn.PeerHasPiece(piece) { tpp = PiecePriorityNone } if tpp == PiecePriorityNone { return cn.stopRequestingPiece(piece) } prio := cn.getPieceInclination()[piece] switch cn.t.requestStrategy { case 1: switch tpp { case PiecePriorityNormal: case PiecePriorityReadahead: prio -= int(cn.t.numPieces()) case PiecePriorityNext, PiecePriorityNow: prio -= 2 * int(cn.t.numPieces()) default: panic(tpp) } prio += int(piece / 3) default: } return cn.pieceRequestOrder.Set(bitmap.BitIndex(piece), prio) || cn.shouldRequestWithoutBias() }
[ "func", "(", "cn", "*", "connection", ")", "updatePiecePriority", "(", "piece", "pieceIndex", ")", "bool", "{", "tpp", ":=", "cn", ".", "t", ".", "piecePriority", "(", "piece", ")", "\n", "if", "!", "cn", ".", "PeerHasPiece", "(", "piece", ")", "{", "tpp", "=", "PiecePriorityNone", "\n", "}", "\n", "if", "tpp", "==", "PiecePriorityNone", "{", "return", "cn", ".", "stopRequestingPiece", "(", "piece", ")", "\n", "}", "\n", "prio", ":=", "cn", ".", "getPieceInclination", "(", ")", "[", "piece", "]", "\n", "switch", "cn", ".", "t", ".", "requestStrategy", "{", "case", "1", ":", "switch", "tpp", "{", "case", "PiecePriorityNormal", ":", "case", "PiecePriorityReadahead", ":", "prio", "-=", "int", "(", "cn", ".", "t", ".", "numPieces", "(", ")", ")", "\n", "case", "PiecePriorityNext", ",", "PiecePriorityNow", ":", "prio", "-=", "2", "*", "int", "(", "cn", ".", "t", ".", "numPieces", "(", ")", ")", "\n", "default", ":", "panic", "(", "tpp", ")", "\n", "}", "\n", "prio", "+=", "int", "(", "piece", "/", "3", ")", "\n", "default", ":", "}", "\n", "return", "cn", ".", "pieceRequestOrder", ".", "Set", "(", "bitmap", ".", "BitIndex", "(", "piece", ")", ",", "prio", ")", "||", "cn", ".", "shouldRequestWithoutBias", "(", ")", "\n", "}" ]
// This is distinct from Torrent piece priority, which is the user's // preference. Connection piece priority is specific to a connection and is // used to pseudorandomly avoid connections always requesting the same pieces // and thus wasting effort.
[ "This", "is", "distinct", "from", "Torrent", "piece", "priority", "which", "is", "the", "user", "s", "preference", ".", "Connection", "piece", "priority", "is", "specific", "to", "a", "connection", "and", "is", "used", "to", "pseudorandomly", "avoid", "connections", "always", "requesting", "the", "same", "pieces", "and", "thus", "wasting", "effort", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L819-L843
train
anacrolix/torrent
connection.go
postHandshakeStats
func (cn *connection) postHandshakeStats(f func(*ConnStats)) { t := cn.t f(&t.stats) f(&t.cl.stats) }
go
func (cn *connection) postHandshakeStats(f func(*ConnStats)) { t := cn.t f(&t.stats) f(&t.cl.stats) }
[ "func", "(", "cn", "*", "connection", ")", "postHandshakeStats", "(", "f", "func", "(", "*", "ConnStats", ")", ")", "{", "t", ":=", "cn", ".", "t", "\n", "f", "(", "&", "t", ".", "stats", ")", "\n", "f", "(", "&", "t", ".", "cl", ".", "stats", ")", "\n", "}" ]
// After handshake, we know what Torrent and Client stats to include for a // connection.
[ "After", "handshake", "we", "know", "what", "Torrent", "and", "Client", "stats", "to", "include", "for", "a", "connection", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L962-L966
train
anacrolix/torrent
connection.go
allStats
func (cn *connection) allStats(f func(*ConnStats)) { f(&cn.stats) if cn.reconciledHandshakeStats { cn.postHandshakeStats(f) } }
go
func (cn *connection) allStats(f func(*ConnStats)) { f(&cn.stats) if cn.reconciledHandshakeStats { cn.postHandshakeStats(f) } }
[ "func", "(", "cn", "*", "connection", ")", "allStats", "(", "f", "func", "(", "*", "ConnStats", ")", ")", "{", "f", "(", "&", "cn", ".", "stats", ")", "\n", "if", "cn", ".", "reconciledHandshakeStats", "{", "cn", ".", "postHandshakeStats", "(", "f", ")", "\n", "}", "\n", "}" ]
// All ConnStats that include this connection. Some objects are not known // until the handshake is complete, after which it's expected to reconcile the // differences.
[ "All", "ConnStats", "that", "include", "this", "connection", ".", "Some", "objects", "are", "not", "known", "until", "the", "handshake", "is", "complete", "after", "which", "it", "s", "expected", "to", "reconcile", "the", "differences", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L971-L976
train
anacrolix/torrent
connection.go
useful
func (c *connection) useful() bool { t := c.t if c.closed.IsSet() { return false } if !t.haveInfo() { return c.supportsExtension("ut_metadata") } if t.seeding() && c.PeerInterested { return true } if c.peerHasWantedPieces() { return true } return false }
go
func (c *connection) useful() bool { t := c.t if c.closed.IsSet() { return false } if !t.haveInfo() { return c.supportsExtension("ut_metadata") } if t.seeding() && c.PeerInterested { return true } if c.peerHasWantedPieces() { return true } return false }
[ "func", "(", "c", "*", "connection", ")", "useful", "(", ")", "bool", "{", "t", ":=", "c", ".", "t", "\n", "if", "c", ".", "closed", ".", "IsSet", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "!", "t", ".", "haveInfo", "(", ")", "{", "return", "c", ".", "supportsExtension", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "t", ".", "seeding", "(", ")", "&&", "c", ".", "PeerInterested", "{", "return", "true", "\n", "}", "\n", "if", "c", ".", "peerHasWantedPieces", "(", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Returns whether the connection could be useful to us. We're seeding and // they want data, we don't have metainfo and they can provide it, etc.
[ "Returns", "whether", "the", "connection", "could", "be", "useful", "to", "us", ".", "We", "re", "seeding", "and", "they", "want", "data", "we", "don", "t", "have", "metainfo", "and", "they", "can", "provide", "it", "etc", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L988-L1003
train
anacrolix/torrent
connection.go
setRW
func (cn *connection) setRW(rw io.ReadWriter) { cn.r = rw cn.w = rw }
go
func (cn *connection) setRW(rw io.ReadWriter) { cn.r = rw cn.w = rw }
[ "func", "(", "cn", "*", "connection", ")", "setRW", "(", "rw", "io", ".", "ReadWriter", ")", "{", "cn", ".", "r", "=", "rw", "\n", "cn", ".", "w", "=", "rw", "\n", "}" ]
// Set both the Reader and Writer for the connection from a single ReadWriter.
[ "Set", "both", "the", "Reader", "and", "Writer", "for", "the", "connection", "from", "a", "single", "ReadWriter", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1253-L1256
train
anacrolix/torrent
connection.go
rw
func (cn *connection) rw() io.ReadWriter { return struct { io.Reader io.Writer }{cn.r, cn.w} }
go
func (cn *connection) rw() io.ReadWriter { return struct { io.Reader io.Writer }{cn.r, cn.w} }
[ "func", "(", "cn", "*", "connection", ")", "rw", "(", ")", "io", ".", "ReadWriter", "{", "return", "struct", "{", "io", ".", "Reader", "\n", "io", ".", "Writer", "\n", "}", "{", "cn", ".", "r", ",", "cn", ".", "w", "}", "\n", "}" ]
// Returns the Reader and Writer as a combined ReadWriter.
[ "Returns", "the", "Reader", "and", "Writer", "as", "a", "combined", "ReadWriter", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1259-L1264
train
anacrolix/torrent
connection.go
upload
func (c *connection) upload(msg func(pp.Message) bool) bool { // Breaking or completing this loop means we don't want to upload to the // peer anymore, and we choke them. another: for c.uploadAllowed() { // We want to upload to the peer. if !c.Unchoke(msg) { return false } for r := range c.PeerRequests { res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length)) if !res.OK() { panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length)) } delay := res.Delay() if delay > 0 { res.Cancel() c.setRetryUploadTimer(delay) // Hard to say what to return here. return true } more, err := c.sendChunk(r, msg) if err != nil { i := pieceIndex(r.Index) if c.t.pieceComplete(i) { c.t.updatePieceCompletion(i) if !c.t.pieceComplete(i) { // We had the piece, but not anymore. break another } } log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger) // If we failed to send a chunk, choke the peer to ensure they // flush all their requests. We've probably dropped a piece, // but there's no way to communicate this to the peer. If they // ask for it again, we'll kick them to allow us to send them // an updated bitfield. break another } delete(c.PeerRequests, r) if !more { return false } goto another } return true } return c.Choke(msg) }
go
func (c *connection) upload(msg func(pp.Message) bool) bool { // Breaking or completing this loop means we don't want to upload to the // peer anymore, and we choke them. another: for c.uploadAllowed() { // We want to upload to the peer. if !c.Unchoke(msg) { return false } for r := range c.PeerRequests { res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length)) if !res.OK() { panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length)) } delay := res.Delay() if delay > 0 { res.Cancel() c.setRetryUploadTimer(delay) // Hard to say what to return here. return true } more, err := c.sendChunk(r, msg) if err != nil { i := pieceIndex(r.Index) if c.t.pieceComplete(i) { c.t.updatePieceCompletion(i) if !c.t.pieceComplete(i) { // We had the piece, but not anymore. break another } } log.Str("error sending chunk to peer").AddValues(c, r, err).Log(c.t.logger) // If we failed to send a chunk, choke the peer to ensure they // flush all their requests. We've probably dropped a piece, // but there's no way to communicate this to the peer. If they // ask for it again, we'll kick them to allow us to send them // an updated bitfield. break another } delete(c.PeerRequests, r) if !more { return false } goto another } return true } return c.Choke(msg) }
[ "func", "(", "c", "*", "connection", ")", "upload", "(", "msg", "func", "(", "pp", ".", "Message", ")", "bool", ")", "bool", "{", "// Breaking or completing this loop means we don't want to upload to the", "// peer anymore, and we choke them.", "another", ":", "for", "c", ".", "uploadAllowed", "(", ")", "{", "// We want to upload to the peer.", "if", "!", "c", ".", "Unchoke", "(", "msg", ")", "{", "return", "false", "\n", "}", "\n", "for", "r", ":=", "range", "c", ".", "PeerRequests", "{", "res", ":=", "c", ".", "t", ".", "cl", ".", "config", ".", "UploadRateLimiter", ".", "ReserveN", "(", "time", ".", "Now", "(", ")", ",", "int", "(", "r", ".", "Length", ")", ")", "\n", "if", "!", "res", ".", "OK", "(", ")", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "r", ".", "Length", ")", ")", "\n", "}", "\n", "delay", ":=", "res", ".", "Delay", "(", ")", "\n", "if", "delay", ">", "0", "{", "res", ".", "Cancel", "(", ")", "\n", "c", ".", "setRetryUploadTimer", "(", "delay", ")", "\n", "// Hard to say what to return here.", "return", "true", "\n", "}", "\n", "more", ",", "err", ":=", "c", ".", "sendChunk", "(", "r", ",", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "i", ":=", "pieceIndex", "(", "r", ".", "Index", ")", "\n", "if", "c", ".", "t", ".", "pieceComplete", "(", "i", ")", "{", "c", ".", "t", ".", "updatePieceCompletion", "(", "i", ")", "\n", "if", "!", "c", ".", "t", ".", "pieceComplete", "(", "i", ")", "{", "// We had the piece, but not anymore.", "break", "another", "\n", "}", "\n", "}", "\n", "log", ".", "Str", "(", "\"", "\"", ")", ".", "AddValues", "(", "c", ",", "r", ",", "err", ")", ".", "Log", "(", "c", ".", "t", ".", "logger", ")", "\n", "// If we failed to send a chunk, choke the peer to ensure they", "// flush all their requests. We've probably dropped a piece,", "// but there's no way to communicate this to the peer. If they", "// ask for it again, we'll kick them to allow us to send them", "// an updated bitfield.", "break", "another", "\n", "}", "\n", "delete", "(", "c", ".", "PeerRequests", ",", "r", ")", "\n", "if", "!", "more", "{", "return", "false", "\n", "}", "\n", "goto", "another", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "return", "c", ".", "Choke", "(", "msg", ")", "\n", "}" ]
// Also handles choking and unchoking of the remote peer.
[ "Also", "handles", "choking", "and", "unchoking", "of", "the", "remote", "peer", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/connection.go#L1400-L1448
train
anacrolix/torrent
iplist/iplist.go
Lookup
func (ipl *IPList) Lookup(ip net.IP) (r Range, ok bool) { if ipl == nil { return } // TODO: Perhaps all addresses should be converted to IPv6, if the future // of IP is to always be backwards compatible. But this will cost 4x the // memory for IPv4 addresses? v4 := ip.To4() if v4 != nil { r, ok = ipl.lookup(v4) if ok { return } } v6 := ip.To16() if v6 != nil { return ipl.lookup(v6) } if v4 == nil && v6 == nil { r = Range{ Description: "bad IP", } ok = true } return }
go
func (ipl *IPList) Lookup(ip net.IP) (r Range, ok bool) { if ipl == nil { return } // TODO: Perhaps all addresses should be converted to IPv6, if the future // of IP is to always be backwards compatible. But this will cost 4x the // memory for IPv4 addresses? v4 := ip.To4() if v4 != nil { r, ok = ipl.lookup(v4) if ok { return } } v6 := ip.To16() if v6 != nil { return ipl.lookup(v6) } if v4 == nil && v6 == nil { r = Range{ Description: "bad IP", } ok = true } return }
[ "func", "(", "ipl", "*", "IPList", ")", "Lookup", "(", "ip", "net", ".", "IP", ")", "(", "r", "Range", ",", "ok", "bool", ")", "{", "if", "ipl", "==", "nil", "{", "return", "\n", "}", "\n", "// TODO: Perhaps all addresses should be converted to IPv6, if the future", "// of IP is to always be backwards compatible. But this will cost 4x the", "// memory for IPv4 addresses?", "v4", ":=", "ip", ".", "To4", "(", ")", "\n", "if", "v4", "!=", "nil", "{", "r", ",", "ok", "=", "ipl", ".", "lookup", "(", "v4", ")", "\n", "if", "ok", "{", "return", "\n", "}", "\n", "}", "\n", "v6", ":=", "ip", ".", "To16", "(", ")", "\n", "if", "v6", "!=", "nil", "{", "return", "ipl", ".", "lookup", "(", "v6", ")", "\n", "}", "\n", "if", "v4", "==", "nil", "&&", "v6", "==", "nil", "{", "r", "=", "Range", "{", "Description", ":", "\"", "\"", ",", "}", "\n", "ok", "=", "true", "\n", "}", "\n", "return", "\n", "}" ]
// Return the range the given IP is in. ok if false if no range is found.
[ "Return", "the", "range", "the", "given", "IP", "is", "in", ".", "ok", "if", "false", "if", "no", "range", "is", "found", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L53-L78
train
anacrolix/torrent
iplist/iplist.go
lookup
func lookup( first func(i int) net.IP, full func(i int) Range, n int, ip net.IP, ) ( r Range, ok bool, ) { // Find the index of the first range for which the following range exceeds // it. i := sort.Search(n, func(i int) bool { if i+1 >= n { return true } return bytes.Compare(ip, first(i+1)) < 0 }) if i == n { return } r = full(i) ok = bytes.Compare(r.First, ip) <= 0 && bytes.Compare(ip, r.Last) <= 0 return }
go
func lookup( first func(i int) net.IP, full func(i int) Range, n int, ip net.IP, ) ( r Range, ok bool, ) { // Find the index of the first range for which the following range exceeds // it. i := sort.Search(n, func(i int) bool { if i+1 >= n { return true } return bytes.Compare(ip, first(i+1)) < 0 }) if i == n { return } r = full(i) ok = bytes.Compare(r.First, ip) <= 0 && bytes.Compare(ip, r.Last) <= 0 return }
[ "func", "lookup", "(", "first", "func", "(", "i", "int", ")", "net", ".", "IP", ",", "full", "func", "(", "i", "int", ")", "Range", ",", "n", "int", ",", "ip", "net", ".", "IP", ",", ")", "(", "r", "Range", ",", "ok", "bool", ",", ")", "{", "// Find the index of the first range for which the following range exceeds", "// it.", "i", ":=", "sort", ".", "Search", "(", "n", ",", "func", "(", "i", "int", ")", "bool", "{", "if", "i", "+", "1", ">=", "n", "{", "return", "true", "\n", "}", "\n", "return", "bytes", ".", "Compare", "(", "ip", ",", "first", "(", "i", "+", "1", ")", ")", "<", "0", "\n", "}", ")", "\n", "if", "i", "==", "n", "{", "return", "\n", "}", "\n", "r", "=", "full", "(", "i", ")", "\n", "ok", "=", "bytes", ".", "Compare", "(", "r", ".", "First", ",", "ip", ")", "<=", "0", "&&", "bytes", ".", "Compare", "(", "ip", ",", "r", ".", "Last", ")", "<=", "0", "\n", "return", "\n", "}" ]
// Return a range that contains ip, or nil.
[ "Return", "a", "range", "that", "contains", "ip", "or", "nil", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L81-L103
train
anacrolix/torrent
iplist/iplist.go
lookup
func (ipl *IPList) lookup(ip net.IP) (Range, bool) { return lookup(func(i int) net.IP { return ipl.ranges[i].First }, func(i int) Range { return ipl.ranges[i] }, len(ipl.ranges), ip) }
go
func (ipl *IPList) lookup(ip net.IP) (Range, bool) { return lookup(func(i int) net.IP { return ipl.ranges[i].First }, func(i int) Range { return ipl.ranges[i] }, len(ipl.ranges), ip) }
[ "func", "(", "ipl", "*", "IPList", ")", "lookup", "(", "ip", "net", ".", "IP", ")", "(", "Range", ",", "bool", ")", "{", "return", "lookup", "(", "func", "(", "i", "int", ")", "net", ".", "IP", "{", "return", "ipl", ".", "ranges", "[", "i", "]", ".", "First", "\n", "}", ",", "func", "(", "i", "int", ")", "Range", "{", "return", "ipl", ".", "ranges", "[", "i", "]", "\n", "}", ",", "len", "(", "ipl", ".", "ranges", ")", ",", "ip", ")", "\n", "}" ]
// Return the range the given IP is in. Returns nil if no range is found.
[ "Return", "the", "range", "the", "given", "IP", "is", "in", ".", "Returns", "nil", "if", "no", "range", "is", "found", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L106-L112
train
anacrolix/torrent
iplist/iplist.go
NewFromReader
func NewFromReader(f io.Reader) (ret *IPList, err error) { var ranges []Range // There's a lot of similar descriptions, so we maintain a pool and reuse // them to reduce memory overhead. uniqStrs := make(map[string]string) scanner := bufio.NewScanner(f) lineNum := 1 for scanner.Scan() { r, ok, lineErr := ParseBlocklistP2PLine(scanner.Bytes()) if lineErr != nil { err = fmt.Errorf("error parsing line %d: %s", lineNum, lineErr) return } lineNum++ if !ok { continue } if s, ok := uniqStrs[r.Description]; ok { r.Description = s } else { uniqStrs[r.Description] = r.Description } ranges = append(ranges, r) } err = scanner.Err() if err != nil { return } ret = New(ranges) return }
go
func NewFromReader(f io.Reader) (ret *IPList, err error) { var ranges []Range // There's a lot of similar descriptions, so we maintain a pool and reuse // them to reduce memory overhead. uniqStrs := make(map[string]string) scanner := bufio.NewScanner(f) lineNum := 1 for scanner.Scan() { r, ok, lineErr := ParseBlocklistP2PLine(scanner.Bytes()) if lineErr != nil { err = fmt.Errorf("error parsing line %d: %s", lineNum, lineErr) return } lineNum++ if !ok { continue } if s, ok := uniqStrs[r.Description]; ok { r.Description = s } else { uniqStrs[r.Description] = r.Description } ranges = append(ranges, r) } err = scanner.Err() if err != nil { return } ret = New(ranges) return }
[ "func", "NewFromReader", "(", "f", "io", ".", "Reader", ")", "(", "ret", "*", "IPList", ",", "err", "error", ")", "{", "var", "ranges", "[", "]", "Range", "\n", "// There's a lot of similar descriptions, so we maintain a pool and reuse", "// them to reduce memory overhead.", "uniqStrs", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "lineNum", ":=", "1", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "r", ",", "ok", ",", "lineErr", ":=", "ParseBlocklistP2PLine", "(", "scanner", ".", "Bytes", "(", ")", ")", "\n", "if", "lineErr", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "lineNum", ",", "lineErr", ")", "\n", "return", "\n", "}", "\n", "lineNum", "++", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "s", ",", "ok", ":=", "uniqStrs", "[", "r", ".", "Description", "]", ";", "ok", "{", "r", ".", "Description", "=", "s", "\n", "}", "else", "{", "uniqStrs", "[", "r", ".", "Description", "]", "=", "r", ".", "Description", "\n", "}", "\n", "ranges", "=", "append", "(", "ranges", ",", "r", ")", "\n", "}", "\n", "err", "=", "scanner", ".", "Err", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "ret", "=", "New", "(", "ranges", ")", "\n", "return", "\n", "}" ]
// Creates an IPList from a line-delimited P2P Plaintext file.
[ "Creates", "an", "IPList", "from", "a", "line", "-", "delimited", "P2P", "Plaintext", "file", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/iplist.go#L155-L185
train
anacrolix/torrent
bencode/api.go
Unmarshal
func Unmarshal(data []byte, v interface{}) (err error) { buf := bytes.NewBuffer(data) e := Decoder{r: buf} err = e.Decode(v) if err == nil && buf.Len() != 0 { err = ErrUnusedTrailingBytes{buf.Len()} } return }
go
func Unmarshal(data []byte, v interface{}) (err error) { buf := bytes.NewBuffer(data) e := Decoder{r: buf} err = e.Decode(v) if err == nil && buf.Len() != 0 { err = ErrUnusedTrailingBytes{buf.Len()} } return }
[ "func", "Unmarshal", "(", "data", "[", "]", "byte", ",", "v", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "data", ")", "\n", "e", ":=", "Decoder", "{", "r", ":", "buf", "}", "\n", "err", "=", "e", ".", "Decode", "(", "v", ")", "\n", "if", "err", "==", "nil", "&&", "buf", ".", "Len", "(", ")", "!=", "0", "{", "err", "=", "ErrUnusedTrailingBytes", "{", "buf", ".", "Len", "(", ")", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Unmarshal the bencode value in the 'data' to a value pointed by the 'v' // pointer, return a non-nil error if any.
[ "Unmarshal", "the", "bencode", "value", "in", "the", "data", "to", "a", "value", "pointed", "by", "the", "v", "pointer", "return", "a", "non", "-", "nil", "error", "if", "any", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/api.go#L133-L141
train
anacrolix/torrent
reader.go
SetResponsive
func (r *reader) SetResponsive() { r.responsive = true r.t.cl.event.Broadcast() }
go
func (r *reader) SetResponsive() { r.responsive = true r.t.cl.event.Broadcast() }
[ "func", "(", "r", "*", "reader", ")", "SetResponsive", "(", ")", "{", "r", ".", "responsive", "=", "true", "\n", "r", ".", "t", ".", "cl", ".", "event", ".", "Broadcast", "(", ")", "\n", "}" ]
// Don't wait for pieces to complete and be verified. Read calls return as // soon as they can when the underlying chunks become available.
[ "Don", "t", "wait", "for", "pieces", "to", "complete", "and", "be", "verified", ".", "Read", "calls", "return", "as", "soon", "as", "they", "can", "when", "the", "underlying", "chunks", "become", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L54-L57
train
anacrolix/torrent
reader.go
SetReadahead
func (r *reader) SetReadahead(readahead int64) { r.mu.Lock() r.readahead = readahead r.mu.Unlock() r.t.cl.lock() defer r.t.cl.unlock() r.posChanged() }
go
func (r *reader) SetReadahead(readahead int64) { r.mu.Lock() r.readahead = readahead r.mu.Unlock() r.t.cl.lock() defer r.t.cl.unlock() r.posChanged() }
[ "func", "(", "r", "*", "reader", ")", "SetReadahead", "(", "readahead", "int64", ")", "{", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "r", ".", "readahead", "=", "readahead", "\n", "r", ".", "mu", ".", "Unlock", "(", ")", "\n", "r", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "r", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "r", ".", "posChanged", "(", ")", "\n", "}" ]
// Configure the number of bytes ahead of a read that should also be // prioritized in preparation for further reads.
[ "Configure", "the", "number", "of", "bytes", "ahead", "of", "a", "read", "that", "should", "also", "be", "prioritized", "in", "preparation", "for", "further", "reads", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L67-L74
train
anacrolix/torrent
reader.go
available
func (r *reader) available(off, max int64) (ret int64) { off += r.offset for max > 0 { req, ok := r.t.offsetRequest(off) if !ok { break } if !r.t.haveChunk(req) { break } len1 := int64(req.Length) - (off - r.t.requestOffset(req)) max -= len1 ret += len1 off += len1 } // Ensure that ret hasn't exceeded our original max. if max < 0 { ret += max } return }
go
func (r *reader) available(off, max int64) (ret int64) { off += r.offset for max > 0 { req, ok := r.t.offsetRequest(off) if !ok { break } if !r.t.haveChunk(req) { break } len1 := int64(req.Length) - (off - r.t.requestOffset(req)) max -= len1 ret += len1 off += len1 } // Ensure that ret hasn't exceeded our original max. if max < 0 { ret += max } return }
[ "func", "(", "r", "*", "reader", ")", "available", "(", "off", ",", "max", "int64", ")", "(", "ret", "int64", ")", "{", "off", "+=", "r", ".", "offset", "\n", "for", "max", ">", "0", "{", "req", ",", "ok", ":=", "r", ".", "t", ".", "offsetRequest", "(", "off", ")", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "if", "!", "r", ".", "t", ".", "haveChunk", "(", "req", ")", "{", "break", "\n", "}", "\n", "len1", ":=", "int64", "(", "req", ".", "Length", ")", "-", "(", "off", "-", "r", ".", "t", ".", "requestOffset", "(", "req", ")", ")", "\n", "max", "-=", "len1", "\n", "ret", "+=", "len1", "\n", "off", "+=", "len1", "\n", "}", "\n", "// Ensure that ret hasn't exceeded our original max.", "if", "max", "<", "0", "{", "ret", "+=", "max", "\n", "}", "\n", "return", "\n", "}" ]
// How many bytes are available to read. Max is the most we could require.
[ "How", "many", "bytes", "are", "available", "to", "read", ".", "Max", "is", "the", "most", "we", "could", "require", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L91-L111
train
anacrolix/torrent
reader.go
piecesUncached
func (r *reader) piecesUncached() (ret pieceRange) { ra := r.readahead if ra < 1 { // Needs to be at least 1, because [x, x) means we don't want // anything. ra = 1 } if ra > r.length-r.pos { ra = r.length - r.pos } ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra) return }
go
func (r *reader) piecesUncached() (ret pieceRange) { ra := r.readahead if ra < 1 { // Needs to be at least 1, because [x, x) means we don't want // anything. ra = 1 } if ra > r.length-r.pos { ra = r.length - r.pos } ret.begin, ret.end = r.t.byteRegionPieces(r.torrentOffset(r.pos), ra) return }
[ "func", "(", "r", "*", "reader", ")", "piecesUncached", "(", ")", "(", "ret", "pieceRange", ")", "{", "ra", ":=", "r", ".", "readahead", "\n", "if", "ra", "<", "1", "{", "// Needs to be at least 1, because [x, x) means we don't want", "// anything.", "ra", "=", "1", "\n", "}", "\n", "if", "ra", ">", "r", ".", "length", "-", "r", ".", "pos", "{", "ra", "=", "r", ".", "length", "-", "r", ".", "pos", "\n", "}", "\n", "ret", ".", "begin", ",", "ret", ".", "end", "=", "r", ".", "t", ".", "byteRegionPieces", "(", "r", ".", "torrentOffset", "(", "r", ".", "pos", ")", ",", "ra", ")", "\n", "return", "\n", "}" ]
// Calculates the pieces this reader wants downloaded, ignoring the cached // value at r.pieces.
[ "Calculates", "the", "pieces", "this", "reader", "wants", "downloaded", "ignoring", "the", "cached", "value", "at", "r", ".", "pieces", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L121-L133
train
anacrolix/torrent
reader.go
waitAvailable
func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) { r.t.cl.lock() defer r.t.cl.unlock() for !r.readable(pos) && *ctxErr == nil { r.waitReadable(pos) } return r.available(pos, wanted) }
go
func (r *reader) waitAvailable(pos, wanted int64, ctxErr *error) (avail int64) { r.t.cl.lock() defer r.t.cl.unlock() for !r.readable(pos) && *ctxErr == nil { r.waitReadable(pos) } return r.available(pos, wanted) }
[ "func", "(", "r", "*", "reader", ")", "waitAvailable", "(", "pos", ",", "wanted", "int64", ",", "ctxErr", "*", "error", ")", "(", "avail", "int64", ")", "{", "r", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "r", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "for", "!", "r", ".", "readable", "(", "pos", ")", "&&", "*", "ctxErr", "==", "nil", "{", "r", ".", "waitReadable", "(", "pos", ")", "\n", "}", "\n", "return", "r", ".", "available", "(", "pos", ",", "wanted", ")", "\n", "}" ]
// Wait until some data should be available to read. Tickles the client if it // isn't. Returns how much should be readable without blocking.
[ "Wait", "until", "some", "data", "should", "be", "available", "to", "read", ".", "Tickles", "the", "client", "if", "it", "isn", "t", ".", "Returns", "how", "much", "should", "be", "readable", "without", "blocking", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L184-L191
train
anacrolix/torrent
reader.go
readOnceAt
func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) { if pos >= r.length { err = io.EOF return } for { avail := r.waitAvailable(pos, int64(len(b)), ctxErr) if avail == 0 { if r.t.closed.IsSet() { err = errors.New("torrent closed") return } if *ctxErr != nil { err = *ctxErr return } } pi := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength) ip := r.t.info.Piece(pi) po := r.torrentOffset(pos) % r.t.info.PieceLength b1 := missinggo.LimitLen(b, ip.Length()-po, avail) n, err = r.t.readAt(b1, r.torrentOffset(pos)) if n != 0 { err = nil return } r.t.cl.lock() // TODO: Just reset pieces in the readahead window. This might help // prevent thrashing with small caches and file and piece priorities. log.Printf("error reading torrent %s piece %d offset %d, %d bytes: %v", r.t.infoHash.HexString(), pi, po, len(b1), err) if !r.t.updatePieceCompletion(pi) { log.Printf("piece %d completion unchanged", pi) } r.t.cl.unlock() } }
go
func (r *reader) readOnceAt(b []byte, pos int64, ctxErr *error) (n int, err error) { if pos >= r.length { err = io.EOF return } for { avail := r.waitAvailable(pos, int64(len(b)), ctxErr) if avail == 0 { if r.t.closed.IsSet() { err = errors.New("torrent closed") return } if *ctxErr != nil { err = *ctxErr return } } pi := pieceIndex(r.torrentOffset(pos) / r.t.info.PieceLength) ip := r.t.info.Piece(pi) po := r.torrentOffset(pos) % r.t.info.PieceLength b1 := missinggo.LimitLen(b, ip.Length()-po, avail) n, err = r.t.readAt(b1, r.torrentOffset(pos)) if n != 0 { err = nil return } r.t.cl.lock() // TODO: Just reset pieces in the readahead window. This might help // prevent thrashing with small caches and file and piece priorities. log.Printf("error reading torrent %s piece %d offset %d, %d bytes: %v", r.t.infoHash.HexString(), pi, po, len(b1), err) if !r.t.updatePieceCompletion(pi) { log.Printf("piece %d completion unchanged", pi) } r.t.cl.unlock() } }
[ "func", "(", "r", "*", "reader", ")", "readOnceAt", "(", "b", "[", "]", "byte", ",", "pos", "int64", ",", "ctxErr", "*", "error", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "pos", ">=", "r", ".", "length", "{", "err", "=", "io", ".", "EOF", "\n", "return", "\n", "}", "\n", "for", "{", "avail", ":=", "r", ".", "waitAvailable", "(", "pos", ",", "int64", "(", "len", "(", "b", ")", ")", ",", "ctxErr", ")", "\n", "if", "avail", "==", "0", "{", "if", "r", ".", "t", ".", "closed", ".", "IsSet", "(", ")", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "if", "*", "ctxErr", "!=", "nil", "{", "err", "=", "*", "ctxErr", "\n", "return", "\n", "}", "\n", "}", "\n", "pi", ":=", "pieceIndex", "(", "r", ".", "torrentOffset", "(", "pos", ")", "/", "r", ".", "t", ".", "info", ".", "PieceLength", ")", "\n", "ip", ":=", "r", ".", "t", ".", "info", ".", "Piece", "(", "pi", ")", "\n", "po", ":=", "r", ".", "torrentOffset", "(", "pos", ")", "%", "r", ".", "t", ".", "info", ".", "PieceLength", "\n", "b1", ":=", "missinggo", ".", "LimitLen", "(", "b", ",", "ip", ".", "Length", "(", ")", "-", "po", ",", "avail", ")", "\n", "n", ",", "err", "=", "r", ".", "t", ".", "readAt", "(", "b1", ",", "r", ".", "torrentOffset", "(", "pos", ")", ")", "\n", "if", "n", "!=", "0", "{", "err", "=", "nil", "\n", "return", "\n", "}", "\n", "r", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "// TODO: Just reset pieces in the readahead window. This might help", "// prevent thrashing with small caches and file and piece priorities.", "log", ".", "Printf", "(", "\"", "\"", ",", "r", ".", "t", ".", "infoHash", ".", "HexString", "(", ")", ",", "pi", ",", "po", ",", "len", "(", "b1", ")", ",", "err", ")", "\n", "if", "!", "r", ".", "t", ".", "updatePieceCompletion", "(", "pi", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "pi", ")", "\n", "}", "\n", "r", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "}", "\n", "}" ]
// Performs at most one successful read to torrent storage.
[ "Performs", "at", "most", "one", "successful", "read", "to", "torrent", "storage", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/reader.go#L198-L234
train
anacrolix/torrent
tracker/udp.go
write
func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) { var buf bytes.Buffer err = binary.Write(&buf, binary.BigEndian, h) if err != nil { panic(err) } if body != nil { err = binary.Write(&buf, binary.BigEndian, body) if err != nil { panic(err) } } _, err = buf.Write(trailer) if err != nil { return } n, err := c.socket.Write(buf.Bytes()) if err != nil { return } if n != buf.Len() { panic("write should send all or error") } return }
go
func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) { var buf bytes.Buffer err = binary.Write(&buf, binary.BigEndian, h) if err != nil { panic(err) } if body != nil { err = binary.Write(&buf, binary.BigEndian, body) if err != nil { panic(err) } } _, err = buf.Write(trailer) if err != nil { return } n, err := c.socket.Write(buf.Bytes()) if err != nil { return } if n != buf.Len() { panic("write should send all or error") } return }
[ "func", "(", "c", "*", "udpAnnounce", ")", "write", "(", "h", "*", "RequestHeader", ",", "body", "interface", "{", "}", ",", "trailer", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "err", "=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "h", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "if", "body", "!=", "nil", "{", "err", "=", "binary", ".", "Write", "(", "&", "buf", ",", "binary", ".", "BigEndian", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "buf", ".", "Write", "(", "trailer", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "n", ",", "err", ":=", "c", ".", "socket", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "n", "!=", "buf", ".", "Len", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\n", "}" ]
// body is the binary serializable request body. trailer is optional data // following it, such as for BEP 41.
[ "body", "is", "the", "binary", "serializable", "request", "body", ".", "trailer", "is", "optional", "data", "following", "it", "such", "as", "for", "BEP", "41", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L156-L180
train
anacrolix/torrent
tracker/udp.go
request
func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) { tid := newTransactionId() if err := errors.Wrap( c.write( &RequestHeader{ ConnectionId: c.connectionId, Action: action, TransactionId: tid, }, args, options), "writing request", ); err != nil { return nil, err } c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts))) b := make([]byte, 0x800) // 2KiB for { var ( n int readErr error readDone = make(chan struct{}) ) go func() { defer close(readDone) n, readErr = c.socket.Read(b) }() ctx := c.a.Context if ctx == nil { ctx = context.Background() } select { case <-ctx.Done(): return nil, ctx.Err() case <-readDone: } if opE, ok := readErr.(*net.OpError); ok && opE.Timeout() { c.contiguousTimeouts++ } if readErr != nil { return nil, errors.Wrap(readErr, "reading from socket") } buf := bytes.NewBuffer(b[:n]) var h ResponseHeader err := binary.Read(buf, binary.BigEndian, &h) switch err { default: panic(err) case io.ErrUnexpectedEOF, io.EOF: continue case nil: } if h.TransactionId != tid { continue } c.contiguousTimeouts = 0 if h.Action == ActionError { err = errors.New(buf.String()) } return buf, err } }
go
func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) { tid := newTransactionId() if err := errors.Wrap( c.write( &RequestHeader{ ConnectionId: c.connectionId, Action: action, TransactionId: tid, }, args, options), "writing request", ); err != nil { return nil, err } c.socket.SetReadDeadline(time.Now().Add(timeout(c.contiguousTimeouts))) b := make([]byte, 0x800) // 2KiB for { var ( n int readErr error readDone = make(chan struct{}) ) go func() { defer close(readDone) n, readErr = c.socket.Read(b) }() ctx := c.a.Context if ctx == nil { ctx = context.Background() } select { case <-ctx.Done(): return nil, ctx.Err() case <-readDone: } if opE, ok := readErr.(*net.OpError); ok && opE.Timeout() { c.contiguousTimeouts++ } if readErr != nil { return nil, errors.Wrap(readErr, "reading from socket") } buf := bytes.NewBuffer(b[:n]) var h ResponseHeader err := binary.Read(buf, binary.BigEndian, &h) switch err { default: panic(err) case io.ErrUnexpectedEOF, io.EOF: continue case nil: } if h.TransactionId != tid { continue } c.contiguousTimeouts = 0 if h.Action == ActionError { err = errors.New(buf.String()) } return buf, err } }
[ "func", "(", "c", "*", "udpAnnounce", ")", "request", "(", "action", "Action", ",", "args", "interface", "{", "}", ",", "options", "[", "]", "byte", ")", "(", "*", "bytes", ".", "Buffer", ",", "error", ")", "{", "tid", ":=", "newTransactionId", "(", ")", "\n", "if", "err", ":=", "errors", ".", "Wrap", "(", "c", ".", "write", "(", "&", "RequestHeader", "{", "ConnectionId", ":", "c", ".", "connectionId", ",", "Action", ":", "action", ",", "TransactionId", ":", "tid", ",", "}", ",", "args", ",", "options", ")", ",", "\"", "\"", ",", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "socket", ".", "SetReadDeadline", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "timeout", "(", "c", ".", "contiguousTimeouts", ")", ")", ")", "\n", "b", ":=", "make", "(", "[", "]", "byte", ",", "0x800", ")", "// 2KiB", "\n", "for", "{", "var", "(", "n", "int", "\n", "readErr", "error", "\n", "readDone", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "readDone", ")", "\n", "n", ",", "readErr", "=", "c", ".", "socket", ".", "Read", "(", "b", ")", "\n", "}", "(", ")", "\n", "ctx", ":=", "c", ".", "a", ".", "Context", "\n", "if", "ctx", "==", "nil", "{", "ctx", "=", "context", ".", "Background", "(", ")", "\n", "}", "\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "readDone", ":", "}", "\n", "if", "opE", ",", "ok", ":=", "readErr", ".", "(", "*", "net", ".", "OpError", ")", ";", "ok", "&&", "opE", ".", "Timeout", "(", ")", "{", "c", ".", "contiguousTimeouts", "++", "\n", "}", "\n", "if", "readErr", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "readErr", ",", "\"", "\"", ")", "\n", "}", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "b", "[", ":", "n", "]", ")", "\n", "var", "h", "ResponseHeader", "\n", "err", ":=", "binary", ".", "Read", "(", "buf", ",", "binary", ".", "BigEndian", ",", "&", "h", ")", "\n", "switch", "err", "{", "default", ":", "panic", "(", "err", ")", "\n", "case", "io", ".", "ErrUnexpectedEOF", ",", "io", ".", "EOF", ":", "continue", "\n", "case", "nil", ":", "}", "\n", "if", "h", ".", "TransactionId", "!=", "tid", "{", "continue", "\n", "}", "\n", "c", ".", "contiguousTimeouts", "=", "0", "\n", "if", "h", ".", "Action", "==", "ActionError", "{", "err", "=", "errors", ".", "New", "(", "buf", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "buf", ",", "err", "\n", "}", "\n", "}" ]
// args is the binary serializable request body. trailer is optional data // following it, such as for BEP 41.
[ "args", "is", "the", "binary", "serializable", "request", "body", ".", "trailer", "is", "optional", "data", "following", "it", "such", "as", "for", "BEP", "41", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L192-L251
train
anacrolix/torrent
misc.go
metadataPieceSize
func metadataPieceSize(totalSize int, piece int) int { ret := totalSize - piece*(1<<14) if ret > 1<<14 { ret = 1 << 14 } return ret }
go
func metadataPieceSize(totalSize int, piece int) int { ret := totalSize - piece*(1<<14) if ret > 1<<14 { ret = 1 << 14 } return ret }
[ "func", "metadataPieceSize", "(", "totalSize", "int", ",", "piece", "int", ")", "int", "{", "ret", ":=", "totalSize", "-", "piece", "*", "(", "1", "<<", "14", ")", "\n", "if", "ret", ">", "1", "<<", "14", "{", "ret", "=", "1", "<<", "14", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// The size in bytes of a metadata extension piece.
[ "The", "size", "in", "bytes", "of", "a", "metadata", "extension", "piece", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L47-L53
train
anacrolix/torrent
misc.go
torrentOffsetRequest
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) ( r request, ok bool) { if offset < 0 || offset >= torrentLength { return } r.Index = pp.Integer(offset / pieceSize) r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize) r.Length = pp.Integer(chunkSize) pieceLeft := pp.Integer(pieceSize - int64(r.Begin)) if r.Length > pieceLeft { r.Length = pieceLeft } torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin) if int64(r.Length) > torrentLeft { r.Length = pp.Integer(torrentLeft) } ok = true return }
go
func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) ( r request, ok bool) { if offset < 0 || offset >= torrentLength { return } r.Index = pp.Integer(offset / pieceSize) r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize) r.Length = pp.Integer(chunkSize) pieceLeft := pp.Integer(pieceSize - int64(r.Begin)) if r.Length > pieceLeft { r.Length = pieceLeft } torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin) if int64(r.Length) > torrentLeft { r.Length = pp.Integer(torrentLeft) } ok = true return }
[ "func", "torrentOffsetRequest", "(", "torrentLength", ",", "pieceSize", ",", "chunkSize", ",", "offset", "int64", ")", "(", "r", "request", ",", "ok", "bool", ")", "{", "if", "offset", "<", "0", "||", "offset", ">=", "torrentLength", "{", "return", "\n", "}", "\n", "r", ".", "Index", "=", "pp", ".", "Integer", "(", "offset", "/", "pieceSize", ")", "\n", "r", ".", "Begin", "=", "pp", ".", "Integer", "(", "offset", "%", "pieceSize", "/", "chunkSize", "*", "chunkSize", ")", "\n", "r", ".", "Length", "=", "pp", ".", "Integer", "(", "chunkSize", ")", "\n", "pieceLeft", ":=", "pp", ".", "Integer", "(", "pieceSize", "-", "int64", "(", "r", ".", "Begin", ")", ")", "\n", "if", "r", ".", "Length", ">", "pieceLeft", "{", "r", ".", "Length", "=", "pieceLeft", "\n", "}", "\n", "torrentLeft", ":=", "torrentLength", "-", "int64", "(", "r", ".", "Index", ")", "*", "pieceSize", "-", "int64", "(", "r", ".", "Begin", ")", "\n", "if", "int64", "(", "r", ".", "Length", ")", ">", "torrentLeft", "{", "r", ".", "Length", "=", "pp", ".", "Integer", "(", "torrentLeft", ")", "\n", "}", "\n", "ok", "=", "true", "\n", "return", "\n", "}" ]
// Return the request that would include the given offset into the torrent data.
[ "Return", "the", "request", "that", "would", "include", "the", "given", "offset", "into", "the", "torrent", "data", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L56-L74
train
anacrolix/torrent
peer_protocol/handshake.go
Handshake
func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) { // Bytes to be sent to the peer. Should never block the sender. postCh := make(chan []byte, 4) // A single error value sent when the writer completes. writeDone := make(chan error, 1) // Performs writes to the socket and ensures posts don't block. go handshakeWriter(sock, postCh, writeDone) defer func() { close(postCh) // Done writing. if !ok { return } if err != nil { panic(err) } // Wait until writes complete before returning from handshake. err = <-writeDone if err != nil { err = fmt.Errorf("error writing: %s", err) } }() post := func(bb []byte) { select { case postCh <- bb: default: panic("mustn't block while posting") } } post([]byte(Protocol)) post(extensions[:]) if ih != nil { // We already know what we want. post(ih[:]) post(peerID[:]) } var b [68]byte _, err = io.ReadFull(sock, b[:68]) if err != nil { err = nil return } if string(b[:20]) != Protocol { return } missinggo.CopyExact(&res.PeerExtensionBits, b[20:28]) missinggo.CopyExact(&res.Hash, b[28:48]) missinggo.CopyExact(&res.PeerID, b[48:68]) // peerExtensions.Add(res.PeerExtensionBits.String(), 1) // TODO: Maybe we can just drop peers here if we're not interested. This // could prevent them trying to reconnect, falsely believing there was // just a problem. if ih == nil { // We were waiting for the peer to tell us what they wanted. post(res.Hash[:]) post(peerID[:]) } ok = true return }
go
func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) { // Bytes to be sent to the peer. Should never block the sender. postCh := make(chan []byte, 4) // A single error value sent when the writer completes. writeDone := make(chan error, 1) // Performs writes to the socket and ensures posts don't block. go handshakeWriter(sock, postCh, writeDone) defer func() { close(postCh) // Done writing. if !ok { return } if err != nil { panic(err) } // Wait until writes complete before returning from handshake. err = <-writeDone if err != nil { err = fmt.Errorf("error writing: %s", err) } }() post := func(bb []byte) { select { case postCh <- bb: default: panic("mustn't block while posting") } } post([]byte(Protocol)) post(extensions[:]) if ih != nil { // We already know what we want. post(ih[:]) post(peerID[:]) } var b [68]byte _, err = io.ReadFull(sock, b[:68]) if err != nil { err = nil return } if string(b[:20]) != Protocol { return } missinggo.CopyExact(&res.PeerExtensionBits, b[20:28]) missinggo.CopyExact(&res.Hash, b[28:48]) missinggo.CopyExact(&res.PeerID, b[48:68]) // peerExtensions.Add(res.PeerExtensionBits.String(), 1) // TODO: Maybe we can just drop peers here if we're not interested. This // could prevent them trying to reconnect, falsely believing there was // just a problem. if ih == nil { // We were waiting for the peer to tell us what they wanted. post(res.Hash[:]) post(peerID[:]) } ok = true return }
[ "func", "Handshake", "(", "sock", "io", ".", "ReadWriter", ",", "ih", "*", "metainfo", ".", "Hash", ",", "peerID", "[", "20", "]", "byte", ",", "extensions", "PeerExtensionBits", ")", "(", "res", "HandshakeResult", ",", "ok", "bool", ",", "err", "error", ")", "{", "// Bytes to be sent to the peer. Should never block the sender.", "postCh", ":=", "make", "(", "chan", "[", "]", "byte", ",", "4", ")", "\n", "// A single error value sent when the writer completes.", "writeDone", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "// Performs writes to the socket and ensures posts don't block.", "go", "handshakeWriter", "(", "sock", ",", "postCh", ",", "writeDone", ")", "\n\n", "defer", "func", "(", ")", "{", "close", "(", "postCh", ")", "// Done writing.", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "// Wait until writes complete before returning from handshake.", "err", "=", "<-", "writeDone", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "post", ":=", "func", "(", "bb", "[", "]", "byte", ")", "{", "select", "{", "case", "postCh", "<-", "bb", ":", "default", ":", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "post", "(", "[", "]", "byte", "(", "Protocol", ")", ")", "\n", "post", "(", "extensions", "[", ":", "]", ")", "\n", "if", "ih", "!=", "nil", "{", "// We already know what we want.", "post", "(", "ih", "[", ":", "]", ")", "\n", "post", "(", "peerID", "[", ":", "]", ")", "\n", "}", "\n", "var", "b", "[", "68", "]", "byte", "\n", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "sock", ",", "b", "[", ":", "68", "]", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "nil", "\n", "return", "\n", "}", "\n", "if", "string", "(", "b", "[", ":", "20", "]", ")", "!=", "Protocol", "{", "return", "\n", "}", "\n", "missinggo", ".", "CopyExact", "(", "&", "res", ".", "PeerExtensionBits", ",", "b", "[", "20", ":", "28", "]", ")", "\n", "missinggo", ".", "CopyExact", "(", "&", "res", ".", "Hash", ",", "b", "[", "28", ":", "48", "]", ")", "\n", "missinggo", ".", "CopyExact", "(", "&", "res", ".", "PeerID", ",", "b", "[", "48", ":", "68", "]", ")", "\n", "// peerExtensions.Add(res.PeerExtensionBits.String(), 1)", "// TODO: Maybe we can just drop peers here if we're not interested. This", "// could prevent them trying to reconnect, falsely believing there was", "// just a problem.", "if", "ih", "==", "nil", "{", "// We were waiting for the peer to tell us what they wanted.", "post", "(", "res", ".", "Hash", "[", ":", "]", ")", "\n", "post", "(", "peerID", "[", ":", "]", ")", "\n", "}", "\n\n", "ok", "=", "true", "\n", "return", "\n", "}" ]
// ih is nil if we expect the peer to declare the InfoHash, such as when the // peer initiated the connection. Returns ok if the Handshake was successful, // and err if there was an unexpected condition other than the peer simply // abandoning the Handshake.
[ "ih", "is", "nil", "if", "we", "expect", "the", "peer", "to", "declare", "the", "InfoHash", "such", "as", "when", "the", "peer", "initiated", "the", "connection", ".", "Returns", "ok", "if", "the", "Handshake", "was", "successful", "and", "err", "if", "there", "was", "an", "unexpected", "condition", "other", "than", "the", "peer", "simply", "abandoning", "the", "Handshake", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/peer_protocol/handshake.go#L76-L137
train
anacrolix/torrent
bencode/decode.go
readUntil
func (d *Decoder) readUntil(sep byte) { for { b := d.readByte() if b == sep { return } d.buf.WriteByte(b) } }
go
func (d *Decoder) readUntil(sep byte) { for { b := d.readByte() if b == sep { return } d.buf.WriteByte(b) } }
[ "func", "(", "d", "*", "Decoder", ")", "readUntil", "(", "sep", "byte", ")", "{", "for", "{", "b", ":=", "d", ".", "readByte", "(", ")", "\n", "if", "b", "==", "sep", "{", "return", "\n", "}", "\n", "d", ".", "buf", ".", "WriteByte", "(", "b", ")", "\n", "}", "\n", "}" ]
// reads data writing it to 'd.buf' until 'sep' byte is encountered, 'sep' byte // is consumed, but not included into the 'd.buf'
[ "reads", "data", "writing", "it", "to", "d", ".", "buf", "until", "sep", "byte", "is", "encountered", "sep", "byte", "is", "consumed", "but", "not", "included", "into", "the", "d", ".", "buf" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L78-L86
train
anacrolix/torrent
bencode/decode.go
parseInt
func (d *Decoder) parseInt(v reflect.Value) { start := d.Offset - 1 d.readUntil('e') if d.buf.Len() == 0 { panic(&SyntaxError{ Offset: start, What: errors.New("empty integer value"), }) } s := bytesAsString(d.buf.Bytes()) switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(s, 10, 64) checkForIntParseError(err, start) if v.OverflowInt(n) { panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(s, 10, 64) checkForIntParseError(err, start) if v.OverflowUint(n) { panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } v.SetUint(n) case reflect.Bool: v.SetBool(s != "0") default: panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } d.buf.Reset() }
go
func (d *Decoder) parseInt(v reflect.Value) { start := d.Offset - 1 d.readUntil('e') if d.buf.Len() == 0 { panic(&SyntaxError{ Offset: start, What: errors.New("empty integer value"), }) } s := bytesAsString(d.buf.Bytes()) switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(s, 10, 64) checkForIntParseError(err, start) if v.OverflowInt(n) { panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: n, err := strconv.ParseUint(s, 10, 64) checkForIntParseError(err, start) if v.OverflowUint(n) { panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } v.SetUint(n) case reflect.Bool: v.SetBool(s != "0") default: panic(&UnmarshalTypeError{ Value: "integer " + s, Type: v.Type(), }) } d.buf.Reset() }
[ "func", "(", "d", "*", "Decoder", ")", "parseInt", "(", "v", "reflect", ".", "Value", ")", "{", "start", ":=", "d", ".", "Offset", "-", "1", "\n", "d", ".", "readUntil", "(", "'e'", ")", "\n", "if", "d", ".", "buf", ".", "Len", "(", ")", "==", "0", "{", "panic", "(", "&", "SyntaxError", "{", "Offset", ":", "start", ",", "What", ":", "errors", ".", "New", "(", "\"", "\"", ")", ",", "}", ")", "\n", "}", "\n\n", "s", ":=", "bytesAsString", "(", "d", ".", "buf", ".", "Bytes", "(", ")", ")", "\n\n", "switch", "v", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Int", ",", "reflect", ".", "Int8", ",", "reflect", ".", "Int16", ",", "reflect", ".", "Int32", ",", "reflect", ".", "Int64", ":", "n", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "10", ",", "64", ")", "\n", "checkForIntParseError", "(", "err", ",", "start", ")", "\n\n", "if", "v", ".", "OverflowInt", "(", "n", ")", "{", "panic", "(", "&", "UnmarshalTypeError", "{", "Value", ":", "\"", "\"", "+", "s", ",", "Type", ":", "v", ".", "Type", "(", ")", ",", "}", ")", "\n", "}", "\n", "v", ".", "SetInt", "(", "n", ")", "\n", "case", "reflect", ".", "Uint", ",", "reflect", ".", "Uint8", ",", "reflect", ".", "Uint16", ",", "reflect", ".", "Uint32", ",", "reflect", ".", "Uint64", ":", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "checkForIntParseError", "(", "err", ",", "start", ")", "\n\n", "if", "v", ".", "OverflowUint", "(", "n", ")", "{", "panic", "(", "&", "UnmarshalTypeError", "{", "Value", ":", "\"", "\"", "+", "s", ",", "Type", ":", "v", ".", "Type", "(", ")", ",", "}", ")", "\n", "}", "\n", "v", ".", "SetUint", "(", "n", ")", "\n", "case", "reflect", ".", "Bool", ":", "v", ".", "SetBool", "(", "s", "!=", "\"", "\"", ")", "\n", "default", ":", "panic", "(", "&", "UnmarshalTypeError", "{", "Value", ":", "\"", "\"", "+", "s", ",", "Type", ":", "v", ".", "Type", "(", ")", ",", "}", ")", "\n", "}", "\n", "d", ".", "buf", ".", "Reset", "(", ")", "\n", "}" ]
// called when 'i' was consumed
[ "called", "when", "i", "was", "consumed" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L105-L149
train
anacrolix/torrent
bencode/decode.go
getDictField
func getDictField(dict reflect.Value, key string) dictField { // get valuev as a map value or as a struct field switch dict.Kind() { case reflect.Map: value := reflect.New(dict.Type().Elem()).Elem() return dictField{ Value: value, Ok: true, Set: func() { if dict.IsNil() { dict.Set(reflect.MakeMap(dict.Type())) } // Assigns the value into the map. dict.SetMapIndex(reflect.ValueOf(key).Convert(dict.Type().Key()), value) }, } case reflect.Struct: sf, ok := getStructFieldForKey(dict.Type(), key) if !ok { return dictField{} } if sf.r.PkgPath != "" { panic(&UnmarshalFieldError{ Key: key, Type: dict.Type(), Field: sf.r, }) } return dictField{ Value: dict.FieldByIndex(sf.r.Index), Ok: true, Set: func() {}, IgnoreUnmarshalTypeError: sf.tag.IgnoreUnmarshalTypeError(), } default: return dictField{} } }
go
func getDictField(dict reflect.Value, key string) dictField { // get valuev as a map value or as a struct field switch dict.Kind() { case reflect.Map: value := reflect.New(dict.Type().Elem()).Elem() return dictField{ Value: value, Ok: true, Set: func() { if dict.IsNil() { dict.Set(reflect.MakeMap(dict.Type())) } // Assigns the value into the map. dict.SetMapIndex(reflect.ValueOf(key).Convert(dict.Type().Key()), value) }, } case reflect.Struct: sf, ok := getStructFieldForKey(dict.Type(), key) if !ok { return dictField{} } if sf.r.PkgPath != "" { panic(&UnmarshalFieldError{ Key: key, Type: dict.Type(), Field: sf.r, }) } return dictField{ Value: dict.FieldByIndex(sf.r.Index), Ok: true, Set: func() {}, IgnoreUnmarshalTypeError: sf.tag.IgnoreUnmarshalTypeError(), } default: return dictField{} } }
[ "func", "getDictField", "(", "dict", "reflect", ".", "Value", ",", "key", "string", ")", "dictField", "{", "// get valuev as a map value or as a struct field", "switch", "dict", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ":", "value", ":=", "reflect", ".", "New", "(", "dict", ".", "Type", "(", ")", ".", "Elem", "(", ")", ")", ".", "Elem", "(", ")", "\n", "return", "dictField", "{", "Value", ":", "value", ",", "Ok", ":", "true", ",", "Set", ":", "func", "(", ")", "{", "if", "dict", ".", "IsNil", "(", ")", "{", "dict", ".", "Set", "(", "reflect", ".", "MakeMap", "(", "dict", ".", "Type", "(", ")", ")", ")", "\n", "}", "\n", "// Assigns the value into the map.", "dict", ".", "SetMapIndex", "(", "reflect", ".", "ValueOf", "(", "key", ")", ".", "Convert", "(", "dict", ".", "Type", "(", ")", ".", "Key", "(", ")", ")", ",", "value", ")", "\n", "}", ",", "}", "\n", "case", "reflect", ".", "Struct", ":", "sf", ",", "ok", ":=", "getStructFieldForKey", "(", "dict", ".", "Type", "(", ")", ",", "key", ")", "\n", "if", "!", "ok", "{", "return", "dictField", "{", "}", "\n", "}", "\n", "if", "sf", ".", "r", ".", "PkgPath", "!=", "\"", "\"", "{", "panic", "(", "&", "UnmarshalFieldError", "{", "Key", ":", "key", ",", "Type", ":", "dict", ".", "Type", "(", ")", ",", "Field", ":", "sf", ".", "r", ",", "}", ")", "\n", "}", "\n", "return", "dictField", "{", "Value", ":", "dict", ".", "FieldByIndex", "(", "sf", ".", "r", ".", "Index", ")", ",", "Ok", ":", "true", ",", "Set", ":", "func", "(", ")", "{", "}", ",", "IgnoreUnmarshalTypeError", ":", "sf", ".", "tag", ".", "IgnoreUnmarshalTypeError", "(", ")", ",", "}", "\n", "default", ":", "return", "dictField", "{", "}", "\n", "}", "\n", "}" ]
// Returns specifics for parsing a dict field value.
[ "Returns", "specifics", "for", "parsing", "a", "dict", "field", "value", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L217-L254
train
anacrolix/torrent
bencode/decode.go
raiseUnknownValueType
func (d *Decoder) raiseUnknownValueType(b byte, offset int64) { panic(&SyntaxError{ Offset: offset, What: fmt.Errorf("unknown value type %+q", b), }) }
go
func (d *Decoder) raiseUnknownValueType(b byte, offset int64) { panic(&SyntaxError{ Offset: offset, What: fmt.Errorf("unknown value type %+q", b), }) }
[ "func", "(", "d", "*", "Decoder", ")", "raiseUnknownValueType", "(", "b", "byte", ",", "offset", "int64", ")", "{", "panic", "(", "&", "SyntaxError", "{", "Offset", ":", "offset", ",", "What", ":", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "b", ")", ",", "}", ")", "\n", "}" ]
// An unknown bencode type character was encountered.
[ "An", "unknown", "bencode", "type", "character", "was", "encountered", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L520-L525
train
anacrolix/torrent
tracker_scraper.go
announce
func (me *trackerScraper) announce() (ret trackerAnnounceResult) { defer func() { ret.Completed = time.Now() }() ret.Interval = 5 * time.Minute ip, err := me.getIp() if err != nil { ret.Err = fmt.Errorf("error getting ip: %s", err) return } me.t.cl.lock() req := me.t.announceRequest() me.t.cl.unlock() res, err := tracker.Announce{ HTTPProxy: me.t.cl.config.HTTPProxy, UserAgent: me.t.cl.config.HTTPUserAgent, TrackerUrl: me.trackerUrl(ip), Request: req, HostHeader: me.u.Host, ServerName: me.u.Hostname(), UdpNetwork: me.u.Scheme, ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4}, ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6}, }.Do() if err != nil { ret.Err = fmt.Errorf("error announcing: %s", err) return } me.t.AddPeers(Peers(nil).AppendFromTracker(res.Peers)) ret.NumPeers = len(res.Peers) ret.Interval = time.Duration(res.Interval) * time.Second return }
go
func (me *trackerScraper) announce() (ret trackerAnnounceResult) { defer func() { ret.Completed = time.Now() }() ret.Interval = 5 * time.Minute ip, err := me.getIp() if err != nil { ret.Err = fmt.Errorf("error getting ip: %s", err) return } me.t.cl.lock() req := me.t.announceRequest() me.t.cl.unlock() res, err := tracker.Announce{ HTTPProxy: me.t.cl.config.HTTPProxy, UserAgent: me.t.cl.config.HTTPUserAgent, TrackerUrl: me.trackerUrl(ip), Request: req, HostHeader: me.u.Host, ServerName: me.u.Hostname(), UdpNetwork: me.u.Scheme, ClientIp4: krpc.NodeAddr{IP: me.t.cl.config.PublicIp4}, ClientIp6: krpc.NodeAddr{IP: me.t.cl.config.PublicIp6}, }.Do() if err != nil { ret.Err = fmt.Errorf("error announcing: %s", err) return } me.t.AddPeers(Peers(nil).AppendFromTracker(res.Peers)) ret.NumPeers = len(res.Peers) ret.Interval = time.Duration(res.Interval) * time.Second return }
[ "func", "(", "me", "*", "trackerScraper", ")", "announce", "(", ")", "(", "ret", "trackerAnnounceResult", ")", "{", "defer", "func", "(", ")", "{", "ret", ".", "Completed", "=", "time", ".", "Now", "(", ")", "\n", "}", "(", ")", "\n", "ret", ".", "Interval", "=", "5", "*", "time", ".", "Minute", "\n", "ip", ",", "err", ":=", "me", ".", "getIp", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ret", ".", "Err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "me", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "req", ":=", "me", ".", "t", ".", "announceRequest", "(", ")", "\n", "me", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "res", ",", "err", ":=", "tracker", ".", "Announce", "{", "HTTPProxy", ":", "me", ".", "t", ".", "cl", ".", "config", ".", "HTTPProxy", ",", "UserAgent", ":", "me", ".", "t", ".", "cl", ".", "config", ".", "HTTPUserAgent", ",", "TrackerUrl", ":", "me", ".", "trackerUrl", "(", "ip", ")", ",", "Request", ":", "req", ",", "HostHeader", ":", "me", ".", "u", ".", "Host", ",", "ServerName", ":", "me", ".", "u", ".", "Hostname", "(", ")", ",", "UdpNetwork", ":", "me", ".", "u", ".", "Scheme", ",", "ClientIp4", ":", "krpc", ".", "NodeAddr", "{", "IP", ":", "me", ".", "t", ".", "cl", ".", "config", ".", "PublicIp4", "}", ",", "ClientIp6", ":", "krpc", ".", "NodeAddr", "{", "IP", ":", "me", ".", "t", ".", "cl", ".", "config", ".", "PublicIp6", "}", ",", "}", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ret", ".", "Err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "me", ".", "t", ".", "AddPeers", "(", "Peers", "(", "nil", ")", ".", "AppendFromTracker", "(", "res", ".", "Peers", ")", ")", "\n", "ret", ".", "NumPeers", "=", "len", "(", "res", ".", "Peers", ")", "\n", "ret", ".", "Interval", "=", "time", ".", "Duration", "(", "res", ".", "Interval", ")", "*", "time", ".", "Second", "\n", "return", "\n", "}" ]
// Return how long to wait before trying again. For most errors, we return 5 // minutes, a relatively quick turn around for DNS changes.
[ "Return", "how", "long", "to", "wait", "before", "trying", "again", ".", "For", "most", "errors", "we", "return", "5", "minutes", "a", "relatively", "quick", "turn", "around", "for", "DNS", "changes", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker_scraper.go#L99-L131
train
anacrolix/torrent
iplist/cidr.go
IPNetLast
func IPNetLast(in *net.IPNet) (last net.IP) { n := len(in.IP) if n != len(in.Mask) { panic("wat") } last = make(net.IP, n) for i := 0; i < n; i++ { last[i] = in.IP[i] | ^in.Mask[i] } return }
go
func IPNetLast(in *net.IPNet) (last net.IP) { n := len(in.IP) if n != len(in.Mask) { panic("wat") } last = make(net.IP, n) for i := 0; i < n; i++ { last[i] = in.IP[i] | ^in.Mask[i] } return }
[ "func", "IPNetLast", "(", "in", "*", "net", ".", "IPNet", ")", "(", "last", "net", ".", "IP", ")", "{", "n", ":=", "len", "(", "in", ".", "IP", ")", "\n", "if", "n", "!=", "len", "(", "in", ".", "Mask", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "last", "=", "make", "(", "net", ".", "IP", ",", "n", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "last", "[", "i", "]", "=", "in", ".", "IP", "[", "i", "]", "|", "^", "in", ".", "Mask", "[", "i", "]", "\n", "}", "\n", "return", "\n", "}" ]
// Returns the last, inclusive IP in a net.IPNet.
[ "Returns", "the", "last", "inclusive", "IP", "in", "a", "net", ".", "IPNet", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/cidr.go#L31-L41
train
anacrolix/torrent
bencode/encode.go
reflectMarshaler
func (e *Encoder) reflectMarshaler(v reflect.Value) bool { if !v.Type().Implements(marshalerType) { if v.Kind() != reflect.Ptr && v.CanAddr() && v.Addr().Type().Implements(marshalerType) { v = v.Addr() } else { return false } } m := v.Interface().(Marshaler) data, err := m.MarshalBencode() if err != nil { panic(&MarshalerError{v.Type(), err}) } e.write(data) return true }
go
func (e *Encoder) reflectMarshaler(v reflect.Value) bool { if !v.Type().Implements(marshalerType) { if v.Kind() != reflect.Ptr && v.CanAddr() && v.Addr().Type().Implements(marshalerType) { v = v.Addr() } else { return false } } m := v.Interface().(Marshaler) data, err := m.MarshalBencode() if err != nil { panic(&MarshalerError{v.Type(), err}) } e.write(data) return true }
[ "func", "(", "e", "*", "Encoder", ")", "reflectMarshaler", "(", "v", "reflect", ".", "Value", ")", "bool", "{", "if", "!", "v", ".", "Type", "(", ")", ".", "Implements", "(", "marshalerType", ")", "{", "if", "v", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "&&", "v", ".", "CanAddr", "(", ")", "&&", "v", ".", "Addr", "(", ")", ".", "Type", "(", ")", ".", "Implements", "(", "marshalerType", ")", "{", "v", "=", "v", ".", "Addr", "(", ")", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}", "\n", "m", ":=", "v", ".", "Interface", "(", ")", ".", "(", "Marshaler", ")", "\n", "data", ",", "err", ":=", "m", ".", "MarshalBencode", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "&", "MarshalerError", "{", "v", ".", "Type", "(", ")", ",", "err", "}", ")", "\n", "}", "\n", "e", ".", "write", "(", "data", ")", "\n", "return", "true", "\n", "}" ]
// Returns true if the value implements Marshaler interface and marshaling was // done successfully.
[ "Returns", "true", "if", "the", "value", "implements", "Marshaler", "interface", "and", "marshaling", "was", "done", "successfully", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/encode.go#L82-L97
train
anacrolix/torrent
file.go
DisplayPath
func (f *File) DisplayPath() string { fip := f.FileInfo().Path if len(fip) == 0 { return f.t.info.Name } return strings.Join(fip, "/") }
go
func (f *File) DisplayPath() string { fip := f.FileInfo().Path if len(fip) == 0 { return f.t.info.Name } return strings.Join(fip, "/") }
[ "func", "(", "f", "*", "File", ")", "DisplayPath", "(", ")", "string", "{", "fip", ":=", "f", ".", "FileInfo", "(", ")", ".", "Path", "\n", "if", "len", "(", "fip", ")", "==", "0", "{", "return", "f", ".", "t", ".", "info", ".", "Name", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "fip", ",", "\"", "\"", ")", "\n\n", "}" ]
// The relative file path for a multi-file torrent, and the torrent name for a // single-file torrent.
[ "The", "relative", "file", "path", "for", "a", "multi", "-", "file", "torrent", "and", "the", "torrent", "name", "for", "a", "single", "-", "file", "torrent", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L45-L52
train
anacrolix/torrent
file.go
State
func (f *File) State() (ret []FilePieceState) { f.t.cl.rLock() defer f.t.cl.rUnlock() pieceSize := int64(f.t.usualPieceSize()) off := f.offset % pieceSize remaining := f.length for i := pieceIndex(f.offset / pieceSize); ; i++ { if remaining == 0 { break } len1 := pieceSize - off if len1 > remaining { len1 = remaining } ps := f.t.pieceState(i) ret = append(ret, FilePieceState{len1, ps}) off = 0 remaining -= len1 } return }
go
func (f *File) State() (ret []FilePieceState) { f.t.cl.rLock() defer f.t.cl.rUnlock() pieceSize := int64(f.t.usualPieceSize()) off := f.offset % pieceSize remaining := f.length for i := pieceIndex(f.offset / pieceSize); ; i++ { if remaining == 0 { break } len1 := pieceSize - off if len1 > remaining { len1 = remaining } ps := f.t.pieceState(i) ret = append(ret, FilePieceState{len1, ps}) off = 0 remaining -= len1 } return }
[ "func", "(", "f", "*", "File", ")", "State", "(", ")", "(", "ret", "[", "]", "FilePieceState", ")", "{", "f", ".", "t", ".", "cl", ".", "rLock", "(", ")", "\n", "defer", "f", ".", "t", ".", "cl", ".", "rUnlock", "(", ")", "\n", "pieceSize", ":=", "int64", "(", "f", ".", "t", ".", "usualPieceSize", "(", ")", ")", "\n", "off", ":=", "f", ".", "offset", "%", "pieceSize", "\n", "remaining", ":=", "f", ".", "length", "\n", "for", "i", ":=", "pieceIndex", "(", "f", ".", "offset", "/", "pieceSize", ")", ";", ";", "i", "++", "{", "if", "remaining", "==", "0", "{", "break", "\n", "}", "\n", "len1", ":=", "pieceSize", "-", "off", "\n", "if", "len1", ">", "remaining", "{", "len1", "=", "remaining", "\n", "}", "\n", "ps", ":=", "f", ".", "t", ".", "pieceState", "(", "i", ")", "\n", "ret", "=", "append", "(", "ret", ",", "FilePieceState", "{", "len1", ",", "ps", "}", ")", "\n", "off", "=", "0", "\n", "remaining", "-=", "len1", "\n", "}", "\n", "return", "\n", "}" ]
// Returns the state of pieces in this file.
[ "Returns", "the", "state", "of", "pieces", "in", "this", "file", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L61-L81
train
anacrolix/torrent
file.go
SetPriority
func (f *File) SetPriority(prio piecePriority) { f.t.cl.lock() defer f.t.cl.unlock() if prio == f.prio { return } f.prio = prio f.t.updatePiecePriorities(f.firstPieceIndex(), f.endPieceIndex()) }
go
func (f *File) SetPriority(prio piecePriority) { f.t.cl.lock() defer f.t.cl.unlock() if prio == f.prio { return } f.prio = prio f.t.updatePiecePriorities(f.firstPieceIndex(), f.endPieceIndex()) }
[ "func", "(", "f", "*", "File", ")", "SetPriority", "(", "prio", "piecePriority", ")", "{", "f", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "f", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "if", "prio", "==", "f", ".", "prio", "{", "return", "\n", "}", "\n", "f", ".", "prio", "=", "prio", "\n", "f", ".", "t", ".", "updatePiecePriorities", "(", "f", ".", "firstPieceIndex", "(", ")", ",", "f", ".", "endPieceIndex", "(", ")", ")", "\n", "}" ]
// Sets the minimum priority for pieces in the File.
[ "Sets", "the", "minimum", "priority", "for", "pieces", "in", "the", "File", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L112-L120
train
anacrolix/torrent
file.go
Priority
func (f *File) Priority() piecePriority { f.t.cl.lock() defer f.t.cl.unlock() return f.prio }
go
func (f *File) Priority() piecePriority { f.t.cl.lock() defer f.t.cl.unlock() return f.prio }
[ "func", "(", "f", "*", "File", ")", "Priority", "(", ")", "piecePriority", "{", "f", ".", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "f", ".", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "return", "f", ".", "prio", "\n", "}" ]
// Returns the priority per File.SetPriority.
[ "Returns", "the", "priority", "per", "File", ".", "SetPriority", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L123-L127
train
anacrolix/torrent
client.go
WriteStatus
func (cl *Client) WriteStatus(_w io.Writer) { cl.rLock() defer cl.rUnlock() w := bufio.NewWriter(_w) defer w.Flush() fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort()) fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID()) fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey()) fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked())) cl.eachDhtServer(func(s *dht.Server) { fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String()) writeDhtServerStatus(w, s) }) spew.Fdump(w, cl.stats) fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice())) fmt.Fprintln(w) for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool { return l.InfoHash().AsString() < r.InfoHash().AsString() }).([]*Torrent) { if t.name() == "" { fmt.Fprint(w, "<unknown name>") } else { fmt.Fprint(w, t.name()) } fmt.Fprint(w, "\n") if t.info != nil { fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength()))) } else { w.WriteString("<missing metainfo>") } fmt.Fprint(w, "\n") t.writeStatus(w) fmt.Fprintln(w) } }
go
func (cl *Client) WriteStatus(_w io.Writer) { cl.rLock() defer cl.rUnlock() w := bufio.NewWriter(_w) defer w.Flush() fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort()) fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID()) fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey()) fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked())) cl.eachDhtServer(func(s *dht.Server) { fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String()) writeDhtServerStatus(w, s) }) spew.Fdump(w, cl.stats) fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrentsAsSlice())) fmt.Fprintln(w) for _, t := range slices.Sort(cl.torrentsAsSlice(), func(l, r *Torrent) bool { return l.InfoHash().AsString() < r.InfoHash().AsString() }).([]*Torrent) { if t.name() == "" { fmt.Fprint(w, "<unknown name>") } else { fmt.Fprint(w, t.name()) } fmt.Fprint(w, "\n") if t.info != nil { fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())), t.length, humanize.Bytes(uint64(t.info.TotalLength()))) } else { w.WriteString("<missing metainfo>") } fmt.Fprint(w, "\n") t.writeStatus(w) fmt.Fprintln(w) } }
[ "func", "(", "cl", "*", "Client", ")", "WriteStatus", "(", "_w", "io", ".", "Writer", ")", "{", "cl", ".", "rLock", "(", ")", "\n", "defer", "cl", ".", "rUnlock", "(", ")", "\n", "w", ":=", "bufio", ".", "NewWriter", "(", "_w", ")", "\n", "defer", "w", ".", "Flush", "(", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "cl", ".", "LocalPort", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "cl", ".", "PeerID", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "cl", ".", "announceKey", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "len", "(", "cl", ".", "badPeerIPsLocked", "(", ")", ")", ")", "\n", "cl", ".", "eachDhtServer", "(", "func", "(", "s", "*", "dht", ".", "Server", ")", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "s", ".", "Addr", "(", ")", ".", "Network", "(", ")", ",", "s", ".", "Addr", "(", ")", ".", "String", "(", ")", ")", "\n", "writeDhtServerStatus", "(", "w", ",", "s", ")", "\n", "}", ")", "\n", "spew", ".", "Fdump", "(", "w", ",", "cl", ".", "stats", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "len", "(", "cl", ".", "torrentsAsSlice", "(", ")", ")", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ")", "\n", "for", "_", ",", "t", ":=", "range", "slices", ".", "Sort", "(", "cl", ".", "torrentsAsSlice", "(", ")", ",", "func", "(", "l", ",", "r", "*", "Torrent", ")", "bool", "{", "return", "l", ".", "InfoHash", "(", ")", ".", "AsString", "(", ")", "<", "r", ".", "InfoHash", "(", ")", ".", "AsString", "(", ")", "\n", "}", ")", ".", "(", "[", "]", "*", "Torrent", ")", "{", "if", "t", ".", "name", "(", ")", "==", "\"", "\"", "{", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\"", ")", "\n", "}", "else", "{", "fmt", ".", "Fprint", "(", "w", ",", "t", ".", "name", "(", ")", ")", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "if", "t", ".", "info", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\"", ",", "100", "*", "(", "1", "-", "float64", "(", "t", ".", "bytesMissingLocked", "(", ")", ")", "/", "float64", "(", "t", ".", "info", ".", "TotalLength", "(", ")", ")", ")", ",", "t", ".", "length", ",", "humanize", ".", "Bytes", "(", "uint64", "(", "t", ".", "info", ".", "TotalLength", "(", ")", ")", ")", ")", "\n", "}", "else", "{", "w", ".", "WriteString", "(", "\"", "\"", ")", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "t", ".", "writeStatus", "(", "w", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ")", "\n", "}", "\n", "}" ]
// Writes out a human readable status of the client, such as for writing to a // HTTP status page.
[ "Writes", "out", "a", "human", "readable", "status", "of", "the", "client", "such", "as", "for", "writing", "to", "a", "HTTP", "status", "page", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L118-L152
train
anacrolix/torrent
client.go
Close
func (cl *Client) Close() { cl.lock() defer cl.unlock() cl.closed.Set() cl.eachDhtServer(func(s *dht.Server) { s.Close() }) cl.closeSockets() for _, t := range cl.torrents { t.close() } for _, f := range cl.onClose { f() } cl.event.Broadcast() }
go
func (cl *Client) Close() { cl.lock() defer cl.unlock() cl.closed.Set() cl.eachDhtServer(func(s *dht.Server) { s.Close() }) cl.closeSockets() for _, t := range cl.torrents { t.close() } for _, f := range cl.onClose { f() } cl.event.Broadcast() }
[ "func", "(", "cl", "*", "Client", ")", "Close", "(", ")", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "cl", ".", "closed", ".", "Set", "(", ")", "\n", "cl", ".", "eachDhtServer", "(", "func", "(", "s", "*", "dht", ".", "Server", ")", "{", "s", ".", "Close", "(", ")", "}", ")", "\n", "cl", ".", "closeSockets", "(", ")", "\n", "for", "_", ",", "t", ":=", "range", "cl", ".", "torrents", "{", "t", ".", "close", "(", ")", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "cl", ".", "onClose", "{", "f", "(", ")", "\n", "}", "\n", "cl", ".", "event", ".", "Broadcast", "(", ")", "\n", "}" ]
// Stops the client. All connections to peers are closed and all activity will // come to a halt.
[ "Stops", "the", "client", ".", "All", "connections", "to", "peers", "are", "closed", "and", "all", "activity", "will", "come", "to", "a", "halt", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L352-L365
train
anacrolix/torrent
client.go
Torrent
func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) { cl.lock() defer cl.unlock() t, ok = cl.torrents[ih] return }
go
func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) { cl.lock() defer cl.unlock() t, ok = cl.torrents[ih] return }
[ "func", "(", "cl", "*", "Client", ")", "Torrent", "(", "ih", "metainfo", ".", "Hash", ")", "(", "t", "*", "Torrent", ",", "ok", "bool", ")", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "t", ",", "ok", "=", "cl", ".", "torrents", "[", "ih", "]", "\n", "return", "\n", "}" ]
// Returns a handle to the given torrent, if it's present in the client.
[ "Returns", "a", "handle", "to", "the", "given", "torrent", "if", "it", "s", "present", "in", "the", "client", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L465-L470
train
anacrolix/torrent
client.go
dopplegangerAddr
func (cl *Client) dopplegangerAddr(addr string) bool { _, ok := cl.dopplegangerAddrs[addr] return ok }
go
func (cl *Client) dopplegangerAddr(addr string) bool { _, ok := cl.dopplegangerAddrs[addr] return ok }
[ "func", "(", "cl", "*", "Client", ")", "dopplegangerAddr", "(", "addr", "string", ")", "bool", "{", "_", ",", "ok", ":=", "cl", ".", "dopplegangerAddrs", "[", "addr", "]", "\n", "return", "ok", "\n", "}" ]
// Returns whether an address is known to connect to a client with our own ID.
[ "Returns", "whether", "an", "address", "is", "known", "to", "connect", "to", "a", "client", "with", "our", "own", "ID", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L498-L501
train
anacrolix/torrent
client.go
dialFirst
func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult { ctx, cancel := context.WithCancel(ctx) // As soon as we return one connection, cancel the others. defer cancel() left := 0 resCh := make(chan dialResult, left) func() { cl.lock() defer cl.unlock() cl.eachListener(func(s socket) bool { network := s.Addr().Network() if peerNetworkEnabled(parseNetworkString(network), cl.config) { left++ go func() { cte := cl.config.ConnTracker.Wait( ctx, conntrack.Entry{network, s.Addr().String(), addr}, "dial torrent client", 0, ) // Try to avoid committing to a dial if the context is complete as it's // difficult to determine which dial errors allow us to forget the connection // tracking entry handle. if ctx.Err() != nil { if cte != nil { cte.Forget() } resCh <- dialResult{} return } c, err := s.dial(ctx, addr) // This is a bit optimistic, but it looks non-trivial to thread // this through the proxy code. Set it now in case we close the // connection forthwith. if tc, ok := c.(*net.TCPConn); ok { tc.SetLinger(0) } countDialResult(err) dr := dialResult{c, network} if c == nil { if err != nil && forgettableDialError(err) { cte.Forget() } else { cte.Done() } } else { dr.Conn = closeWrapper{c, func() error { err := c.Close() cte.Done() return err }} } resCh <- dr }() } return true }) }() var res dialResult // Wait for a successful connection. func() { defer perf.ScopeTimer()() for ; left > 0 && res.Conn == nil; left-- { res = <-resCh } }() // There are still incompleted dials. go func() { for ; left > 0; left-- { conn := (<-resCh).Conn if conn != nil { conn.Close() } } }() if res.Conn != nil { go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1) } return res }
go
func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult { ctx, cancel := context.WithCancel(ctx) // As soon as we return one connection, cancel the others. defer cancel() left := 0 resCh := make(chan dialResult, left) func() { cl.lock() defer cl.unlock() cl.eachListener(func(s socket) bool { network := s.Addr().Network() if peerNetworkEnabled(parseNetworkString(network), cl.config) { left++ go func() { cte := cl.config.ConnTracker.Wait( ctx, conntrack.Entry{network, s.Addr().String(), addr}, "dial torrent client", 0, ) // Try to avoid committing to a dial if the context is complete as it's // difficult to determine which dial errors allow us to forget the connection // tracking entry handle. if ctx.Err() != nil { if cte != nil { cte.Forget() } resCh <- dialResult{} return } c, err := s.dial(ctx, addr) // This is a bit optimistic, but it looks non-trivial to thread // this through the proxy code. Set it now in case we close the // connection forthwith. if tc, ok := c.(*net.TCPConn); ok { tc.SetLinger(0) } countDialResult(err) dr := dialResult{c, network} if c == nil { if err != nil && forgettableDialError(err) { cte.Forget() } else { cte.Done() } } else { dr.Conn = closeWrapper{c, func() error { err := c.Close() cte.Done() return err }} } resCh <- dr }() } return true }) }() var res dialResult // Wait for a successful connection. func() { defer perf.ScopeTimer()() for ; left > 0 && res.Conn == nil; left-- { res = <-resCh } }() // There are still incompleted dials. go func() { for ; left > 0; left-- { conn := (<-resCh).Conn if conn != nil { conn.Close() } } }() if res.Conn != nil { go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1) } return res }
[ "func", "(", "cl", "*", "Client", ")", "dialFirst", "(", "ctx", "context", ".", "Context", ",", "addr", "string", ")", "dialResult", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "// As soon as we return one connection, cancel the others.", "defer", "cancel", "(", ")", "\n", "left", ":=", "0", "\n", "resCh", ":=", "make", "(", "chan", "dialResult", ",", "left", ")", "\n", "func", "(", ")", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "cl", ".", "eachListener", "(", "func", "(", "s", "socket", ")", "bool", "{", "network", ":=", "s", ".", "Addr", "(", ")", ".", "Network", "(", ")", "\n", "if", "peerNetworkEnabled", "(", "parseNetworkString", "(", "network", ")", ",", "cl", ".", "config", ")", "{", "left", "++", "\n", "go", "func", "(", ")", "{", "cte", ":=", "cl", ".", "config", ".", "ConnTracker", ".", "Wait", "(", "ctx", ",", "conntrack", ".", "Entry", "{", "network", ",", "s", ".", "Addr", "(", ")", ".", "String", "(", ")", ",", "addr", "}", ",", "\"", "\"", ",", "0", ",", ")", "\n", "// Try to avoid committing to a dial if the context is complete as it's", "// difficult to determine which dial errors allow us to forget the connection", "// tracking entry handle.", "if", "ctx", ".", "Err", "(", ")", "!=", "nil", "{", "if", "cte", "!=", "nil", "{", "cte", ".", "Forget", "(", ")", "\n", "}", "\n", "resCh", "<-", "dialResult", "{", "}", "\n", "return", "\n", "}", "\n", "c", ",", "err", ":=", "s", ".", "dial", "(", "ctx", ",", "addr", ")", "\n", "// This is a bit optimistic, but it looks non-trivial to thread", "// this through the proxy code. Set it now in case we close the", "// connection forthwith.", "if", "tc", ",", "ok", ":=", "c", ".", "(", "*", "net", ".", "TCPConn", ")", ";", "ok", "{", "tc", ".", "SetLinger", "(", "0", ")", "\n", "}", "\n", "countDialResult", "(", "err", ")", "\n", "dr", ":=", "dialResult", "{", "c", ",", "network", "}", "\n", "if", "c", "==", "nil", "{", "if", "err", "!=", "nil", "&&", "forgettableDialError", "(", "err", ")", "{", "cte", ".", "Forget", "(", ")", "\n", "}", "else", "{", "cte", ".", "Done", "(", ")", "\n", "}", "\n", "}", "else", "{", "dr", ".", "Conn", "=", "closeWrapper", "{", "c", ",", "func", "(", ")", "error", "{", "err", ":=", "c", ".", "Close", "(", ")", "\n", "cte", ".", "Done", "(", ")", "\n", "return", "err", "\n", "}", "}", "\n", "}", "\n", "resCh", "<-", "dr", "\n", "}", "(", ")", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "}", "(", ")", "\n", "var", "res", "dialResult", "\n", "// Wait for a successful connection.", "func", "(", ")", "{", "defer", "perf", ".", "ScopeTimer", "(", ")", "(", ")", "\n", "for", ";", "left", ">", "0", "&&", "res", ".", "Conn", "==", "nil", ";", "left", "--", "{", "res", "=", "<-", "resCh", "\n", "}", "\n", "}", "(", ")", "\n", "// There are still incompleted dials.", "go", "func", "(", ")", "{", "for", ";", "left", ">", "0", ";", "left", "--", "{", "conn", ":=", "(", "<-", "resCh", ")", ".", "Conn", "\n", "if", "conn", "!=", "nil", "{", "conn", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "if", "res", ".", "Conn", "!=", "nil", "{", "go", "torrent", ".", "Add", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "res", ".", "Conn", ".", "RemoteAddr", "(", ")", ".", "Network", "(", ")", ")", ",", "1", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Returns a connection over UTP or TCP, whichever is first to connect.
[ "Returns", "a", "connection", "over", "UTP", "or", "TCP", "whichever", "is", "first", "to", "connect", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L504-L583
train
anacrolix/torrent
client.go
outgoingConnection
func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) { cl.dialRateLimiter.Wait(context.Background()) c, err := cl.establishOutgoingConn(t, addr) cl.lock() defer cl.unlock() // Don't release lock between here and addConnection, unless it's for // failure. cl.noLongerHalfOpen(t, addr.String()) if err != nil { if cl.config.Debug { cl.logger.Printf("error establishing outgoing connection: %s", err) } return } if c == nil { return } defer c.Close() c.Discovery = ps cl.runHandshookConn(c, t) }
go
func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) { cl.dialRateLimiter.Wait(context.Background()) c, err := cl.establishOutgoingConn(t, addr) cl.lock() defer cl.unlock() // Don't release lock between here and addConnection, unless it's for // failure. cl.noLongerHalfOpen(t, addr.String()) if err != nil { if cl.config.Debug { cl.logger.Printf("error establishing outgoing connection: %s", err) } return } if c == nil { return } defer c.Close() c.Discovery = ps cl.runHandshookConn(c, t) }
[ "func", "(", "cl", "*", "Client", ")", "outgoingConnection", "(", "t", "*", "Torrent", ",", "addr", "IpPort", ",", "ps", "peerSource", ")", "{", "cl", ".", "dialRateLimiter", ".", "Wait", "(", "context", ".", "Background", "(", ")", ")", "\n", "c", ",", "err", ":=", "cl", ".", "establishOutgoingConn", "(", "t", ",", "addr", ")", "\n", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "// Don't release lock between here and addConnection, unless it's for", "// failure.", "cl", ".", "noLongerHalfOpen", "(", "t", ",", "addr", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "cl", ".", "config", ".", "Debug", "{", "cl", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "c", "==", "nil", "{", "return", "\n", "}", "\n", "defer", "c", ".", "Close", "(", ")", "\n", "c", ".", "Discovery", "=", "ps", "\n", "cl", ".", "runHandshookConn", "(", "c", ",", "t", ")", "\n", "}" ]
// Called to dial out and run a connection. The addr we're given is already // considered half-open.
[ "Called", "to", "dial", "out", "and", "run", "a", "connection", ".", "The", "addr", "we", "re", "given", "is", "already", "considered", "half", "-", "open", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L672-L692
train
anacrolix/torrent
client.go
forSkeys
func (cl *Client) forSkeys(f func([]byte) bool) { cl.lock() defer cl.unlock() for ih := range cl.torrents { if !f(ih[:]) { break } } }
go
func (cl *Client) forSkeys(f func([]byte) bool) { cl.lock() defer cl.unlock() for ih := range cl.torrents { if !f(ih[:]) { break } } }
[ "func", "(", "cl", "*", "Client", ")", "forSkeys", "(", "f", "func", "(", "[", "]", "byte", ")", "bool", ")", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "for", "ih", ":=", "range", "cl", ".", "torrents", "{", "if", "!", "f", "(", "ih", "[", ":", "]", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Calls f with any secret keys.
[ "Calls", "f", "with", "any", "secret", "keys", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L734-L742
train
anacrolix/torrent
client.go
receiveHandshakes
func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) { defer perf.ScopeTimerErr(&err)() var rw io.ReadWriter rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy) c.setRW(rw) if err == nil || err == mse.ErrNoSecretKeyMatch { if c.headerEncrypted { torrent.Add("handshakes received encrypted", 1) } else { torrent.Add("handshakes received unencrypted", 1) } } else { torrent.Add("handshakes received with error while handling encryption", 1) } if err != nil { if err == mse.ErrNoSecretKeyMatch { err = nil } return } if cl.config.ForceEncryption && !c.headerEncrypted { err = errors.New("connection not encrypted") return } ih, ok, err := cl.connBTHandshake(c, nil) if err != nil { err = fmt.Errorf("error during bt handshake: %s", err) return } if !ok { return } cl.lock() t = cl.torrents[ih] cl.unlock() return }
go
func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) { defer perf.ScopeTimerErr(&err)() var rw io.ReadWriter rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.forSkeys, cl.config.EncryptionPolicy) c.setRW(rw) if err == nil || err == mse.ErrNoSecretKeyMatch { if c.headerEncrypted { torrent.Add("handshakes received encrypted", 1) } else { torrent.Add("handshakes received unencrypted", 1) } } else { torrent.Add("handshakes received with error while handling encryption", 1) } if err != nil { if err == mse.ErrNoSecretKeyMatch { err = nil } return } if cl.config.ForceEncryption && !c.headerEncrypted { err = errors.New("connection not encrypted") return } ih, ok, err := cl.connBTHandshake(c, nil) if err != nil { err = fmt.Errorf("error during bt handshake: %s", err) return } if !ok { return } cl.lock() t = cl.torrents[ih] cl.unlock() return }
[ "func", "(", "cl", "*", "Client", ")", "receiveHandshakes", "(", "c", "*", "connection", ")", "(", "t", "*", "Torrent", ",", "err", "error", ")", "{", "defer", "perf", ".", "ScopeTimerErr", "(", "&", "err", ")", "(", ")", "\n", "var", "rw", "io", ".", "ReadWriter", "\n", "rw", ",", "c", ".", "headerEncrypted", ",", "c", ".", "cryptoMethod", ",", "err", "=", "handleEncryption", "(", "c", ".", "rw", "(", ")", ",", "cl", ".", "forSkeys", ",", "cl", ".", "config", ".", "EncryptionPolicy", ")", "\n", "c", ".", "setRW", "(", "rw", ")", "\n", "if", "err", "==", "nil", "||", "err", "==", "mse", ".", "ErrNoSecretKeyMatch", "{", "if", "c", ".", "headerEncrypted", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "else", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "}", "else", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "mse", ".", "ErrNoSecretKeyMatch", "{", "err", "=", "nil", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "cl", ".", "config", ".", "ForceEncryption", "&&", "!", "c", ".", "headerEncrypted", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "ih", ",", "ok", ",", "err", ":=", "cl", ".", "connBTHandshake", "(", "c", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "cl", ".", "lock", "(", ")", "\n", "t", "=", "cl", ".", "torrents", "[", "ih", "]", "\n", "cl", ".", "unlock", "(", ")", "\n", "return", "\n", "}" ]
// Do encryption and bittorrent handshakes as receiver.
[ "Do", "encryption", "and", "bittorrent", "handshakes", "as", "receiver", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L745-L781
train
anacrolix/torrent
client.go
connBTHandshake
func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) { res, ok, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes) if err != nil || !ok { return } ret = res.Hash c.PeerExtensionBytes = res.PeerExtensionBits c.PeerID = res.PeerID c.completedHandshake = time.Now() return }
go
func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) { res, ok, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.extensionBytes) if err != nil || !ok { return } ret = res.Hash c.PeerExtensionBytes = res.PeerExtensionBits c.PeerID = res.PeerID c.completedHandshake = time.Now() return }
[ "func", "(", "cl", "*", "Client", ")", "connBTHandshake", "(", "c", "*", "connection", ",", "ih", "*", "metainfo", ".", "Hash", ")", "(", "ret", "metainfo", ".", "Hash", ",", "ok", "bool", ",", "err", "error", ")", "{", "res", ",", "ok", ",", "err", ":=", "pp", ".", "Handshake", "(", "c", ".", "rw", "(", ")", ",", "ih", ",", "cl", ".", "peerID", ",", "cl", ".", "extensionBytes", ")", "\n", "if", "err", "!=", "nil", "||", "!", "ok", "{", "return", "\n", "}", "\n", "ret", "=", "res", ".", "Hash", "\n", "c", ".", "PeerExtensionBytes", "=", "res", ".", "PeerExtensionBits", "\n", "c", ".", "PeerID", "=", "res", ".", "PeerID", "\n", "c", ".", "completedHandshake", "=", "time", ".", "Now", "(", ")", "\n", "return", "\n", "}" ]
// Returns !ok if handshake failed for valid reasons.
[ "Returns", "!ok", "if", "handshake", "failed", "for", "valid", "reasons", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L784-L794
train
anacrolix/torrent
client.go
sendInitialMessages
func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) { if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() { conn.Post(pp.Message{ Type: pp.Extended, ExtendedID: pp.HandshakeExtendedID, ExtendedPayload: func() []byte { msg := pp.ExtendedHandshakeMessage{ M: map[pp.ExtensionName]pp.ExtensionNumber{ pp.ExtensionNameMetadata: metadataExtendedId, }, V: cl.config.ExtendedHandshakeClientVersion, Reqq: 64, // TODO: Really? YourIp: pp.CompactIp(conn.remoteAddr.IP), Encryption: !cl.config.DisableEncryption, Port: cl.incomingPeerPort(), MetadataSize: torrent.metadataSize(), // TODO: We can figured these out specific to the socket // used. Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()), Ipv6: cl.config.PublicIp6.To16(), } if !cl.config.DisablePEX { msg.M[pp.ExtensionNamePex] = pexExtendedId } return bencode.MustMarshal(msg) }(), }) } func() { if conn.fastEnabled() { if torrent.haveAllPieces() { conn.Post(pp.Message{Type: pp.HaveAll}) conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces())) return } else if !torrent.haveAnyPieces() { conn.Post(pp.Message{Type: pp.HaveNone}) conn.sentHaves.Clear() return } } conn.PostBitfield() }() if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() { conn.Post(pp.Message{ Type: pp.Port, Port: cl.dhtPort(), }) } }
go
func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) { if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() { conn.Post(pp.Message{ Type: pp.Extended, ExtendedID: pp.HandshakeExtendedID, ExtendedPayload: func() []byte { msg := pp.ExtendedHandshakeMessage{ M: map[pp.ExtensionName]pp.ExtensionNumber{ pp.ExtensionNameMetadata: metadataExtendedId, }, V: cl.config.ExtendedHandshakeClientVersion, Reqq: 64, // TODO: Really? YourIp: pp.CompactIp(conn.remoteAddr.IP), Encryption: !cl.config.DisableEncryption, Port: cl.incomingPeerPort(), MetadataSize: torrent.metadataSize(), // TODO: We can figured these out specific to the socket // used. Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()), Ipv6: cl.config.PublicIp6.To16(), } if !cl.config.DisablePEX { msg.M[pp.ExtensionNamePex] = pexExtendedId } return bencode.MustMarshal(msg) }(), }) } func() { if conn.fastEnabled() { if torrent.haveAllPieces() { conn.Post(pp.Message{Type: pp.HaveAll}) conn.sentHaves.AddRange(0, bitmap.BitIndex(conn.t.NumPieces())) return } else if !torrent.haveAnyPieces() { conn.Post(pp.Message{Type: pp.HaveNone}) conn.sentHaves.Clear() return } } conn.PostBitfield() }() if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.haveDhtServer() { conn.Post(pp.Message{ Type: pp.Port, Port: cl.dhtPort(), }) } }
[ "func", "(", "cl", "*", "Client", ")", "sendInitialMessages", "(", "conn", "*", "connection", ",", "torrent", "*", "Torrent", ")", "{", "if", "conn", ".", "PeerExtensionBytes", ".", "SupportsExtended", "(", ")", "&&", "cl", ".", "extensionBytes", ".", "SupportsExtended", "(", ")", "{", "conn", ".", "Post", "(", "pp", ".", "Message", "{", "Type", ":", "pp", ".", "Extended", ",", "ExtendedID", ":", "pp", ".", "HandshakeExtendedID", ",", "ExtendedPayload", ":", "func", "(", ")", "[", "]", "byte", "{", "msg", ":=", "pp", ".", "ExtendedHandshakeMessage", "{", "M", ":", "map", "[", "pp", ".", "ExtensionName", "]", "pp", ".", "ExtensionNumber", "{", "pp", ".", "ExtensionNameMetadata", ":", "metadataExtendedId", ",", "}", ",", "V", ":", "cl", ".", "config", ".", "ExtendedHandshakeClientVersion", ",", "Reqq", ":", "64", ",", "// TODO: Really?", "YourIp", ":", "pp", ".", "CompactIp", "(", "conn", ".", "remoteAddr", ".", "IP", ")", ",", "Encryption", ":", "!", "cl", ".", "config", ".", "DisableEncryption", ",", "Port", ":", "cl", ".", "incomingPeerPort", "(", ")", ",", "MetadataSize", ":", "torrent", ".", "metadataSize", "(", ")", ",", "// TODO: We can figured these out specific to the socket", "// used.", "Ipv4", ":", "pp", ".", "CompactIp", "(", "cl", ".", "config", ".", "PublicIp4", ".", "To4", "(", ")", ")", ",", "Ipv6", ":", "cl", ".", "config", ".", "PublicIp6", ".", "To16", "(", ")", ",", "}", "\n", "if", "!", "cl", ".", "config", ".", "DisablePEX", "{", "msg", ".", "M", "[", "pp", ".", "ExtensionNamePex", "]", "=", "pexExtendedId", "\n", "}", "\n", "return", "bencode", ".", "MustMarshal", "(", "msg", ")", "\n", "}", "(", ")", ",", "}", ")", "\n", "}", "\n", "func", "(", ")", "{", "if", "conn", ".", "fastEnabled", "(", ")", "{", "if", "torrent", ".", "haveAllPieces", "(", ")", "{", "conn", ".", "Post", "(", "pp", ".", "Message", "{", "Type", ":", "pp", ".", "HaveAll", "}", ")", "\n", "conn", ".", "sentHaves", ".", "AddRange", "(", "0", ",", "bitmap", ".", "BitIndex", "(", "conn", ".", "t", ".", "NumPieces", "(", ")", ")", ")", "\n", "return", "\n", "}", "else", "if", "!", "torrent", ".", "haveAnyPieces", "(", ")", "{", "conn", ".", "Post", "(", "pp", ".", "Message", "{", "Type", ":", "pp", ".", "HaveNone", "}", ")", "\n", "conn", ".", "sentHaves", ".", "Clear", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "conn", ".", "PostBitfield", "(", ")", "\n", "}", "(", ")", "\n", "if", "conn", ".", "PeerExtensionBytes", ".", "SupportsDHT", "(", ")", "&&", "cl", ".", "extensionBytes", ".", "SupportsDHT", "(", ")", "&&", "cl", ".", "haveDhtServer", "(", ")", "{", "conn", ".", "Post", "(", "pp", ".", "Message", "{", "Type", ":", "pp", ".", "Port", ",", "Port", ":", "cl", ".", "dhtPort", "(", ")", ",", "}", ")", "\n", "}", "\n", "}" ]
// See the order given in Transmission's tr_peerMsgsNew.
[ "See", "the", "order", "given", "in", "Transmission", "s", "tr_peerMsgsNew", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L864-L912
train
anacrolix/torrent
client.go
gotMetadataExtensionMsg
func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error { var d map[string]int err := bencode.Unmarshal(payload, &d) if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok { } else if err != nil { return fmt.Errorf("error unmarshalling bencode: %s", err) } msgType, ok := d["msg_type"] if !ok { return errors.New("missing msg_type field") } piece := d["piece"] switch msgType { case pp.DataMetadataExtensionMsgType: c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead })) if !c.requestedMetadataPiece(piece) { return fmt.Errorf("got unexpected piece %d", piece) } c.metadataRequests[piece] = false begin := len(payload) - metadataPieceSize(d["total_size"], piece) if begin < 0 || begin >= len(payload) { return fmt.Errorf("data has bad offset in payload: %d", begin) } t.saveMetadataPiece(piece, payload[begin:]) c.lastUsefulChunkReceived = time.Now() return t.maybeCompleteMetadata() case pp.RequestMetadataExtensionMsgType: if !t.haveMetadataPiece(piece) { c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil)) return nil } start := (1 << 14) * piece c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)])) return nil case pp.RejectMetadataExtensionMsgType: return nil default: return errors.New("unknown msg_type value") } }
go
func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error { var d map[string]int err := bencode.Unmarshal(payload, &d) if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok { } else if err != nil { return fmt.Errorf("error unmarshalling bencode: %s", err) } msgType, ok := d["msg_type"] if !ok { return errors.New("missing msg_type field") } piece := d["piece"] switch msgType { case pp.DataMetadataExtensionMsgType: c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead })) if !c.requestedMetadataPiece(piece) { return fmt.Errorf("got unexpected piece %d", piece) } c.metadataRequests[piece] = false begin := len(payload) - metadataPieceSize(d["total_size"], piece) if begin < 0 || begin >= len(payload) { return fmt.Errorf("data has bad offset in payload: %d", begin) } t.saveMetadataPiece(piece, payload[begin:]) c.lastUsefulChunkReceived = time.Now() return t.maybeCompleteMetadata() case pp.RequestMetadataExtensionMsgType: if !t.haveMetadataPiece(piece) { c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil)) return nil } start := (1 << 14) * piece c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)])) return nil case pp.RejectMetadataExtensionMsgType: return nil default: return errors.New("unknown msg_type value") } }
[ "func", "(", "cl", "*", "Client", ")", "gotMetadataExtensionMsg", "(", "payload", "[", "]", "byte", ",", "t", "*", "Torrent", ",", "c", "*", "connection", ")", "error", "{", "var", "d", "map", "[", "string", "]", "int", "\n", "err", ":=", "bencode", ".", "Unmarshal", "(", "payload", ",", "&", "d", ")", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "bencode", ".", "ErrUnusedTrailingBytes", ")", ";", "ok", "{", "}", "else", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "msgType", ",", "ok", ":=", "d", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "piece", ":=", "d", "[", "\"", "\"", "]", "\n", "switch", "msgType", "{", "case", "pp", ".", "DataMetadataExtensionMsgType", ":", "c", ".", "allStats", "(", "add", "(", "1", ",", "func", "(", "cs", "*", "ConnStats", ")", "*", "Count", "{", "return", "&", "cs", ".", "MetadataChunksRead", "}", ")", ")", "\n", "if", "!", "c", ".", "requestedMetadataPiece", "(", "piece", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "piece", ")", "\n", "}", "\n", "c", ".", "metadataRequests", "[", "piece", "]", "=", "false", "\n", "begin", ":=", "len", "(", "payload", ")", "-", "metadataPieceSize", "(", "d", "[", "\"", "\"", "]", ",", "piece", ")", "\n", "if", "begin", "<", "0", "||", "begin", ">=", "len", "(", "payload", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "begin", ")", "\n", "}", "\n", "t", ".", "saveMetadataPiece", "(", "piece", ",", "payload", "[", "begin", ":", "]", ")", "\n", "c", ".", "lastUsefulChunkReceived", "=", "time", ".", "Now", "(", ")", "\n", "return", "t", ".", "maybeCompleteMetadata", "(", ")", "\n", "case", "pp", ".", "RequestMetadataExtensionMsgType", ":", "if", "!", "t", ".", "haveMetadataPiece", "(", "piece", ")", "{", "c", ".", "Post", "(", "t", ".", "newMetadataExtensionMessage", "(", "c", ",", "pp", ".", "RejectMetadataExtensionMsgType", ",", "d", "[", "\"", "\"", "]", ",", "nil", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "start", ":=", "(", "1", "<<", "14", ")", "*", "piece", "\n", "c", ".", "Post", "(", "t", ".", "newMetadataExtensionMessage", "(", "c", ",", "pp", ".", "DataMetadataExtensionMsgType", ",", "piece", ",", "t", ".", "metadataBytes", "[", "start", ":", "start", "+", "t", ".", "metadataPieceSize", "(", "piece", ")", "]", ")", ")", "\n", "return", "nil", "\n", "case", "pp", ".", "RejectMetadataExtensionMsgType", ":", "return", "nil", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Process incoming ut_metadata message.
[ "Process", "incoming", "ut_metadata", "message", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L929-L968
train
anacrolix/torrent
client.go
newTorrent
func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) { // use provided storage, if provided storageClient := cl.defaultStorage if specStorage != nil { storageClient = storage.NewClient(specStorage) } t = &Torrent{ cl: cl, infoHash: ih, peers: prioritizedPeers{ om: btree.New(32), getPrio: func(p Peer) peerPriority { return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr()) }, }, conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent), halfOpen: make(map[string]Peer), pieceStateChanges: pubsub.NewPubSub(), storageOpener: storageClient, maxEstablishedConns: cl.config.EstablishedConnsPerTorrent, networkingEnabled: true, requestStrategy: 2, metadataChanged: sync.Cond{ L: cl.locker(), }, duplicateRequestTimeout: 1 * time.Second, } t.logger = cl.logger.Clone().AddValue(t) t.setChunkSize(defaultChunkSize) return }
go
func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) { // use provided storage, if provided storageClient := cl.defaultStorage if specStorage != nil { storageClient = storage.NewClient(specStorage) } t = &Torrent{ cl: cl, infoHash: ih, peers: prioritizedPeers{ om: btree.New(32), getPrio: func(p Peer) peerPriority { return bep40PriorityIgnoreError(cl.publicAddr(p.IP), p.addr()) }, }, conns: make(map[*connection]struct{}, 2*cl.config.EstablishedConnsPerTorrent), halfOpen: make(map[string]Peer), pieceStateChanges: pubsub.NewPubSub(), storageOpener: storageClient, maxEstablishedConns: cl.config.EstablishedConnsPerTorrent, networkingEnabled: true, requestStrategy: 2, metadataChanged: sync.Cond{ L: cl.locker(), }, duplicateRequestTimeout: 1 * time.Second, } t.logger = cl.logger.Clone().AddValue(t) t.setChunkSize(defaultChunkSize) return }
[ "func", "(", "cl", "*", "Client", ")", "newTorrent", "(", "ih", "metainfo", ".", "Hash", ",", "specStorage", "storage", ".", "ClientImpl", ")", "(", "t", "*", "Torrent", ")", "{", "// use provided storage, if provided", "storageClient", ":=", "cl", ".", "defaultStorage", "\n", "if", "specStorage", "!=", "nil", "{", "storageClient", "=", "storage", ".", "NewClient", "(", "specStorage", ")", "\n", "}", "\n\n", "t", "=", "&", "Torrent", "{", "cl", ":", "cl", ",", "infoHash", ":", "ih", ",", "peers", ":", "prioritizedPeers", "{", "om", ":", "btree", ".", "New", "(", "32", ")", ",", "getPrio", ":", "func", "(", "p", "Peer", ")", "peerPriority", "{", "return", "bep40PriorityIgnoreError", "(", "cl", ".", "publicAddr", "(", "p", ".", "IP", ")", ",", "p", ".", "addr", "(", ")", ")", "\n", "}", ",", "}", ",", "conns", ":", "make", "(", "map", "[", "*", "connection", "]", "struct", "{", "}", ",", "2", "*", "cl", ".", "config", ".", "EstablishedConnsPerTorrent", ")", ",", "halfOpen", ":", "make", "(", "map", "[", "string", "]", "Peer", ")", ",", "pieceStateChanges", ":", "pubsub", ".", "NewPubSub", "(", ")", ",", "storageOpener", ":", "storageClient", ",", "maxEstablishedConns", ":", "cl", ".", "config", ".", "EstablishedConnsPerTorrent", ",", "networkingEnabled", ":", "true", ",", "requestStrategy", ":", "2", ",", "metadataChanged", ":", "sync", ".", "Cond", "{", "L", ":", "cl", ".", "locker", "(", ")", ",", "}", ",", "duplicateRequestTimeout", ":", "1", "*", "time", ".", "Second", ",", "}", "\n", "t", ".", "logger", "=", "cl", ".", "logger", ".", "Clone", "(", ")", ".", "AddValue", "(", "t", ")", "\n", "t", ".", "setChunkSize", "(", "defaultChunkSize", ")", "\n", "return", "\n", "}" ]
// Return a Torrent ready for insertion into a Client.
[ "Return", "a", "Torrent", "ready", "for", "insertion", "into", "a", "Client", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L987-L1021
train
anacrolix/torrent
client.go
AddTorrentInfoHashWithStorage
func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) { cl.lock() defer cl.unlock() t, ok := cl.torrents[infoHash] if ok { return } new = true t = cl.newTorrent(infoHash, specStorage) cl.eachDhtServer(func(s *dht.Server) { go t.dhtAnnouncer(s) }) cl.torrents[infoHash] = t cl.clearAcceptLimits() t.updateWantPeersEvent() // Tickle Client.waitAccept, new torrent may want conns. cl.event.Broadcast() return }
go
func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) { cl.lock() defer cl.unlock() t, ok := cl.torrents[infoHash] if ok { return } new = true t = cl.newTorrent(infoHash, specStorage) cl.eachDhtServer(func(s *dht.Server) { go t.dhtAnnouncer(s) }) cl.torrents[infoHash] = t cl.clearAcceptLimits() t.updateWantPeersEvent() // Tickle Client.waitAccept, new torrent may want conns. cl.event.Broadcast() return }
[ "func", "(", "cl", "*", "Client", ")", "AddTorrentInfoHashWithStorage", "(", "infoHash", "metainfo", ".", "Hash", ",", "specStorage", "storage", ".", "ClientImpl", ")", "(", "t", "*", "Torrent", ",", "new", "bool", ")", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "t", ",", "ok", ":=", "cl", ".", "torrents", "[", "infoHash", "]", "\n", "if", "ok", "{", "return", "\n", "}", "\n", "new", "=", "true", "\n\n", "t", "=", "cl", ".", "newTorrent", "(", "infoHash", ",", "specStorage", ")", "\n", "cl", ".", "eachDhtServer", "(", "func", "(", "s", "*", "dht", ".", "Server", ")", "{", "go", "t", ".", "dhtAnnouncer", "(", "s", ")", "\n", "}", ")", "\n", "cl", ".", "torrents", "[", "infoHash", "]", "=", "t", "\n", "cl", ".", "clearAcceptLimits", "(", ")", "\n", "t", ".", "updateWantPeersEvent", "(", ")", "\n", "// Tickle Client.waitAccept, new torrent may want conns.", "cl", ".", "event", ".", "Broadcast", "(", ")", "\n", "return", "\n", "}" ]
// Adds a torrent by InfoHash with a custom Storage implementation. // If the torrent already exists then this Storage is ignored and the // existing torrent returned with `new` set to `false`
[ "Adds", "a", "torrent", "by", "InfoHash", "with", "a", "custom", "Storage", "implementation", ".", "If", "the", "torrent", "already", "exists", "then", "this", "Storage", "is", "ignored", "and", "the", "existing", "torrent", "returned", "with", "new", "set", "to", "false" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1038-L1057
train
anacrolix/torrent
client.go
WaitAll
func (cl *Client) WaitAll() bool { cl.lock() defer cl.unlock() for !cl.allTorrentsCompleted() { if cl.closed.IsSet() { return false } cl.event.Wait() } return true }
go
func (cl *Client) WaitAll() bool { cl.lock() defer cl.unlock() for !cl.allTorrentsCompleted() { if cl.closed.IsSet() { return false } cl.event.Wait() } return true }
[ "func", "(", "cl", "*", "Client", ")", "WaitAll", "(", ")", "bool", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "for", "!", "cl", ".", "allTorrentsCompleted", "(", ")", "{", "if", "cl", ".", "closed", ".", "IsSet", "(", ")", "{", "return", "false", "\n", "}", "\n", "cl", ".", "event", ".", "Wait", "(", ")", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Returns true when all torrents are completely downloaded and false if the // client is stopped before that.
[ "Returns", "true", "when", "all", "torrents", "are", "completely", "downloaded", "and", "false", "if", "the", "client", "is", "stopped", "before", "that", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1114-L1124
train
anacrolix/torrent
client.go
Torrents
func (cl *Client) Torrents() []*Torrent { cl.lock() defer cl.unlock() return cl.torrentsAsSlice() }
go
func (cl *Client) Torrents() []*Torrent { cl.lock() defer cl.unlock() return cl.torrentsAsSlice() }
[ "func", "(", "cl", "*", "Client", ")", "Torrents", "(", ")", "[", "]", "*", "Torrent", "{", "cl", ".", "lock", "(", ")", "\n", "defer", "cl", ".", "unlock", "(", ")", "\n", "return", "cl", ".", "torrentsAsSlice", "(", ")", "\n", "}" ]
// Returns handles to all the torrents loaded in the Client.
[ "Returns", "handles", "to", "all", "the", "torrents", "loaded", "in", "the", "Client", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1127-L1131
train
anacrolix/torrent
client.go
publicAddr
func (cl *Client) publicAddr(peer net.IP) IpPort { return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())} }
go
func (cl *Client) publicAddr(peer net.IP) IpPort { return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())} }
[ "func", "(", "cl", "*", "Client", ")", "publicAddr", "(", "peer", "net", ".", "IP", ")", "IpPort", "{", "return", "IpPort", "{", "cl", ".", "publicIp", "(", "peer", ")", ",", "uint16", "(", "cl", ".", "incomingPeerPort", "(", ")", ")", "}", "\n", "}" ]
// Our IP as a peer should see it.
[ "Our", "IP", "as", "a", "peer", "should", "see", "it", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1277-L1279
train
anacrolix/torrent
mse/mse.go
postY
func (h *handshake) postY(x *big.Int) error { var y big.Int y.Exp(&g, x, &p) return h.postWrite(paddedLeft(y.Bytes(), 96)) }
go
func (h *handshake) postY(x *big.Int) error { var y big.Int y.Exp(&g, x, &p) return h.postWrite(paddedLeft(y.Bytes(), 96)) }
[ "func", "(", "h", "*", "handshake", ")", "postY", "(", "x", "*", "big", ".", "Int", ")", "error", "{", "var", "y", "big", ".", "Int", "\n", "y", ".", "Exp", "(", "&", "g", ",", "x", ",", "&", "p", ")", "\n", "return", "h", ".", "postWrite", "(", "paddedLeft", "(", "y", ".", "Bytes", "(", ")", ",", "96", ")", ")", "\n", "}" ]
// Calculate, and send Y, our public key.
[ "Calculate", "and", "send", "Y", "our", "public", "key", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L175-L179
train
anacrolix/torrent
mse/mse.go
suffixMatchLen
func suffixMatchLen(a, b []byte) int { if len(b) > len(a) { b = b[:len(a)] } // i is how much of b to try to match for i := len(b); i > 0; i-- { // j is how many chars we've compared j := 0 for ; j < i; j++ { if b[i-1-j] != a[len(a)-1-j] { goto shorter } } return j shorter: } return 0 }
go
func suffixMatchLen(a, b []byte) int { if len(b) > len(a) { b = b[:len(a)] } // i is how much of b to try to match for i := len(b); i > 0; i-- { // j is how many chars we've compared j := 0 for ; j < i; j++ { if b[i-1-j] != a[len(a)-1-j] { goto shorter } } return j shorter: } return 0 }
[ "func", "suffixMatchLen", "(", "a", ",", "b", "[", "]", "byte", ")", "int", "{", "if", "len", "(", "b", ")", ">", "len", "(", "a", ")", "{", "b", "=", "b", "[", ":", "len", "(", "a", ")", "]", "\n", "}", "\n", "// i is how much of b to try to match", "for", "i", ":=", "len", "(", "b", ")", ";", "i", ">", "0", ";", "i", "--", "{", "// j is how many chars we've compared", "j", ":=", "0", "\n", "for", ";", "j", "<", "i", ";", "j", "++", "{", "if", "b", "[", "i", "-", "1", "-", "j", "]", "!=", "a", "[", "len", "(", "a", ")", "-", "1", "-", "j", "]", "{", "goto", "shorter", "\n", "}", "\n", "}", "\n", "return", "j", "\n", "shorter", ":", "}", "\n", "return", "0", "\n", "}" ]
// Looking for b at the end of a.
[ "Looking", "for", "b", "at", "the", "end", "of", "a", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L322-L339
train
anacrolix/torrent
mse/mse.go
readUntil
func readUntil(r io.Reader, b []byte) error { b1 := make([]byte, len(b)) i := 0 for { _, err := io.ReadFull(r, b1[i:]) if err != nil { return err } i = suffixMatchLen(b1, b) if i == len(b) { break } if copy(b1, b1[len(b1)-i:]) != i { panic("wat") } } return nil }
go
func readUntil(r io.Reader, b []byte) error { b1 := make([]byte, len(b)) i := 0 for { _, err := io.ReadFull(r, b1[i:]) if err != nil { return err } i = suffixMatchLen(b1, b) if i == len(b) { break } if copy(b1, b1[len(b1)-i:]) != i { panic("wat") } } return nil }
[ "func", "readUntil", "(", "r", "io", ".", "Reader", ",", "b", "[", "]", "byte", ")", "error", "{", "b1", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "b", ")", ")", "\n", "i", ":=", "0", "\n", "for", "{", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "b1", "[", "i", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "i", "=", "suffixMatchLen", "(", "b1", ",", "b", ")", "\n", "if", "i", "==", "len", "(", "b", ")", "{", "break", "\n", "}", "\n", "if", "copy", "(", "b1", ",", "b1", "[", "len", "(", "b1", ")", "-", "i", ":", "]", ")", "!=", "i", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Reads from r until b has been seen. Keeps the minimum amount of data in // memory.
[ "Reads", "from", "r", "until", "b", "has", "been", "seen", ".", "Keeps", "the", "minimum", "amount", "of", "data", "in", "memory", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L343-L360
train
anacrolix/torrent
tracker/peer.go
fromDictInterface
func (p *Peer) fromDictInterface(d map[string]interface{}) { p.IP = net.ParseIP(d["ip"].(string)) if _, ok := d["peer id"]; ok { p.ID = []byte(d["peer id"].(string)) } p.Port = int(d["port"].(int64)) }
go
func (p *Peer) fromDictInterface(d map[string]interface{}) { p.IP = net.ParseIP(d["ip"].(string)) if _, ok := d["peer id"]; ok { p.ID = []byte(d["peer id"].(string)) } p.Port = int(d["port"].(int64)) }
[ "func", "(", "p", "*", "Peer", ")", "fromDictInterface", "(", "d", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "p", ".", "IP", "=", "net", ".", "ParseIP", "(", "d", "[", "\"", "\"", "]", ".", "(", "string", ")", ")", "\n", "if", "_", ",", "ok", ":=", "d", "[", "\"", "\"", "]", ";", "ok", "{", "p", ".", "ID", "=", "[", "]", "byte", "(", "d", "[", "\"", "\"", "]", ".", "(", "string", ")", ")", "\n", "}", "\n", "p", ".", "Port", "=", "int", "(", "d", "[", "\"", "\"", "]", ".", "(", "int64", ")", ")", "\n", "}" ]
// Set from the non-compact form in BEP 3.
[ "Set", "from", "the", "non", "-", "compact", "form", "in", "BEP", "3", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/peer.go#L16-L22
train
anacrolix/torrent
metainfo/announcelist.go
OverridesAnnounce
func (al AnnounceList) OverridesAnnounce(announce string) bool { for _, tier := range al { for _, url := range tier { if url != "" || announce == "" { return true } } } return false }
go
func (al AnnounceList) OverridesAnnounce(announce string) bool { for _, tier := range al { for _, url := range tier { if url != "" || announce == "" { return true } } } return false }
[ "func", "(", "al", "AnnounceList", ")", "OverridesAnnounce", "(", "announce", "string", ")", "bool", "{", "for", "_", ",", "tier", ":=", "range", "al", "{", "for", "_", ",", "url", ":=", "range", "tier", "{", "if", "url", "!=", "\"", "\"", "||", "announce", "==", "\"", "\"", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Whether the AnnounceList should be preferred over a single URL announce.
[ "Whether", "the", "AnnounceList", "should", "be", "preferred", "over", "a", "single", "URL", "announce", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/announcelist.go#L6-L15
train
anacrolix/torrent
prioritized_peers.go
Add
func (me *prioritizedPeers) Add(p Peer) bool { return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil }
go
func (me *prioritizedPeers) Add(p Peer) bool { return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil }
[ "func", "(", "me", "*", "prioritizedPeers", ")", "Add", "(", "p", "Peer", ")", "bool", "{", "return", "me", ".", "om", ".", "ReplaceOrInsert", "(", "prioritizedPeersItem", "{", "me", ".", "getPrio", "(", "p", ")", ",", "p", "}", ")", "!=", "nil", "\n", "}" ]
// Returns true if a peer is replaced.
[ "Returns", "true", "if", "a", "peer", "is", "replaced", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/prioritized_peers.go#L33-L35
train
anacrolix/torrent
storage/file.go
defaultPathMaker
func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string { return baseDir }
go
func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string { return baseDir }
[ "func", "defaultPathMaker", "(", "baseDir", "string", ",", "info", "*", "metainfo", ".", "Info", ",", "infoHash", "metainfo", ".", "Hash", ")", "string", "{", "return", "baseDir", "\n", "}" ]
// The Default path maker just returns the current path
[ "The", "Default", "path", "maker", "just", "returns", "the", "current", "path" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L21-L23
train
anacrolix/torrent
storage/file.go
NewFileWithCustomPathMaker
func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl { return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir)) }
go
func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl { return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir)) }
[ "func", "NewFileWithCustomPathMaker", "(", "baseDir", "string", ",", "pathMaker", "func", "(", "baseDir", "string", ",", "info", "*", "metainfo", ".", "Info", ",", "infoHash", "metainfo", ".", "Hash", ")", "string", ")", "ClientImpl", "{", "return", "newFileWithCustomPathMakerAndCompletion", "(", "baseDir", ",", "pathMaker", ",", "pieceCompletionForDir", "(", "baseDir", ")", ")", "\n", "}" ]
// Allows passing a function to determine the path for storing torrent data
[ "Allows", "passing", "a", "function", "to", "determine", "the", "path", "for", "storing", "torrent", "data" ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L44-L46
train
anacrolix/torrent
storage/file.go
CreateNativeZeroLengthFiles
func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) { for _, fi := range info.UpvertedFiles() { if fi.Length != 0 { continue } name := filepath.Join(append([]string{dir, info.Name}, fi.Path...)...) os.MkdirAll(filepath.Dir(name), 0777) var f io.Closer f, err = os.Create(name) if err != nil { break } f.Close() } return }
go
func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) { for _, fi := range info.UpvertedFiles() { if fi.Length != 0 { continue } name := filepath.Join(append([]string{dir, info.Name}, fi.Path...)...) os.MkdirAll(filepath.Dir(name), 0777) var f io.Closer f, err = os.Create(name) if err != nil { break } f.Close() } return }
[ "func", "CreateNativeZeroLengthFiles", "(", "info", "*", "metainfo", ".", "Info", ",", "dir", "string", ")", "(", "err", "error", ")", "{", "for", "_", ",", "fi", ":=", "range", "info", ".", "UpvertedFiles", "(", ")", "{", "if", "fi", ".", "Length", "!=", "0", "{", "continue", "\n", "}", "\n", "name", ":=", "filepath", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "dir", ",", "info", ".", "Name", "}", ",", "fi", ".", "Path", "...", ")", "...", ")", "\n", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "name", ")", ",", "0777", ")", "\n", "var", "f", "io", ".", "Closer", "\n", "f", ",", "err", "=", "os", ".", "Create", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "f", ".", "Close", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Creates natives files for any zero-length file entries in the info. This is // a helper for file-based storages, which don't address or write to zero- // length files because they have no corresponding pieces.
[ "Creates", "natives", "files", "for", "any", "zero", "-", "length", "file", "entries", "in", "the", "info", ".", "This", "is", "a", "helper", "for", "file", "-", "based", "storages", "which", "don", "t", "address", "or", "write", "to", "zero", "-", "length", "files", "because", "they", "have", "no", "corresponding", "pieces", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L103-L118
train
anacrolix/torrent
storage/file.go
readFileAt
func (fst *fileTorrentImplIO) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) { f, err := os.Open(fst.fts.fileInfoName(fi)) if os.IsNotExist(err) { // File missing is treated the same as a short file. err = io.EOF return } if err != nil { return } defer f.Close() // Limit the read to within the expected bounds of this file. if int64(len(b)) > fi.Length-off { b = b[:fi.Length-off] } for off < fi.Length && len(b) != 0 { n1, err1 := f.ReadAt(b, off) b = b[n1:] n += n1 off += int64(n1) if n1 == 0 { err = err1 break } } return }
go
func (fst *fileTorrentImplIO) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) { f, err := os.Open(fst.fts.fileInfoName(fi)) if os.IsNotExist(err) { // File missing is treated the same as a short file. err = io.EOF return } if err != nil { return } defer f.Close() // Limit the read to within the expected bounds of this file. if int64(len(b)) > fi.Length-off { b = b[:fi.Length-off] } for off < fi.Length && len(b) != 0 { n1, err1 := f.ReadAt(b, off) b = b[n1:] n += n1 off += int64(n1) if n1 == 0 { err = err1 break } } return }
[ "func", "(", "fst", "*", "fileTorrentImplIO", ")", "readFileAt", "(", "fi", "metainfo", ".", "FileInfo", ",", "b", "[", "]", "byte", ",", "off", "int64", ")", "(", "n", "int", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "fst", ".", "fts", ".", "fileInfoName", "(", "fi", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// File missing is treated the same as a short file.", "err", "=", "io", ".", "EOF", "\n", "return", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "// Limit the read to within the expected bounds of this file.", "if", "int64", "(", "len", "(", "b", ")", ")", ">", "fi", ".", "Length", "-", "off", "{", "b", "=", "b", "[", ":", "fi", ".", "Length", "-", "off", "]", "\n", "}", "\n", "for", "off", "<", "fi", ".", "Length", "&&", "len", "(", "b", ")", "!=", "0", "{", "n1", ",", "err1", ":=", "f", ".", "ReadAt", "(", "b", ",", "off", ")", "\n", "b", "=", "b", "[", "n1", ":", "]", "\n", "n", "+=", "n1", "\n", "off", "+=", "int64", "(", "n1", ")", "\n", "if", "n1", "==", "0", "{", "err", "=", "err1", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Returns EOF on short or missing file.
[ "Returns", "EOF", "on", "short", "or", "missing", "file", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L126-L152
train
anacrolix/torrent
storage/file.go
ReadAt
func (fst fileTorrentImplIO) ReadAt(b []byte, off int64) (n int, err error) { for _, fi := range fst.fts.info.UpvertedFiles() { for off < fi.Length { n1, err1 := fst.readFileAt(fi, b, off) n += n1 off += int64(n1) b = b[n1:] if len(b) == 0 { // Got what we need. return } if n1 != 0 { // Made progress. continue } err = err1 if err == io.EOF { // Lies. err = io.ErrUnexpectedEOF } return } off -= fi.Length } err = io.EOF return }
go
func (fst fileTorrentImplIO) ReadAt(b []byte, off int64) (n int, err error) { for _, fi := range fst.fts.info.UpvertedFiles() { for off < fi.Length { n1, err1 := fst.readFileAt(fi, b, off) n += n1 off += int64(n1) b = b[n1:] if len(b) == 0 { // Got what we need. return } if n1 != 0 { // Made progress. continue } err = err1 if err == io.EOF { // Lies. err = io.ErrUnexpectedEOF } return } off -= fi.Length } err = io.EOF return }
[ "func", "(", "fst", "fileTorrentImplIO", ")", "ReadAt", "(", "b", "[", "]", "byte", ",", "off", "int64", ")", "(", "n", "int", ",", "err", "error", ")", "{", "for", "_", ",", "fi", ":=", "range", "fst", ".", "fts", ".", "info", ".", "UpvertedFiles", "(", ")", "{", "for", "off", "<", "fi", ".", "Length", "{", "n1", ",", "err1", ":=", "fst", ".", "readFileAt", "(", "fi", ",", "b", ",", "off", ")", "\n", "n", "+=", "n1", "\n", "off", "+=", "int64", "(", "n1", ")", "\n", "b", "=", "b", "[", "n1", ":", "]", "\n", "if", "len", "(", "b", ")", "==", "0", "{", "// Got what we need.", "return", "\n", "}", "\n", "if", "n1", "!=", "0", "{", "// Made progress.", "continue", "\n", "}", "\n", "err", "=", "err1", "\n", "if", "err", "==", "io", ".", "EOF", "{", "// Lies.", "err", "=", "io", ".", "ErrUnexpectedEOF", "\n", "}", "\n", "return", "\n", "}", "\n", "off", "-=", "fi", ".", "Length", "\n", "}", "\n", "err", "=", "io", ".", "EOF", "\n", "return", "\n", "}" ]
// Only returns EOF at the end of the torrent. Premature EOF is ErrUnexpectedEOF.
[ "Only", "returns", "EOF", "at", "the", "end", "of", "the", "torrent", ".", "Premature", "EOF", "is", "ErrUnexpectedEOF", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L155-L181
train
anacrolix/torrent
t.go
Info
func (t *Torrent) Info() *metainfo.Info { t.cl.lock() defer t.cl.unlock() return t.info }
go
func (t *Torrent) Info() *metainfo.Info { t.cl.lock() defer t.cl.unlock() return t.info }
[ "func", "(", "t", "*", "Torrent", ")", "Info", "(", ")", "*", "metainfo", ".", "Info", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "return", "t", ".", "info", "\n", "}" ]
// Returns the metainfo info dictionary, or nil if it's not yet available.
[ "Returns", "the", "metainfo", "info", "dictionary", "or", "nil", "if", "it", "s", "not", "yet", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L26-L30
train
anacrolix/torrent
t.go
NewReader
func (t *Torrent) NewReader() Reader { r := reader{ mu: t.cl.locker(), t: t, readahead: 5 * 1024 * 1024, length: *t.length, } t.addReader(&r) return &r }
go
func (t *Torrent) NewReader() Reader { r := reader{ mu: t.cl.locker(), t: t, readahead: 5 * 1024 * 1024, length: *t.length, } t.addReader(&r) return &r }
[ "func", "(", "t", "*", "Torrent", ")", "NewReader", "(", ")", "Reader", "{", "r", ":=", "reader", "{", "mu", ":", "t", ".", "cl", ".", "locker", "(", ")", ",", "t", ":", "t", ",", "readahead", ":", "5", "*", "1024", "*", "1024", ",", "length", ":", "*", "t", ".", "length", ",", "}", "\n", "t", ".", "addReader", "(", "&", "r", ")", "\n", "return", "&", "r", "\n", "}" ]
// Returns a Reader bound to the torrent's data. All read calls block until // the data requested is actually available.
[ "Returns", "a", "Reader", "bound", "to", "the", "torrent", "s", "data", ".", "All", "read", "calls", "block", "until", "the", "data", "requested", "is", "actually", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L34-L43
train
anacrolix/torrent
t.go
PieceStateRuns
func (t *Torrent) PieceStateRuns() []PieceStateRun { t.cl.rLock() defer t.cl.rUnlock() return t.pieceStateRuns() }
go
func (t *Torrent) PieceStateRuns() []PieceStateRun { t.cl.rLock() defer t.cl.rUnlock() return t.pieceStateRuns() }
[ "func", "(", "t", "*", "Torrent", ")", "PieceStateRuns", "(", ")", "[", "]", "PieceStateRun", "{", "t", ".", "cl", ".", "rLock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "rUnlock", "(", ")", "\n", "return", "t", ".", "pieceStateRuns", "(", ")", "\n", "}" ]
// Returns the state of pieces of the torrent. They are grouped into runs of // same state. The sum of the state run lengths is the number of pieces // in the torrent.
[ "Returns", "the", "state", "of", "pieces", "of", "the", "torrent", ".", "They", "are", "grouped", "into", "runs", "of", "same", "state", ".", "The", "sum", "of", "the", "state", "run", "lengths", "is", "the", "number", "of", "pieces", "in", "the", "torrent", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L48-L52
train
anacrolix/torrent
t.go
PieceBytesMissing
func (t *Torrent) PieceBytesMissing(piece int) int64 { t.cl.lock() defer t.cl.unlock() return int64(t.pieces[piece].bytesLeft()) }
go
func (t *Torrent) PieceBytesMissing(piece int) int64 { t.cl.lock() defer t.cl.unlock() return int64(t.pieces[piece].bytesLeft()) }
[ "func", "(", "t", "*", "Torrent", ")", "PieceBytesMissing", "(", "piece", "int", ")", "int64", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "unlock", "(", ")", "\n\n", "return", "int64", "(", "t", ".", "pieces", "[", "piece", "]", ".", "bytesLeft", "(", ")", ")", "\n", "}" ]
// Get missing bytes count for specific piece.
[ "Get", "missing", "bytes", "count", "for", "specific", "piece", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L67-L72
train
anacrolix/torrent
t.go
Drop
func (t *Torrent) Drop() { t.cl.lock() t.cl.dropTorrent(t.infoHash) t.cl.unlock() }
go
func (t *Torrent) Drop() { t.cl.lock() t.cl.dropTorrent(t.infoHash) t.cl.unlock() }
[ "func", "(", "t", "*", "Torrent", ")", "Drop", "(", ")", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "t", ".", "cl", ".", "dropTorrent", "(", "t", ".", "infoHash", ")", "\n", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "}" ]
// Drop the torrent from the client, and close it. It's always safe to do // this. No data corruption can, or should occur to either the torrent's data, // or connected peers.
[ "Drop", "the", "torrent", "from", "the", "client", "and", "close", "it", ".", "It", "s", "always", "safe", "to", "do", "this", ".", "No", "data", "corruption", "can", "or", "should", "occur", "to", "either", "the", "torrent", "s", "data", "or", "connected", "peers", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L77-L81
train
anacrolix/torrent
t.go
BytesCompleted
func (t *Torrent) BytesCompleted() int64 { t.cl.rLock() defer t.cl.rUnlock() return t.bytesCompleted() }
go
func (t *Torrent) BytesCompleted() int64 { t.cl.rLock() defer t.cl.rUnlock() return t.bytesCompleted() }
[ "func", "(", "t", "*", "Torrent", ")", "BytesCompleted", "(", ")", "int64", "{", "t", ".", "cl", ".", "rLock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "rUnlock", "(", ")", "\n", "return", "t", ".", "bytesCompleted", "(", ")", "\n", "}" ]
// Number of bytes of the entire torrent we have completed. This is the sum of // completed pieces, and dirtied chunks of incomplete pieces. Do not use this // for download rate, as it can go down when pieces are lost or fail checks. // Sample Torrent.Stats.DataBytesRead for actual file data download rate.
[ "Number", "of", "bytes", "of", "the", "entire", "torrent", "we", "have", "completed", ".", "This", "is", "the", "sum", "of", "completed", "pieces", "and", "dirtied", "chunks", "of", "incomplete", "pieces", ".", "Do", "not", "use", "this", "for", "download", "rate", "as", "it", "can", "go", "down", "when", "pieces", "are", "lost", "or", "fail", "checks", ".", "Sample", "Torrent", ".", "Stats", ".", "DataBytesRead", "for", "actual", "file", "data", "download", "rate", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L87-L91
train
anacrolix/torrent
t.go
Seeding
func (t *Torrent) Seeding() bool { t.cl.lock() defer t.cl.unlock() return t.seeding() }
go
func (t *Torrent) Seeding() bool { t.cl.lock() defer t.cl.unlock() return t.seeding() }
[ "func", "(", "t", "*", "Torrent", ")", "Seeding", "(", ")", "bool", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "return", "t", ".", "seeding", "(", ")", "\n", "}" ]
// Returns true if the torrent is currently being seeded. This occurs when the // client is willing to upload without wanting anything in return.
[ "Returns", "true", "if", "the", "torrent", "is", "currently", "being", "seeded", ".", "This", "occurs", "when", "the", "client", "is", "willing", "to", "upload", "without", "wanting", "anything", "in", "return", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L101-L105
train
anacrolix/torrent
t.go
SetDisplayName
func (t *Torrent) SetDisplayName(dn string) { t.nameMu.Lock() defer t.nameMu.Unlock() if t.haveInfo() { return } t.displayName = dn }
go
func (t *Torrent) SetDisplayName(dn string) { t.nameMu.Lock() defer t.nameMu.Unlock() if t.haveInfo() { return } t.displayName = dn }
[ "func", "(", "t", "*", "Torrent", ")", "SetDisplayName", "(", "dn", "string", ")", "{", "t", ".", "nameMu", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "nameMu", ".", "Unlock", "(", ")", "\n", "if", "t", ".", "haveInfo", "(", ")", "{", "return", "\n", "}", "\n", "t", ".", "displayName", "=", "dn", "\n", "}" ]
// Clobbers the torrent display name. The display name is used as the torrent // name if the metainfo is not available.
[ "Clobbers", "the", "torrent", "display", "name", ".", "The", "display", "name", "is", "used", "as", "the", "torrent", "name", "if", "the", "metainfo", "is", "not", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L109-L116
train
anacrolix/torrent
t.go
Metainfo
func (t *Torrent) Metainfo() metainfo.MetaInfo { t.cl.lock() defer t.cl.unlock() return t.newMetaInfo() }
go
func (t *Torrent) Metainfo() metainfo.MetaInfo { t.cl.lock() defer t.cl.unlock() return t.newMetaInfo() }
[ "func", "(", "t", "*", "Torrent", ")", "Metainfo", "(", ")", "metainfo", ".", "MetaInfo", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "return", "t", ".", "newMetaInfo", "(", ")", "\n", "}" ]
// Returns a run-time generated metainfo for the torrent that includes the // info bytes and announce-list as currently known to the client.
[ "Returns", "a", "run", "-", "time", "generated", "metainfo", "for", "the", "torrent", "that", "includes", "the", "info", "bytes", "and", "announce", "-", "list", "as", "currently", "known", "to", "the", "client", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L132-L136
train
anacrolix/torrent
t.go
DownloadPieces
func (t *Torrent) DownloadPieces(begin, end pieceIndex) { t.cl.lock() defer t.cl.unlock() t.downloadPiecesLocked(begin, end) }
go
func (t *Torrent) DownloadPieces(begin, end pieceIndex) { t.cl.lock() defer t.cl.unlock() t.downloadPiecesLocked(begin, end) }
[ "func", "(", "t", "*", "Torrent", ")", "DownloadPieces", "(", "begin", ",", "end", "pieceIndex", ")", "{", "t", ".", "cl", ".", "lock", "(", ")", "\n", "defer", "t", ".", "cl", ".", "unlock", "(", ")", "\n", "t", ".", "downloadPiecesLocked", "(", "begin", ",", "end", ")", "\n", "}" ]
// Raise the priorities of pieces in the range [begin, end) to at least Normal // priority. Piece indexes are not the same as bytes. Requires that the info // has been obtained, see Torrent.Info and Torrent.GotInfo.
[ "Raise", "the", "priorities", "of", "pieces", "in", "the", "range", "[", "begin", "end", ")", "to", "at", "least", "Normal", "priority", ".", "Piece", "indexes", "are", "not", "the", "same", "as", "bytes", ".", "Requires", "that", "the", "info", "has", "been", "obtained", "see", "Torrent", ".", "Info", "and", "Torrent", ".", "GotInfo", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L156-L160
train
anacrolix/torrent
torrent.go
KnownSwarm
func (t *Torrent) KnownSwarm() (ks []Peer) { // Add pending peers to the list t.peers.Each(func(peer Peer) { ks = append(ks, peer) }) // Add half-open peers to the list for _, peer := range t.halfOpen { ks = append(ks, peer) } // Add active peers to the list for conn := range t.conns { ks = append(ks, Peer{ Id: conn.PeerID, IP: conn.remoteAddr.IP, Port: int(conn.remoteAddr.Port), Source: conn.Discovery, // > If the connection is encrypted, that's certainly enough to set SupportsEncryption. // > But if we're not connected to them with an encrypted connection, I couldn't say // > what's appropriate. We can carry forward the SupportsEncryption value as we // > received it from trackers/DHT/PEX, or just use the encryption state for the // > connection. It's probably easiest to do the latter for now. // https://github.com/anacrolix/torrent/pull/188 SupportsEncryption: conn.headerEncrypted, }) } return }
go
func (t *Torrent) KnownSwarm() (ks []Peer) { // Add pending peers to the list t.peers.Each(func(peer Peer) { ks = append(ks, peer) }) // Add half-open peers to the list for _, peer := range t.halfOpen { ks = append(ks, peer) } // Add active peers to the list for conn := range t.conns { ks = append(ks, Peer{ Id: conn.PeerID, IP: conn.remoteAddr.IP, Port: int(conn.remoteAddr.Port), Source: conn.Discovery, // > If the connection is encrypted, that's certainly enough to set SupportsEncryption. // > But if we're not connected to them with an encrypted connection, I couldn't say // > what's appropriate. We can carry forward the SupportsEncryption value as we // > received it from trackers/DHT/PEX, or just use the encryption state for the // > connection. It's probably easiest to do the latter for now. // https://github.com/anacrolix/torrent/pull/188 SupportsEncryption: conn.headerEncrypted, }) } return }
[ "func", "(", "t", "*", "Torrent", ")", "KnownSwarm", "(", ")", "(", "ks", "[", "]", "Peer", ")", "{", "// Add pending peers to the list", "t", ".", "peers", ".", "Each", "(", "func", "(", "peer", "Peer", ")", "{", "ks", "=", "append", "(", "ks", ",", "peer", ")", "\n", "}", ")", "\n\n", "// Add half-open peers to the list", "for", "_", ",", "peer", ":=", "range", "t", ".", "halfOpen", "{", "ks", "=", "append", "(", "ks", ",", "peer", ")", "\n", "}", "\n\n", "// Add active peers to the list", "for", "conn", ":=", "range", "t", ".", "conns", "{", "ks", "=", "append", "(", "ks", ",", "Peer", "{", "Id", ":", "conn", ".", "PeerID", ",", "IP", ":", "conn", ".", "remoteAddr", ".", "IP", ",", "Port", ":", "int", "(", "conn", ".", "remoteAddr", ".", "Port", ")", ",", "Source", ":", "conn", ".", "Discovery", ",", "// > If the connection is encrypted, that's certainly enough to set SupportsEncryption.", "// > But if we're not connected to them with an encrypted connection, I couldn't say", "// > what's appropriate. We can carry forward the SupportsEncryption value as we", "// > received it from trackers/DHT/PEX, or just use the encryption state for the", "// > connection. It's probably easiest to do the latter for now.", "// https://github.com/anacrolix/torrent/pull/188", "SupportsEncryption", ":", "conn", ".", "headerEncrypted", ",", "}", ")", "\n", "}", "\n\n", "return", "\n", "}" ]
// KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active, // pending, and half-open peers.
[ "KnownSwarm", "returns", "the", "known", "subset", "of", "the", "peers", "in", "the", "Torrent", "s", "swarm", "including", "active", "pending", "and", "half", "-", "open", "peers", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L157-L187
train
anacrolix/torrent
torrent.go
addrActive
func (t *Torrent) addrActive(addr string) bool { if _, ok := t.halfOpen[addr]; ok { return true } for c := range t.conns { ra := c.remoteAddr if ra.String() == addr { return true } } return false }
go
func (t *Torrent) addrActive(addr string) bool { if _, ok := t.halfOpen[addr]; ok { return true } for c := range t.conns { ra := c.remoteAddr if ra.String() == addr { return true } } return false }
[ "func", "(", "t", "*", "Torrent", ")", "addrActive", "(", "addr", "string", ")", "bool", "{", "if", "_", ",", "ok", ":=", "t", ".", "halfOpen", "[", "addr", "]", ";", "ok", "{", "return", "true", "\n", "}", "\n", "for", "c", ":=", "range", "t", ".", "conns", "{", "ra", ":=", "c", ".", "remoteAddr", "\n", "if", "ra", ".", "String", "(", ")", "==", "addr", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// There's a connection to that address already.
[ "There", "s", "a", "connection", "to", "that", "address", "already", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L208-L219
train
anacrolix/torrent
torrent.go
pieceFirstFileIndex
func pieceFirstFileIndex(pieceOffset int64, files []*File) int { for i, f := range files { if f.offset+f.length > pieceOffset { return i } } return 0 }
go
func pieceFirstFileIndex(pieceOffset int64, files []*File) int { for i, f := range files { if f.offset+f.length > pieceOffset { return i } } return 0 }
[ "func", "pieceFirstFileIndex", "(", "pieceOffset", "int64", ",", "files", "[", "]", "*", "File", ")", "int", "{", "for", "i", ",", "f", ":=", "range", "files", "{", "if", "f", ".", "offset", "+", "f", ".", "length", ">", "pieceOffset", "{", "return", "i", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Returns the index of the first file containing the piece. files must be // ordered by offset.
[ "Returns", "the", "index", "of", "the", "first", "file", "containing", "the", "piece", ".", "files", "must", "be", "ordered", "by", "offset", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L315-L322
train
anacrolix/torrent
torrent.go
pieceEndFileIndex
func pieceEndFileIndex(pieceEndOffset int64, files []*File) int { for i, f := range files { if f.offset+f.length >= pieceEndOffset { return i + 1 } } return 0 }
go
func pieceEndFileIndex(pieceEndOffset int64, files []*File) int { for i, f := range files { if f.offset+f.length >= pieceEndOffset { return i + 1 } } return 0 }
[ "func", "pieceEndFileIndex", "(", "pieceEndOffset", "int64", ",", "files", "[", "]", "*", "File", ")", "int", "{", "for", "i", ",", "f", ":=", "range", "files", "{", "if", "f", ".", "offset", "+", "f", ".", "length", ">=", "pieceEndOffset", "{", "return", "i", "+", "1", "\n", "}", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Returns the index after the last file containing the piece. files must be // ordered by offset.
[ "Returns", "the", "index", "after", "the", "last", "file", "containing", "the", "piece", ".", "files", "must", "be", "ordered", "by", "offset", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L326-L333
train
anacrolix/torrent
torrent.go
setInfoBytes
func (t *Torrent) setInfoBytes(b []byte) error { if metainfo.HashBytes(b) != t.infoHash { return errors.New("info bytes have wrong hash") } var info metainfo.Info if err := bencode.Unmarshal(b, &info); err != nil { return fmt.Errorf("error unmarshalling info bytes: %s", err) } if err := t.setInfo(&info); err != nil { return err } t.metadataBytes = b t.metadataCompletedChunks = nil t.onSetInfo() return nil }
go
func (t *Torrent) setInfoBytes(b []byte) error { if metainfo.HashBytes(b) != t.infoHash { return errors.New("info bytes have wrong hash") } var info metainfo.Info if err := bencode.Unmarshal(b, &info); err != nil { return fmt.Errorf("error unmarshalling info bytes: %s", err) } if err := t.setInfo(&info); err != nil { return err } t.metadataBytes = b t.metadataCompletedChunks = nil t.onSetInfo() return nil }
[ "func", "(", "t", "*", "Torrent", ")", "setInfoBytes", "(", "b", "[", "]", "byte", ")", "error", "{", "if", "metainfo", ".", "HashBytes", "(", "b", ")", "!=", "t", ".", "infoHash", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "info", "metainfo", ".", "Info", "\n", "if", "err", ":=", "bencode", ".", "Unmarshal", "(", "b", ",", "&", "info", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "t", ".", "setInfo", "(", "&", "info", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "metadataBytes", "=", "b", "\n", "t", ".", "metadataCompletedChunks", "=", "nil", "\n", "t", ".", "onSetInfo", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Called when metadata for a torrent becomes available.
[ "Called", "when", "metadata", "for", "a", "torrent", "becomes", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L387-L402
train
anacrolix/torrent
torrent.go
name
func (t *Torrent) name() string { t.nameMu.RLock() defer t.nameMu.RUnlock() if t.haveInfo() { return t.info.Name } return t.displayName }
go
func (t *Torrent) name() string { t.nameMu.RLock() defer t.nameMu.RUnlock() if t.haveInfo() { return t.info.Name } return t.displayName }
[ "func", "(", "t", "*", "Torrent", ")", "name", "(", ")", "string", "{", "t", ".", "nameMu", ".", "RLock", "(", ")", "\n", "defer", "t", ".", "nameMu", ".", "RUnlock", "(", ")", "\n", "if", "t", ".", "haveInfo", "(", ")", "{", "return", "t", ".", "info", ".", "Name", "\n", "}", "\n", "return", "t", ".", "displayName", "\n", "}" ]
// The current working name for the torrent. Either the name in the info dict, // or a display name given such as by the dn value in a magnet link, or "".
[ "The", "current", "working", "name", "for", "the", "torrent", ".", "Either", "the", "name", "in", "the", "info", "dict", "or", "a", "display", "name", "given", "such", "as", "by", "the", "dn", "value", "in", "a", "magnet", "link", "or", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L442-L449
train
anacrolix/torrent
torrent.go
pieceStateRunStatusChars
func pieceStateRunStatusChars(psr PieceStateRun) (ret string) { ret = fmt.Sprintf("%d", psr.Length) ret += func() string { switch psr.Priority { case PiecePriorityNext: return "N" case PiecePriorityNormal: return "." case PiecePriorityReadahead: return "R" case PiecePriorityNow: return "!" case PiecePriorityHigh: return "H" default: return "" } }() if psr.Checking { ret += "H" } if psr.Partial { ret += "P" } if psr.Complete { ret += "C" } if !psr.Ok { ret += "?" } return }
go
func pieceStateRunStatusChars(psr PieceStateRun) (ret string) { ret = fmt.Sprintf("%d", psr.Length) ret += func() string { switch psr.Priority { case PiecePriorityNext: return "N" case PiecePriorityNormal: return "." case PiecePriorityReadahead: return "R" case PiecePriorityNow: return "!" case PiecePriorityHigh: return "H" default: return "" } }() if psr.Checking { ret += "H" } if psr.Partial { ret += "P" } if psr.Complete { ret += "C" } if !psr.Ok { ret += "?" } return }
[ "func", "pieceStateRunStatusChars", "(", "psr", "PieceStateRun", ")", "(", "ret", "string", ")", "{", "ret", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "psr", ".", "Length", ")", "\n", "ret", "+=", "func", "(", ")", "string", "{", "switch", "psr", ".", "Priority", "{", "case", "PiecePriorityNext", ":", "return", "\"", "\"", "\n", "case", "PiecePriorityNormal", ":", "return", "\"", "\"", "\n", "case", "PiecePriorityReadahead", ":", "return", "\"", "\"", "\n", "case", "PiecePriorityNow", ":", "return", "\"", "\"", "\n", "case", "PiecePriorityHigh", ":", "return", "\"", "\"", "\n", "default", ":", "return", "\"", "\"", "\n", "}", "\n", "}", "(", ")", "\n", "if", "psr", ".", "Checking", "{", "ret", "+=", "\"", "\"", "\n", "}", "\n", "if", "psr", ".", "Partial", "{", "ret", "+=", "\"", "\"", "\n", "}", "\n", "if", "psr", ".", "Complete", "{", "ret", "+=", "\"", "\"", "\n", "}", "\n", "if", "!", "psr", ".", "Ok", "{", "ret", "+=", "\"", "\"", "\n", "}", "\n", "return", "\n", "}" ]
// Produces a small string representing a PieceStateRun.
[ "Produces", "a", "small", "string", "representing", "a", "PieceStateRun", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L499-L530
train
anacrolix/torrent
torrent.go
newMetaInfo
func (t *Torrent) newMetaInfo() metainfo.MetaInfo { return metainfo.MetaInfo{ CreationDate: time.Now().Unix(), Comment: "dynamic metainfo from client", CreatedBy: "go.torrent", AnnounceList: t.metainfo.UpvertedAnnounceList(), InfoBytes: func() []byte { if t.haveInfo() { return t.metadataBytes } else { return nil } }(), } }
go
func (t *Torrent) newMetaInfo() metainfo.MetaInfo { return metainfo.MetaInfo{ CreationDate: time.Now().Unix(), Comment: "dynamic metainfo from client", CreatedBy: "go.torrent", AnnounceList: t.metainfo.UpvertedAnnounceList(), InfoBytes: func() []byte { if t.haveInfo() { return t.metadataBytes } else { return nil } }(), } }
[ "func", "(", "t", "*", "Torrent", ")", "newMetaInfo", "(", ")", "metainfo", ".", "MetaInfo", "{", "return", "metainfo", ".", "MetaInfo", "{", "CreationDate", ":", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", ",", "Comment", ":", "\"", "\"", ",", "CreatedBy", ":", "\"", "\"", ",", "AnnounceList", ":", "t", ".", "metainfo", ".", "UpvertedAnnounceList", "(", ")", ",", "InfoBytes", ":", "func", "(", ")", "[", "]", "byte", "{", "if", "t", ".", "haveInfo", "(", ")", "{", "return", "t", ".", "metadataBytes", "\n", "}", "else", "{", "return", "nil", "\n", "}", "\n", "}", "(", ")", ",", "}", "\n", "}" ]
// Returns a run-time generated MetaInfo that includes the info bytes and // announce-list as currently known to the client.
[ "Returns", "a", "run", "-", "time", "generated", "MetaInfo", "that", "includes", "the", "info", "bytes", "and", "announce", "-", "list", "as", "currently", "known", "to", "the", "client", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L602-L616
train
anacrolix/torrent
torrent.go
bytesLeftAnnounce
func (t *Torrent) bytesLeftAnnounce() uint64 { if t.haveInfo() { return uint64(t.bytesLeft()) } else { return math.MaxUint64 } }
go
func (t *Torrent) bytesLeftAnnounce() uint64 { if t.haveInfo() { return uint64(t.bytesLeft()) } else { return math.MaxUint64 } }
[ "func", "(", "t", "*", "Torrent", ")", "bytesLeftAnnounce", "(", ")", "uint64", "{", "if", "t", ".", "haveInfo", "(", ")", "{", "return", "uint64", "(", "t", ".", "bytesLeft", "(", ")", ")", "\n", "}", "else", "{", "return", "math", ".", "MaxUint64", "\n", "}", "\n", "}" ]
// Bytes left to give in tracker announces.
[ "Bytes", "left", "to", "give", "in", "tracker", "announces", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L638-L644
train
anacrolix/torrent
torrent.go
offsetRequest
func (t *Torrent) offsetRequest(off int64) (req request, ok bool) { return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off) }
go
func (t *Torrent) offsetRequest(off int64) (req request, ok bool) { return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off) }
[ "func", "(", "t", "*", "Torrent", ")", "offsetRequest", "(", "off", "int64", ")", "(", "req", "request", ",", "ok", "bool", ")", "{", "return", "torrentOffsetRequest", "(", "*", "t", ".", "length", ",", "t", ".", "info", ".", "PieceLength", ",", "int64", "(", "t", ".", "chunkSize", ")", ",", "off", ")", "\n", "}" ]
// Return the request that would include the given offset into the torrent // data. Returns !ok if there is no such request.
[ "Return", "the", "request", "that", "would", "include", "the", "given", "offset", "into", "the", "torrent", "data", ".", "Returns", "!ok", "if", "there", "is", "no", "such", "request", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L691-L693
train
anacrolix/torrent
torrent.go
worstBadConn
func (t *Torrent) worstBadConn() *connection { wcs := worseConnSlice{t.unclosedConnsAsSlice()} heap.Init(&wcs) for wcs.Len() != 0 { c := heap.Pop(&wcs).(*connection) if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() { return c } // If the connection is in the worst half of the established // connection quota and is older than a minute. if wcs.Len() >= (t.maxEstablishedConns+1)/2 { // Give connections 1 minute to prove themselves. if time.Since(c.completedHandshake) > time.Minute { return c } } } return nil }
go
func (t *Torrent) worstBadConn() *connection { wcs := worseConnSlice{t.unclosedConnsAsSlice()} heap.Init(&wcs) for wcs.Len() != 0 { c := heap.Pop(&wcs).(*connection) if c.stats.ChunksReadWasted.Int64() >= 6 && c.stats.ChunksReadWasted.Int64() > c.stats.ChunksReadUseful.Int64() { return c } // If the connection is in the worst half of the established // connection quota and is older than a minute. if wcs.Len() >= (t.maxEstablishedConns+1)/2 { // Give connections 1 minute to prove themselves. if time.Since(c.completedHandshake) > time.Minute { return c } } } return nil }
[ "func", "(", "t", "*", "Torrent", ")", "worstBadConn", "(", ")", "*", "connection", "{", "wcs", ":=", "worseConnSlice", "{", "t", ".", "unclosedConnsAsSlice", "(", ")", "}", "\n", "heap", ".", "Init", "(", "&", "wcs", ")", "\n", "for", "wcs", ".", "Len", "(", ")", "!=", "0", "{", "c", ":=", "heap", ".", "Pop", "(", "&", "wcs", ")", ".", "(", "*", "connection", ")", "\n", "if", "c", ".", "stats", ".", "ChunksReadWasted", ".", "Int64", "(", ")", ">=", "6", "&&", "c", ".", "stats", ".", "ChunksReadWasted", ".", "Int64", "(", ")", ">", "c", ".", "stats", ".", "ChunksReadUseful", ".", "Int64", "(", ")", "{", "return", "c", "\n", "}", "\n", "// If the connection is in the worst half of the established", "// connection quota and is older than a minute.", "if", "wcs", ".", "Len", "(", ")", ">=", "(", "t", ".", "maxEstablishedConns", "+", "1", ")", "/", "2", "{", "// Give connections 1 minute to prove themselves.", "if", "time", ".", "Since", "(", "c", ".", "completedHandshake", ")", ">", "time", ".", "Minute", "{", "return", "c", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// The worst connection is one that hasn't been sent, or sent anything useful // for the longest. A bad connection is one that usually sends us unwanted // pieces, or has been in worser half of the established connections for more // than a minute.
[ "The", "worst", "connection", "is", "one", "that", "hasn", "t", "been", "sent", "or", "sent", "anything", "useful", "for", "the", "longest", ".", "A", "bad", "connection", "is", "one", "that", "usually", "sends", "us", "unwanted", "pieces", "or", "has", "been", "in", "worser", "half", "of", "the", "established", "connections", "for", "more", "than", "a", "minute", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L815-L833
train
anacrolix/torrent
torrent.go
updatePiecePriorities
func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) { for i := begin; i < end; i++ { t.updatePiecePriority(i) } }
go
func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) { for i := begin; i < end; i++ { t.updatePiecePriority(i) } }
[ "func", "(", "t", "*", "Torrent", ")", "updatePiecePriorities", "(", "begin", ",", "end", "pieceIndex", ")", "{", "for", "i", ":=", "begin", ";", "i", "<", "end", ";", "i", "++", "{", "t", ".", "updatePiecePriority", "(", "i", ")", "\n", "}", "\n", "}" ]
// Update all piece priorities in one hit. This function should have the same // output as updatePiecePriority, but across all pieces.
[ "Update", "all", "piece", "priorities", "in", "one", "hit", ".", "This", "function", "should", "have", "the", "same", "output", "as", "updatePiecePriority", "but", "across", "all", "pieces", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L936-L940
train
anacrolix/torrent
torrent.go
byteRegionPieces
func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) { if off >= *t.length { return } if off < 0 { size += off off = 0 } if size <= 0 { return } begin = pieceIndex(off / t.info.PieceLength) end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength) if end > pieceIndex(t.info.NumPieces()) { end = pieceIndex(t.info.NumPieces()) } return }
go
func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) { if off >= *t.length { return } if off < 0 { size += off off = 0 } if size <= 0 { return } begin = pieceIndex(off / t.info.PieceLength) end = pieceIndex((off + size + t.info.PieceLength - 1) / t.info.PieceLength) if end > pieceIndex(t.info.NumPieces()) { end = pieceIndex(t.info.NumPieces()) } return }
[ "func", "(", "t", "*", "Torrent", ")", "byteRegionPieces", "(", "off", ",", "size", "int64", ")", "(", "begin", ",", "end", "pieceIndex", ")", "{", "if", "off", ">=", "*", "t", ".", "length", "{", "return", "\n", "}", "\n", "if", "off", "<", "0", "{", "size", "+=", "off", "\n", "off", "=", "0", "\n", "}", "\n", "if", "size", "<=", "0", "{", "return", "\n", "}", "\n", "begin", "=", "pieceIndex", "(", "off", "/", "t", ".", "info", ".", "PieceLength", ")", "\n", "end", "=", "pieceIndex", "(", "(", "off", "+", "size", "+", "t", ".", "info", ".", "PieceLength", "-", "1", ")", "/", "t", ".", "info", ".", "PieceLength", ")", "\n", "if", "end", ">", "pieceIndex", "(", "t", ".", "info", ".", "NumPieces", "(", ")", ")", "{", "end", "=", "pieceIndex", "(", "t", ".", "info", ".", "NumPieces", "(", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Returns the range of pieces [begin, end) that contains the extent of bytes.
[ "Returns", "the", "range", "of", "pieces", "[", "begin", "end", ")", "that", "contains", "the", "extent", "of", "bytes", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L943-L960
train
anacrolix/torrent
torrent.go
forReaderOffsetPieces
func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) { for r := range t.readers { p := r.pieces if p.begin >= p.end { continue } if !f(p.begin, p.end) { return false } } return true }
go
func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) { for r := range t.readers { p := r.pieces if p.begin >= p.end { continue } if !f(p.begin, p.end) { return false } } return true }
[ "func", "(", "t", "*", "Torrent", ")", "forReaderOffsetPieces", "(", "f", "func", "(", "begin", ",", "end", "pieceIndex", ")", "(", "more", "bool", ")", ")", "(", "all", "bool", ")", "{", "for", "r", ":=", "range", "t", ".", "readers", "{", "p", ":=", "r", ".", "pieces", "\n", "if", "p", ".", "begin", ">=", "p", ".", "end", "{", "continue", "\n", "}", "\n", "if", "!", "f", "(", "p", ".", "begin", ",", "p", ".", "end", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Returns true if all iterations complete without breaking. Returns the read // regions for all readers. The reader regions should not be merged as some // callers depend on this method to enumerate readers.
[ "Returns", "true", "if", "all", "iterations", "complete", "without", "breaking", ".", "Returns", "the", "read", "regions", "for", "all", "readers", ".", "The", "reader", "regions", "should", "not", "be", "merged", "as", "some", "callers", "depend", "on", "this", "method", "to", "enumerate", "readers", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L965-L976
train
anacrolix/torrent
torrent.go
readAt
func (t *Torrent) readAt(b []byte, off int64) (n int, err error) { p := &t.pieces[off/t.info.PieceLength] p.waitNoPendingWrites() return p.Storage().ReadAt(b, off-p.Info().Offset()) }
go
func (t *Torrent) readAt(b []byte, off int64) (n int, err error) { p := &t.pieces[off/t.info.PieceLength] p.waitNoPendingWrites() return p.Storage().ReadAt(b, off-p.Info().Offset()) }
[ "func", "(", "t", "*", "Torrent", ")", "readAt", "(", "b", "[", "]", "byte", ",", "off", "int64", ")", "(", "n", "int", ",", "err", "error", ")", "{", "p", ":=", "&", "t", ".", "pieces", "[", "off", "/", "t", ".", "info", ".", "PieceLength", "]", "\n", "p", ".", "waitNoPendingWrites", "(", ")", "\n", "return", "p", ".", "Storage", "(", ")", ".", "ReadAt", "(", "b", ",", "off", "-", "p", ".", "Info", "(", ")", ".", "Offset", "(", ")", ")", "\n", "}" ]
// Non-blocking read. Client lock is not required.
[ "Non", "-", "blocking", "read", ".", "Client", "lock", "is", "not", "required", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1074-L1078
train
anacrolix/torrent
torrent.go
maybeCompleteMetadata
func (t *Torrent) maybeCompleteMetadata() error { if t.haveInfo() { // Nothing to do. return nil } if !t.haveAllMetadataPieces() { // Don't have enough metadata pieces. return nil } err := t.setInfoBytes(t.metadataBytes) if err != nil { t.invalidateMetadata() return fmt.Errorf("error setting info bytes: %s", err) } if t.cl.config.Debug { t.logger.Printf("%s: got metadata from peers", t) } return nil }
go
func (t *Torrent) maybeCompleteMetadata() error { if t.haveInfo() { // Nothing to do. return nil } if !t.haveAllMetadataPieces() { // Don't have enough metadata pieces. return nil } err := t.setInfoBytes(t.metadataBytes) if err != nil { t.invalidateMetadata() return fmt.Errorf("error setting info bytes: %s", err) } if t.cl.config.Debug { t.logger.Printf("%s: got metadata from peers", t) } return nil }
[ "func", "(", "t", "*", "Torrent", ")", "maybeCompleteMetadata", "(", ")", "error", "{", "if", "t", ".", "haveInfo", "(", ")", "{", "// Nothing to do.", "return", "nil", "\n", "}", "\n", "if", "!", "t", ".", "haveAllMetadataPieces", "(", ")", "{", "// Don't have enough metadata pieces.", "return", "nil", "\n", "}", "\n", "err", ":=", "t", ".", "setInfoBytes", "(", "t", ".", "metadataBytes", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "invalidateMetadata", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "t", ".", "cl", ".", "config", ".", "Debug", "{", "t", ".", "logger", ".", "Printf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Returns an error if the metadata was completed, but couldn't be set for // some reason. Blame it on the last peer to contribute.
[ "Returns", "an", "error", "if", "the", "metadata", "was", "completed", "but", "couldn", "t", "be", "set", "for", "some", "reason", ".", "Blame", "it", "on", "the", "last", "peer", "to", "contribute", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1088-L1106
train