id
int32
0
167k
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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
22,000
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
22,001
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
22,002
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
22,003
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
22,004
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
22,005
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
22,006
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
22,007
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
22,008
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
22,009
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
22,010
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
22,011
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
22,012
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
22,013
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
22,014
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
22,015
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
22,016
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
22,017
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
22,018
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
22,019
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
22,020
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
22,021
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
22,022
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
22,023
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
22,024
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
22,025
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
22,026
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
22,027
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
22,028
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
22,029
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
22,030
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
22,031
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
22,032
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
22,033
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
22,034
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
22,035
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
22,036
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
22,037
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
22,038
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
22,039
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
22,040
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
22,041
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
22,042
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
22,043
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
22,044
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
22,045
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
22,046
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
22,047
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
22,048
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
22,049
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
22,050
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
22,051
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
22,052
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
22,053
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
22,054
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
22,055
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
22,056
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
22,057
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
22,058
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
22,059
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
22,060
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
22,061
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
22,062
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
22,063
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
22,064
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
22,065
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
22,066
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
22,067
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
22,068
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
22,069
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
22,070
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
22,071
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
22,072
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
22,073
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
22,074
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
22,075
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
22,076
anacrolix/torrent
torrent.go
bytesCompleted
func (t *Torrent) bytesCompleted() int64 { if !t.haveInfo() { return 0 } return t.info.TotalLength() - t.bytesLeft() }
go
func (t *Torrent) bytesCompleted() int64 { if !t.haveInfo() { return 0 } return t.info.TotalLength() - t.bytesLeft() }
[ "func", "(", "t", "*", "Torrent", ")", "bytesCompleted", "(", ")", "int64", "{", "if", "!", "t", ".", "haveInfo", "(", ")", "{", "return", "0", "\n", "}", "\n", "return", "t", ".", "info", ".", "TotalLength", "(", ")", "-", "t", ".", "bytesLeft", "(", ")", "\n", "}" ]
// Don't call this before the info is available.
[ "Don", "t", "call", "this", "before", "the", "info", "is", "available", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1162-L1167
22,077
anacrolix/torrent
torrent.go
deleteConnection
func (t *Torrent) deleteConnection(c *connection) (ret bool) { if !c.closed.IsSet() { panic("connection is not closed") // There are behaviours prevented by the closed state that will fail // if the connection has been deleted. } _, ret = t.conns[c] delete(t.conns, c) torrent.Add("deleted connections", 1) c.deleteAllRequests() if len(t.conns) == 0 { t.assertNoPendingRequests() } return }
go
func (t *Torrent) deleteConnection(c *connection) (ret bool) { if !c.closed.IsSet() { panic("connection is not closed") // There are behaviours prevented by the closed state that will fail // if the connection has been deleted. } _, ret = t.conns[c] delete(t.conns, c) torrent.Add("deleted connections", 1) c.deleteAllRequests() if len(t.conns) == 0 { t.assertNoPendingRequests() } return }
[ "func", "(", "t", "*", "Torrent", ")", "deleteConnection", "(", "c", "*", "connection", ")", "(", "ret", "bool", ")", "{", "if", "!", "c", ".", "closed", ".", "IsSet", "(", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "// There are behaviours prevented by the closed state that will fail", "// if the connection has been deleted.", "}", "\n", "_", ",", "ret", "=", "t", ".", "conns", "[", "c", "]", "\n", "delete", "(", "t", ".", "conns", ",", "c", ")", "\n", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "c", ".", "deleteAllRequests", "(", ")", "\n", "if", "len", "(", "t", ".", "conns", ")", "==", "0", "{", "t", ".", "assertNoPendingRequests", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Returns true if connection is removed from torrent.Conns.
[ "Returns", "true", "if", "connection", "is", "removed", "from", "torrent", ".", "Conns", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1176-L1190
22,078
anacrolix/torrent
torrent.go
seeding
func (t *Torrent) seeding() bool { cl := t.cl if t.closed.IsSet() { return false } if cl.config.NoUpload { return false } if !cl.config.Seed { return false } if cl.config.DisableAggressiveUpload && t.needData() { return false } return true }
go
func (t *Torrent) seeding() bool { cl := t.cl if t.closed.IsSet() { return false } if cl.config.NoUpload { return false } if !cl.config.Seed { return false } if cl.config.DisableAggressiveUpload && t.needData() { return false } return true }
[ "func", "(", "t", "*", "Torrent", ")", "seeding", "(", ")", "bool", "{", "cl", ":=", "t", ".", "cl", "\n", "if", "t", ".", "closed", ".", "IsSet", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "cl", ".", "config", ".", "NoUpload", "{", "return", "false", "\n", "}", "\n", "if", "!", "cl", ".", "config", ".", "Seed", "{", "return", "false", "\n", "}", "\n", "if", "cl", ".", "config", ".", "DisableAggressiveUpload", "&&", "t", ".", "needData", "(", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Returns whether the client should make effort to seed the torrent.
[ "Returns", "whether", "the", "client", "should", "make", "effort", "to", "seed", "the", "torrent", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1228-L1243
22,079
anacrolix/torrent
torrent.go
startMissingTrackerScrapers
func (t *Torrent) startMissingTrackerScrapers() { if t.cl.config.DisableTrackers { return } t.startScrapingTracker(t.metainfo.Announce) for _, tier := range t.metainfo.AnnounceList { for _, url := range tier { t.startScrapingTracker(url) } } }
go
func (t *Torrent) startMissingTrackerScrapers() { if t.cl.config.DisableTrackers { return } t.startScrapingTracker(t.metainfo.Announce) for _, tier := range t.metainfo.AnnounceList { for _, url := range tier { t.startScrapingTracker(url) } } }
[ "func", "(", "t", "*", "Torrent", ")", "startMissingTrackerScrapers", "(", ")", "{", "if", "t", ".", "cl", ".", "config", ".", "DisableTrackers", "{", "return", "\n", "}", "\n", "t", ".", "startScrapingTracker", "(", "t", ".", "metainfo", ".", "Announce", ")", "\n", "for", "_", ",", "tier", ":=", "range", "t", ".", "metainfo", ".", "AnnounceList", "{", "for", "_", ",", "url", ":=", "range", "tier", "{", "t", ".", "startScrapingTracker", "(", "url", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Adds and starts tracker scrapers for tracker URLs that aren't already // running.
[ "Adds", "and", "starts", "tracker", "scrapers", "for", "tracker", "URLs", "that", "aren", "t", "already", "running", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1287-L1297
22,080
anacrolix/torrent
torrent.go
announceRequest
func (t *Torrent) announceRequest() tracker.AnnounceRequest { // Note that IPAddress is not set. It's set for UDP inside the tracker // code, since it's dependent on the network in use. return tracker.AnnounceRequest{ Event: tracker.None, NumWant: -1, Port: uint16(t.cl.incomingPeerPort()), PeerId: t.cl.peerID, InfoHash: t.infoHash, Key: t.cl.announceKey(), // The following are vaguely described in BEP 3. Left: t.bytesLeftAnnounce(), Uploaded: t.stats.BytesWrittenData.Int64(), // There's no mention of wasted or unwanted download in the BEP. Downloaded: t.stats.BytesReadUsefulData.Int64(), } }
go
func (t *Torrent) announceRequest() tracker.AnnounceRequest { // Note that IPAddress is not set. It's set for UDP inside the tracker // code, since it's dependent on the network in use. return tracker.AnnounceRequest{ Event: tracker.None, NumWant: -1, Port: uint16(t.cl.incomingPeerPort()), PeerId: t.cl.peerID, InfoHash: t.infoHash, Key: t.cl.announceKey(), // The following are vaguely described in BEP 3. Left: t.bytesLeftAnnounce(), Uploaded: t.stats.BytesWrittenData.Int64(), // There's no mention of wasted or unwanted download in the BEP. Downloaded: t.stats.BytesReadUsefulData.Int64(), } }
[ "func", "(", "t", "*", "Torrent", ")", "announceRequest", "(", ")", "tracker", ".", "AnnounceRequest", "{", "// Note that IPAddress is not set. It's set for UDP inside the tracker", "// code, since it's dependent on the network in use.", "return", "tracker", ".", "AnnounceRequest", "{", "Event", ":", "tracker", ".", "None", ",", "NumWant", ":", "-", "1", ",", "Port", ":", "uint16", "(", "t", ".", "cl", ".", "incomingPeerPort", "(", ")", ")", ",", "PeerId", ":", "t", ".", "cl", ".", "peerID", ",", "InfoHash", ":", "t", ".", "infoHash", ",", "Key", ":", "t", ".", "cl", ".", "announceKey", "(", ")", ",", "// The following are vaguely described in BEP 3.", "Left", ":", "t", ".", "bytesLeftAnnounce", "(", ")", ",", "Uploaded", ":", "t", ".", "stats", ".", "BytesWrittenData", ".", "Int64", "(", ")", ",", "// There's no mention of wasted or unwanted download in the BEP.", "Downloaded", ":", "t", ".", "stats", ".", "BytesReadUsefulData", ".", "Int64", "(", ")", ",", "}", "\n", "}" ]
// Returns an AnnounceRequest with fields filled out to defaults and current // values.
[ "Returns", "an", "AnnounceRequest", "with", "fields", "filled", "out", "to", "defaults", "and", "current", "values", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1301-L1319
22,081
anacrolix/torrent
torrent.go
consumeDhtAnnouncePeers
func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) { cl := t.cl for v := range pvs { cl.lock() for _, cp := range v.Peers { if cp.Port == 0 { // Can't do anything with this. continue } t.addPeer(Peer{ IP: cp.IP[:], Port: cp.Port, Source: peerSourceDHTGetPeers, }) } cl.unlock() } }
go
func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) { cl := t.cl for v := range pvs { cl.lock() for _, cp := range v.Peers { if cp.Port == 0 { // Can't do anything with this. continue } t.addPeer(Peer{ IP: cp.IP[:], Port: cp.Port, Source: peerSourceDHTGetPeers, }) } cl.unlock() } }
[ "func", "(", "t", "*", "Torrent", ")", "consumeDhtAnnouncePeers", "(", "pvs", "<-", "chan", "dht", ".", "PeersValues", ")", "{", "cl", ":=", "t", ".", "cl", "\n", "for", "v", ":=", "range", "pvs", "{", "cl", ".", "lock", "(", ")", "\n", "for", "_", ",", "cp", ":=", "range", "v", ".", "Peers", "{", "if", "cp", ".", "Port", "==", "0", "{", "// Can't do anything with this.", "continue", "\n", "}", "\n", "t", ".", "addPeer", "(", "Peer", "{", "IP", ":", "cp", ".", "IP", "[", ":", "]", ",", "Port", ":", "cp", ".", "Port", ",", "Source", ":", "peerSourceDHTGetPeers", ",", "}", ")", "\n", "}", "\n", "cl", ".", "unlock", "(", ")", "\n", "}", "\n", "}" ]
// Adds peers revealed in an announce until the announce ends, or we have // enough peers.
[ "Adds", "peers", "revealed", "in", "an", "announce", "until", "the", "announce", "ends", "or", "we", "have", "enough", "peers", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1323-L1340
22,082
anacrolix/torrent
torrent.go
numTotalPeers
func (t *Torrent) numTotalPeers() int { peers := make(map[string]struct{}) for conn := range t.conns { ra := conn.conn.RemoteAddr() if ra == nil { // It's been closed and doesn't support RemoteAddr. continue } peers[ra.String()] = struct{}{} } for addr := range t.halfOpen { peers[addr] = struct{}{} } t.peers.Each(func(peer Peer) { peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{} }) return len(peers) }
go
func (t *Torrent) numTotalPeers() int { peers := make(map[string]struct{}) for conn := range t.conns { ra := conn.conn.RemoteAddr() if ra == nil { // It's been closed and doesn't support RemoteAddr. continue } peers[ra.String()] = struct{}{} } for addr := range t.halfOpen { peers[addr] = struct{}{} } t.peers.Each(func(peer Peer) { peers[fmt.Sprintf("%s:%d", peer.IP, peer.Port)] = struct{}{} }) return len(peers) }
[ "func", "(", "t", "*", "Torrent", ")", "numTotalPeers", "(", ")", "int", "{", "peers", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "conn", ":=", "range", "t", ".", "conns", "{", "ra", ":=", "conn", ".", "conn", ".", "RemoteAddr", "(", ")", "\n", "if", "ra", "==", "nil", "{", "// It's been closed and doesn't support RemoteAddr.", "continue", "\n", "}", "\n", "peers", "[", "ra", ".", "String", "(", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "for", "addr", ":=", "range", "t", ".", "halfOpen", "{", "peers", "[", "addr", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "t", ".", "peers", ".", "Each", "(", "func", "(", "peer", "Peer", ")", "{", "peers", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "peer", ".", "IP", ",", "peer", ".", "Port", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", ")", "\n", "return", "len", "(", "peers", ")", "\n", "}" ]
// The total number of peers in the torrent.
[ "The", "total", "number", "of", "peers", "in", "the", "torrent", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1402-L1419
22,083
anacrolix/torrent
torrent.go
reconcileHandshakeStats
func (t *Torrent) reconcileHandshakeStats(c *connection) { if c.stats != (ConnStats{ // Handshakes should only increment these fields: BytesWritten: c.stats.BytesWritten, BytesRead: c.stats.BytesRead, }) { panic("bad stats") } c.postHandshakeStats(func(cs *ConnStats) { cs.BytesRead.Add(c.stats.BytesRead.Int64()) cs.BytesWritten.Add(c.stats.BytesWritten.Int64()) }) c.reconciledHandshakeStats = true }
go
func (t *Torrent) reconcileHandshakeStats(c *connection) { if c.stats != (ConnStats{ // Handshakes should only increment these fields: BytesWritten: c.stats.BytesWritten, BytesRead: c.stats.BytesRead, }) { panic("bad stats") } c.postHandshakeStats(func(cs *ConnStats) { cs.BytesRead.Add(c.stats.BytesRead.Int64()) cs.BytesWritten.Add(c.stats.BytesWritten.Int64()) }) c.reconciledHandshakeStats = true }
[ "func", "(", "t", "*", "Torrent", ")", "reconcileHandshakeStats", "(", "c", "*", "connection", ")", "{", "if", "c", ".", "stats", "!=", "(", "ConnStats", "{", "// Handshakes should only increment these fields:", "BytesWritten", ":", "c", ".", "stats", ".", "BytesWritten", ",", "BytesRead", ":", "c", ".", "stats", ".", "BytesRead", ",", "}", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "postHandshakeStats", "(", "func", "(", "cs", "*", "ConnStats", ")", "{", "cs", ".", "BytesRead", ".", "Add", "(", "c", ".", "stats", ".", "BytesRead", ".", "Int64", "(", ")", ")", "\n", "cs", ".", "BytesWritten", ".", "Add", "(", "c", ".", "stats", ".", "BytesWritten", ".", "Int64", "(", ")", ")", "\n", "}", ")", "\n", "c", ".", "reconciledHandshakeStats", "=", "true", "\n", "}" ]
// Reconcile bytes transferred before connection was associated with a // torrent.
[ "Reconcile", "bytes", "transferred", "before", "connection", "was", "associated", "with", "a", "torrent", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1423-L1436
22,084
anacrolix/torrent
torrent.go
addConnection
func (t *Torrent) addConnection(c *connection) (err error) { defer func() { if err == nil { torrent.Add("added connections", 1) } }() if t.closed.IsSet() { return errors.New("torrent closed") } for c0 := range t.conns { if c.PeerID != c0.PeerID { continue } if !t.cl.config.dropDuplicatePeerIds { continue } if left, ok := c.hasPreferredNetworkOver(c0); ok && left { c0.Close() t.deleteConnection(c0) } else { return errors.New("existing connection preferred") } } if len(t.conns) >= t.maxEstablishedConns { c := t.worstBadConn() if c == nil { return errors.New("don't want conns") } c.Close() t.deleteConnection(c) } if len(t.conns) >= t.maxEstablishedConns { panic(len(t.conns)) } t.conns[c] = struct{}{} return nil }
go
func (t *Torrent) addConnection(c *connection) (err error) { defer func() { if err == nil { torrent.Add("added connections", 1) } }() if t.closed.IsSet() { return errors.New("torrent closed") } for c0 := range t.conns { if c.PeerID != c0.PeerID { continue } if !t.cl.config.dropDuplicatePeerIds { continue } if left, ok := c.hasPreferredNetworkOver(c0); ok && left { c0.Close() t.deleteConnection(c0) } else { return errors.New("existing connection preferred") } } if len(t.conns) >= t.maxEstablishedConns { c := t.worstBadConn() if c == nil { return errors.New("don't want conns") } c.Close() t.deleteConnection(c) } if len(t.conns) >= t.maxEstablishedConns { panic(len(t.conns)) } t.conns[c] = struct{}{} return nil }
[ "func", "(", "t", "*", "Torrent", ")", "addConnection", "(", "c", "*", "connection", ")", "(", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "torrent", ".", "Add", "(", "\"", "\"", ",", "1", ")", "\n", "}", "\n", "}", "(", ")", "\n", "if", "t", ".", "closed", ".", "IsSet", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "c0", ":=", "range", "t", ".", "conns", "{", "if", "c", ".", "PeerID", "!=", "c0", ".", "PeerID", "{", "continue", "\n", "}", "\n", "if", "!", "t", ".", "cl", ".", "config", ".", "dropDuplicatePeerIds", "{", "continue", "\n", "}", "\n", "if", "left", ",", "ok", ":=", "c", ".", "hasPreferredNetworkOver", "(", "c0", ")", ";", "ok", "&&", "left", "{", "c0", ".", "Close", "(", ")", "\n", "t", ".", "deleteConnection", "(", "c0", ")", "\n", "}", "else", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "t", ".", "conns", ")", ">=", "t", ".", "maxEstablishedConns", "{", "c", ":=", "t", ".", "worstBadConn", "(", ")", "\n", "if", "c", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Close", "(", ")", "\n", "t", ".", "deleteConnection", "(", "c", ")", "\n", "}", "\n", "if", "len", "(", "t", ".", "conns", ")", ">=", "t", ".", "maxEstablishedConns", "{", "panic", "(", "len", "(", "t", ".", "conns", ")", ")", "\n", "}", "\n", "t", ".", "conns", "[", "c", "]", "=", "struct", "{", "}", "{", "}", "\n", "return", "nil", "\n", "}" ]
// Returns true if the connection is added.
[ "Returns", "true", "if", "the", "connection", "is", "added", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1439-L1475
22,085
anacrolix/torrent
torrent.go
onIncompletePiece
func (t *Torrent) onIncompletePiece(piece pieceIndex) { if t.pieceAllDirty(piece) { t.pendAllChunkSpecs(piece) } if !t.wantPieceIndex(piece) { // t.logger.Printf("piece %d incomplete and unwanted", piece) return } // We could drop any connections that we told we have a piece that we // don't here. But there's a test failure, and it seems clients don't care // if you request pieces that you already claim to have. Pruning bad // connections might just remove any connections that aren't treating us // favourably anyway. // for c := range t.conns { // if c.sentHave(piece) { // c.Drop() // } // } for conn := range t.conns { if conn.PeerHasPiece(piece) { conn.updateRequests() } } }
go
func (t *Torrent) onIncompletePiece(piece pieceIndex) { if t.pieceAllDirty(piece) { t.pendAllChunkSpecs(piece) } if !t.wantPieceIndex(piece) { // t.logger.Printf("piece %d incomplete and unwanted", piece) return } // We could drop any connections that we told we have a piece that we // don't here. But there's a test failure, and it seems clients don't care // if you request pieces that you already claim to have. Pruning bad // connections might just remove any connections that aren't treating us // favourably anyway. // for c := range t.conns { // if c.sentHave(piece) { // c.Drop() // } // } for conn := range t.conns { if conn.PeerHasPiece(piece) { conn.updateRequests() } } }
[ "func", "(", "t", "*", "Torrent", ")", "onIncompletePiece", "(", "piece", "pieceIndex", ")", "{", "if", "t", ".", "pieceAllDirty", "(", "piece", ")", "{", "t", ".", "pendAllChunkSpecs", "(", "piece", ")", "\n", "}", "\n", "if", "!", "t", ".", "wantPieceIndex", "(", "piece", ")", "{", "// t.logger.Printf(\"piece %d incomplete and unwanted\", piece)", "return", "\n", "}", "\n", "// We could drop any connections that we told we have a piece that we", "// don't here. But there's a test failure, and it seems clients don't care", "// if you request pieces that you already claim to have. Pruning bad", "// connections might just remove any connections that aren't treating us", "// favourably anyway.", "// for c := range t.conns {", "// \tif c.sentHave(piece) {", "// \t\tc.Drop()", "// \t}", "// }", "for", "conn", ":=", "range", "t", ".", "conns", "{", "if", "conn", ".", "PeerHasPiece", "(", "piece", ")", "{", "conn", ".", "updateRequests", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Called when a piece is found to be not complete.
[ "Called", "when", "a", "piece", "is", "found", "to", "be", "not", "complete", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1580-L1604
22,086
anacrolix/torrent
torrent.go
reapPieceTouchers
func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) { for c := range t.pieces[piece].dirtiers { delete(c.peerTouchedPieces, piece) ret = append(ret, c) } t.pieces[piece].dirtiers = nil return }
go
func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) { for c := range t.pieces[piece].dirtiers { delete(c.peerTouchedPieces, piece) ret = append(ret, c) } t.pieces[piece].dirtiers = nil return }
[ "func", "(", "t", "*", "Torrent", ")", "reapPieceTouchers", "(", "piece", "pieceIndex", ")", "(", "ret", "[", "]", "*", "connection", ")", "{", "for", "c", ":=", "range", "t", ".", "pieces", "[", "piece", "]", ".", "dirtiers", "{", "delete", "(", "c", ".", "peerTouchedPieces", ",", "piece", ")", "\n", "ret", "=", "append", "(", "ret", ",", "c", ")", "\n", "}", "\n", "t", ".", "pieces", "[", "piece", "]", ".", "dirtiers", "=", "nil", "\n", "return", "\n", "}" ]
// Return the connections that touched a piece, and clear the entries while // doing it.
[ "Return", "the", "connections", "that", "touched", "a", "piece", "and", "clear", "the", "entries", "while", "doing", "it", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1641-L1648
22,087
anacrolix/torrent
torrent.go
queuePieceCheck
func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) { piece := &t.pieces[pieceIndex] if piece.queuedForHash() { return } t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex)) t.publishPieceChange(pieceIndex) t.updatePiecePriority(pieceIndex) go t.verifyPiece(pieceIndex) }
go
func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) { piece := &t.pieces[pieceIndex] if piece.queuedForHash() { return } t.piecesQueuedForHash.Add(bitmap.BitIndex(pieceIndex)) t.publishPieceChange(pieceIndex) t.updatePiecePriority(pieceIndex) go t.verifyPiece(pieceIndex) }
[ "func", "(", "t", "*", "Torrent", ")", "queuePieceCheck", "(", "pieceIndex", "pieceIndex", ")", "{", "piece", ":=", "&", "t", ".", "pieces", "[", "pieceIndex", "]", "\n", "if", "piece", ".", "queuedForHash", "(", ")", "{", "return", "\n", "}", "\n", "t", ".", "piecesQueuedForHash", ".", "Add", "(", "bitmap", ".", "BitIndex", "(", "pieceIndex", ")", ")", "\n", "t", ".", "publishPieceChange", "(", "pieceIndex", ")", "\n", "t", ".", "updatePiecePriority", "(", "pieceIndex", ")", "\n", "go", "t", ".", "verifyPiece", "(", "pieceIndex", ")", "\n", "}" ]
// Currently doesn't really queue, but should in the future.
[ "Currently", "doesn", "t", "really", "queue", "but", "should", "in", "the", "future", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1658-L1667
22,088
anacrolix/torrent
torrent.go
initiateConn
func (t *Torrent) initiateConn(peer Peer) { if peer.Id == t.cl.peerID { return } if t.cl.badPeerIPPort(peer.IP, peer.Port) { return } addr := IpPort{peer.IP, uint16(peer.Port)} if t.addrActive(addr.String()) { return } t.halfOpen[addr.String()] = peer go t.cl.outgoingConnection(t, addr, peer.Source) }
go
func (t *Torrent) initiateConn(peer Peer) { if peer.Id == t.cl.peerID { return } if t.cl.badPeerIPPort(peer.IP, peer.Port) { return } addr := IpPort{peer.IP, uint16(peer.Port)} if t.addrActive(addr.String()) { return } t.halfOpen[addr.String()] = peer go t.cl.outgoingConnection(t, addr, peer.Source) }
[ "func", "(", "t", "*", "Torrent", ")", "initiateConn", "(", "peer", "Peer", ")", "{", "if", "peer", ".", "Id", "==", "t", ".", "cl", ".", "peerID", "{", "return", "\n", "}", "\n", "if", "t", ".", "cl", ".", "badPeerIPPort", "(", "peer", ".", "IP", ",", "peer", ".", "Port", ")", "{", "return", "\n", "}", "\n", "addr", ":=", "IpPort", "{", "peer", ".", "IP", ",", "uint16", "(", "peer", ".", "Port", ")", "}", "\n", "if", "t", ".", "addrActive", "(", "addr", ".", "String", "(", ")", ")", "{", "return", "\n", "}", "\n", "t", ".", "halfOpen", "[", "addr", ".", "String", "(", ")", "]", "=", "peer", "\n", "go", "t", ".", "cl", ".", "outgoingConnection", "(", "t", ",", "addr", ",", "peer", ".", "Source", ")", "\n", "}" ]
// Start the process of connecting to the given peer for the given torrent if // appropriate.
[ "Start", "the", "process", "of", "connecting", "to", "the", "given", "peer", "for", "the", "given", "torrent", "if", "appropriate", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1677-L1690
22,089
anacrolix/torrent
torrent.go
allStats
func (t *Torrent) allStats(f func(*ConnStats)) { f(&t.stats) f(&t.cl.stats) }
go
func (t *Torrent) allStats(f func(*ConnStats)) { f(&t.stats) f(&t.cl.stats) }
[ "func", "(", "t", "*", "Torrent", ")", "allStats", "(", "f", "func", "(", "*", "ConnStats", ")", ")", "{", "f", "(", "&", "t", ".", "stats", ")", "\n", "f", "(", "&", "t", ".", "cl", ".", "stats", ")", "\n", "}" ]
// All stats that include this Torrent. Useful when we want to increment // ConnStats but not for every connection.
[ "All", "stats", "that", "include", "this", "Torrent", ".", "Useful", "when", "we", "want", "to", "increment", "ConnStats", "but", "not", "for", "every", "connection", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1706-L1709
22,090
anacrolix/torrent
metainfo/info.go
BuildFromFilePath
func (info *Info) BuildFromFilePath(root string) (err error) { info.Name = filepath.Base(root) info.Files = nil err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { if err != nil { return err } if fi.IsDir() { // Directories are implicit in torrent files. return nil } else if path == root { // The root is a file. info.Length = fi.Size() return nil } relPath, err := filepath.Rel(root, path) if err != nil { return fmt.Errorf("error getting relative path: %s", err) } info.Files = append(info.Files, FileInfo{ Path: strings.Split(relPath, string(filepath.Separator)), Length: fi.Size(), }) return nil }) if err != nil { return } slices.Sort(info.Files, func(l, r FileInfo) bool { return strings.Join(l.Path, "/") < strings.Join(r.Path, "/") }) err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) { return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator)))) }) if err != nil { err = fmt.Errorf("error generating pieces: %s", err) } return }
go
func (info *Info) BuildFromFilePath(root string) (err error) { info.Name = filepath.Base(root) info.Files = nil err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { if err != nil { return err } if fi.IsDir() { // Directories are implicit in torrent files. return nil } else if path == root { // The root is a file. info.Length = fi.Size() return nil } relPath, err := filepath.Rel(root, path) if err != nil { return fmt.Errorf("error getting relative path: %s", err) } info.Files = append(info.Files, FileInfo{ Path: strings.Split(relPath, string(filepath.Separator)), Length: fi.Size(), }) return nil }) if err != nil { return } slices.Sort(info.Files, func(l, r FileInfo) bool { return strings.Join(l.Path, "/") < strings.Join(r.Path, "/") }) err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) { return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator)))) }) if err != nil { err = fmt.Errorf("error generating pieces: %s", err) } return }
[ "func", "(", "info", "*", "Info", ")", "BuildFromFilePath", "(", "root", "string", ")", "(", "err", "error", ")", "{", "info", ".", "Name", "=", "filepath", ".", "Base", "(", "root", ")", "\n", "info", ".", "Files", "=", "nil", "\n", "err", "=", "filepath", ".", "Walk", "(", "root", ",", "func", "(", "path", "string", ",", "fi", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "fi", ".", "IsDir", "(", ")", "{", "// Directories are implicit in torrent files.", "return", "nil", "\n", "}", "else", "if", "path", "==", "root", "{", "// The root is a file.", "info", ".", "Length", "=", "fi", ".", "Size", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "relPath", ",", "err", ":=", "filepath", ".", "Rel", "(", "root", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "info", ".", "Files", "=", "append", "(", "info", ".", "Files", ",", "FileInfo", "{", "Path", ":", "strings", ".", "Split", "(", "relPath", ",", "string", "(", "filepath", ".", "Separator", ")", ")", ",", "Length", ":", "fi", ".", "Size", "(", ")", ",", "}", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "slices", ".", "Sort", "(", "info", ".", "Files", ",", "func", "(", "l", ",", "r", "FileInfo", ")", "bool", "{", "return", "strings", ".", "Join", "(", "l", ".", "Path", ",", "\"", "\"", ")", "<", "strings", ".", "Join", "(", "r", ".", "Path", ",", "\"", "\"", ")", "\n", "}", ")", "\n", "err", "=", "info", ".", "GeneratePieces", "(", "func", "(", "fi", "FileInfo", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "root", ",", "strings", ".", "Join", "(", "fi", ".", "Path", ",", "string", "(", "filepath", ".", "Separator", ")", ")", ")", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// This is a helper that sets Files and Pieces from a root path and its // children.
[ "This", "is", "a", "helper", "that", "sets", "Files", "and", "Pieces", "from", "a", "root", "path", "and", "its", "children", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L29-L67
22,091
anacrolix/torrent
metainfo/info.go
writeFiles
func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error { for _, fi := range info.UpvertedFiles() { r, err := open(fi) if err != nil { return fmt.Errorf("error opening %v: %s", fi, err) } wn, err := io.CopyN(w, r, fi.Length) r.Close() if wn != fi.Length { return fmt.Errorf("error copying %v: %s", fi, err) } } return nil }
go
func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error { for _, fi := range info.UpvertedFiles() { r, err := open(fi) if err != nil { return fmt.Errorf("error opening %v: %s", fi, err) } wn, err := io.CopyN(w, r, fi.Length) r.Close() if wn != fi.Length { return fmt.Errorf("error copying %v: %s", fi, err) } } return nil }
[ "func", "(", "info", "*", "Info", ")", "writeFiles", "(", "w", "io", ".", "Writer", ",", "open", "func", "(", "fi", "FileInfo", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", ")", "error", "{", "for", "_", ",", "fi", ":=", "range", "info", ".", "UpvertedFiles", "(", ")", "{", "r", ",", "err", ":=", "open", "(", "fi", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fi", ",", "err", ")", "\n", "}", "\n", "wn", ",", "err", ":=", "io", ".", "CopyN", "(", "w", ",", "r", ",", "fi", ".", "Length", ")", "\n", "r", ".", "Close", "(", ")", "\n", "if", "wn", "!=", "fi", ".", "Length", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fi", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Concatenates all the files in the torrent into w. open is a function that // gets at the contents of the given file.
[ "Concatenates", "all", "the", "files", "in", "the", "torrent", "into", "w", ".", "open", "is", "a", "function", "that", "gets", "at", "the", "contents", "of", "the", "given", "file", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L71-L84
22,092
anacrolix/torrent
metainfo/info.go
UpvertedFiles
func (info *Info) UpvertedFiles() []FileInfo { if len(info.Files) == 0 { return []FileInfo{{ Length: info.Length, // Callers should determine that Info.Name is the basename, and // thus a regular file. Path: nil, }} } return info.Files }
go
func (info *Info) UpvertedFiles() []FileInfo { if len(info.Files) == 0 { return []FileInfo{{ Length: info.Length, // Callers should determine that Info.Name is the basename, and // thus a regular file. Path: nil, }} } return info.Files }
[ "func", "(", "info", "*", "Info", ")", "UpvertedFiles", "(", ")", "[", "]", "FileInfo", "{", "if", "len", "(", "info", ".", "Files", ")", "==", "0", "{", "return", "[", "]", "FileInfo", "{", "{", "Length", ":", "info", ".", "Length", ",", "// Callers should determine that Info.Name is the basename, and", "// thus a regular file.", "Path", ":", "nil", ",", "}", "}", "\n", "}", "\n", "return", "info", ".", "Files", "\n", "}" ]
// The files field, converted up from the old single-file in the parent info // dict if necessary. This is a helper to avoid having to conditionally handle // single and multi-file torrent infos.
[ "The", "files", "field", "converted", "up", "from", "the", "old", "single", "-", "file", "in", "the", "parent", "info", "dict", "if", "necessary", ".", "This", "is", "a", "helper", "to", "avoid", "having", "to", "conditionally", "handle", "single", "and", "multi", "-", "file", "torrent", "infos", "." ]
d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb
https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L142-L152
22,093
kubernetes-retired/heapster
metrics/util/label_copier.go
makeStoredLabels
func makeStoredLabels(labels []string) map[string]string { storedLabels := make(map[string]string) for _, s := range labels { split := strings.SplitN(s, "=", 2) if len(split) == 1 { storedLabels[split[0]] = split[0] } else { storedLabels[split[1]] = split[0] } } return storedLabels }
go
func makeStoredLabels(labels []string) map[string]string { storedLabels := make(map[string]string) for _, s := range labels { split := strings.SplitN(s, "=", 2) if len(split) == 1 { storedLabels[split[0]] = split[0] } else { storedLabels[split[1]] = split[0] } } return storedLabels }
[ "func", "makeStoredLabels", "(", "labels", "[", "]", "string", ")", "map", "[", "string", "]", "string", "{", "storedLabels", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "s", ":=", "range", "labels", "{", "split", ":=", "strings", ".", "SplitN", "(", "s", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "split", ")", "==", "1", "{", "storedLabels", "[", "split", "[", "0", "]", "]", "=", "split", "[", "0", "]", "\n", "}", "else", "{", "storedLabels", "[", "split", "[", "1", "]", "]", "=", "split", "[", "0", "]", "\n", "}", "\n", "}", "\n", "return", "storedLabels", "\n", "}" ]
// makeStoredLabels converts labels into a map for quicker retrieval. // Incoming labels, if desired, may contain mappings in format "newName=oldName"
[ "makeStoredLabels", "converts", "labels", "into", "a", "map", "for", "quicker", "retrieval", ".", "Incoming", "labels", "if", "desired", "may", "contain", "mappings", "in", "format", "newName", "=", "oldName" ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L56-L67
22,094
kubernetes-retired/heapster
metrics/util/label_copier.go
makeIgnoredLabels
func makeIgnoredLabels(labels []string) map[string]string { ignoredLabels := make(map[string]string) for _, s := range labels { ignoredLabels[s] = "" } return ignoredLabels }
go
func makeIgnoredLabels(labels []string) map[string]string { ignoredLabels := make(map[string]string) for _, s := range labels { ignoredLabels[s] = "" } return ignoredLabels }
[ "func", "makeIgnoredLabels", "(", "labels", "[", "]", "string", ")", "map", "[", "string", "]", "string", "{", "ignoredLabels", ":=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "for", "_", ",", "s", ":=", "range", "labels", "{", "ignoredLabels", "[", "s", "]", "=", "\"", "\"", "\n", "}", "\n", "return", "ignoredLabels", "\n", "}" ]
// makeIgnoredLabels converts label slice into a map for later use.
[ "makeIgnoredLabels", "converts", "label", "slice", "into", "a", "map", "for", "later", "use", "." ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L70-L76
22,095
kubernetes-retired/heapster
metrics/util/label_copier.go
NewLabelCopier
func NewLabelCopier(separator string, storedLabels, ignoredLabels []string) (*LabelCopier, error) { return &LabelCopier{ labelSeparator: separator, storedLabels: makeStoredLabels(storedLabels), ignoredLabels: makeIgnoredLabels(ignoredLabels), }, nil }
go
func NewLabelCopier(separator string, storedLabels, ignoredLabels []string) (*LabelCopier, error) { return &LabelCopier{ labelSeparator: separator, storedLabels: makeStoredLabels(storedLabels), ignoredLabels: makeIgnoredLabels(ignoredLabels), }, nil }
[ "func", "NewLabelCopier", "(", "separator", "string", ",", "storedLabels", ",", "ignoredLabels", "[", "]", "string", ")", "(", "*", "LabelCopier", ",", "error", ")", "{", "return", "&", "LabelCopier", "{", "labelSeparator", ":", "separator", ",", "storedLabels", ":", "makeStoredLabels", "(", "storedLabels", ")", ",", "ignoredLabels", ":", "makeIgnoredLabels", "(", "ignoredLabels", ")", ",", "}", ",", "nil", "\n", "}" ]
// NewLabelCopier creates a new instance of LabelCopier type
[ "NewLabelCopier", "creates", "a", "new", "instance", "of", "LabelCopier", "type" ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L79-L85
22,096
kubernetes-retired/heapster
events/sinks/influxdb/influxdb.go
getEventValue
func getEventValue(event *kube_api.Event) (string, error) { // TODO: check whether indenting is required. bytes, err := json.MarshalIndent(event, "", " ") if err != nil { return "", err } return string(bytes), nil }
go
func getEventValue(event *kube_api.Event) (string, error) { // TODO: check whether indenting is required. bytes, err := json.MarshalIndent(event, "", " ") if err != nil { return "", err } return string(bytes), nil }
[ "func", "getEventValue", "(", "event", "*", "kube_api", ".", "Event", ")", "(", "string", ",", "error", ")", "{", "// TODO: check whether indenting is required.", "bytes", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "event", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "bytes", ")", ",", "nil", "\n", "}" ]
// Generate point value for event
[ "Generate", "point", "value", "for", "event" ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/events/sinks/influxdb/influxdb.go#L61-L68
22,097
kubernetes-retired/heapster
events/sinks/influxdb/influxdb.go
newSink
func newSink(c influxdb_common.InfluxdbConfig) core.EventSink { client, err := influxdb_common.NewClient(c) if err != nil { glog.Errorf("issues while creating an InfluxDB sink: %v, will retry on use", err) } return &influxdbSink{ client: client, // can be nil c: c, } }
go
func newSink(c influxdb_common.InfluxdbConfig) core.EventSink { client, err := influxdb_common.NewClient(c) if err != nil { glog.Errorf("issues while creating an InfluxDB sink: %v, will retry on use", err) } return &influxdbSink{ client: client, // can be nil c: c, } }
[ "func", "newSink", "(", "c", "influxdb_common", ".", "InfluxdbConfig", ")", "core", ".", "EventSink", "{", "client", ",", "err", ":=", "influxdb_common", ".", "NewClient", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "influxdbSink", "{", "client", ":", "client", ",", "// can be nil", "c", ":", "c", ",", "}", "\n", "}" ]
// Returns a thread-safe implementation of core.EventSink for InfluxDB.
[ "Returns", "a", "thread", "-", "safe", "implementation", "of", "core", ".", "EventSink", "for", "InfluxDB", "." ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/events/sinks/influxdb/influxdb.go#L230-L239
22,098
kubernetes-retired/heapster
metrics/sinks/opentsdb/driver.go
metricToPoint
func (tsdbSink *openTSDBSink) metricToPoint(name string, value core.MetricValue, timestamp time.Time, labels map[string]string) opentsdbclient.DataPoint { seriesName := strings.Replace(toValidOpenTsdbName(name), "/", "_", -1) if value.MetricType.String() != "" { seriesName = fmt.Sprintf("%s_%s", seriesName, value.MetricType.String()) } datapoint := opentsdbclient.DataPoint{ Metric: seriesName, Tags: make(map[string]string, len(labels)), Timestamp: timestamp.Unix(), } if value.ValueType == core.ValueInt64 { datapoint.Value = value.IntValue } else { datapoint.Value = value.FloatValue } for key, value := range labels { key = toValidOpenTsdbName(key) value = toValidOpenTsdbName(value) if value != "" { datapoint.Tags[key] = value } } tsdbSink.putDefaultTags(&datapoint) return datapoint }
go
func (tsdbSink *openTSDBSink) metricToPoint(name string, value core.MetricValue, timestamp time.Time, labels map[string]string) opentsdbclient.DataPoint { seriesName := strings.Replace(toValidOpenTsdbName(name), "/", "_", -1) if value.MetricType.String() != "" { seriesName = fmt.Sprintf("%s_%s", seriesName, value.MetricType.String()) } datapoint := opentsdbclient.DataPoint{ Metric: seriesName, Tags: make(map[string]string, len(labels)), Timestamp: timestamp.Unix(), } if value.ValueType == core.ValueInt64 { datapoint.Value = value.IntValue } else { datapoint.Value = value.FloatValue } for key, value := range labels { key = toValidOpenTsdbName(key) value = toValidOpenTsdbName(value) if value != "" { datapoint.Tags[key] = value } } tsdbSink.putDefaultTags(&datapoint) return datapoint }
[ "func", "(", "tsdbSink", "*", "openTSDBSink", ")", "metricToPoint", "(", "name", "string", ",", "value", "core", ".", "MetricValue", ",", "timestamp", "time", ".", "Time", ",", "labels", "map", "[", "string", "]", "string", ")", "opentsdbclient", ".", "DataPoint", "{", "seriesName", ":=", "strings", ".", "Replace", "(", "toValidOpenTsdbName", "(", "name", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "if", "value", ".", "MetricType", ".", "String", "(", ")", "!=", "\"", "\"", "{", "seriesName", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "seriesName", ",", "value", ".", "MetricType", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "datapoint", ":=", "opentsdbclient", ".", "DataPoint", "{", "Metric", ":", "seriesName", ",", "Tags", ":", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "labels", ")", ")", ",", "Timestamp", ":", "timestamp", ".", "Unix", "(", ")", ",", "}", "\n", "if", "value", ".", "ValueType", "==", "core", ".", "ValueInt64", "{", "datapoint", ".", "Value", "=", "value", ".", "IntValue", "\n", "}", "else", "{", "datapoint", ".", "Value", "=", "value", ".", "FloatValue", "\n", "}", "\n\n", "for", "key", ",", "value", ":=", "range", "labels", "{", "key", "=", "toValidOpenTsdbName", "(", "key", ")", "\n", "value", "=", "toValidOpenTsdbName", "(", "value", ")", "\n\n", "if", "value", "!=", "\"", "\"", "{", "datapoint", ".", "Tags", "[", "key", "]", "=", "value", "\n", "}", "\n", "}", "\n\n", "tsdbSink", ".", "putDefaultTags", "(", "&", "datapoint", ")", "\n", "return", "datapoint", "\n", "}" ]
// timeSeriesToPoint transfers the contents holding in the given pointer of sink_api.Timeseries // into the instance of opentsdbclient.DataPoint
[ "timeSeriesToPoint", "transfers", "the", "contents", "holding", "in", "the", "given", "pointer", "of", "sink_api", ".", "Timeseries", "into", "the", "instance", "of", "opentsdbclient", ".", "DataPoint" ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/opentsdb/driver.go#L117-L146
22,099
kubernetes-retired/heapster
metrics/sinks/opentsdb/driver.go
putDefaultTags
func (tsdbSink *openTSDBSink) putDefaultTags(datapoint *opentsdbclient.DataPoint) { datapoint.Tags[clusterNameTagName] = tsdbSink.clusterName }
go
func (tsdbSink *openTSDBSink) putDefaultTags(datapoint *opentsdbclient.DataPoint) { datapoint.Tags[clusterNameTagName] = tsdbSink.clusterName }
[ "func", "(", "tsdbSink", "*", "openTSDBSink", ")", "putDefaultTags", "(", "datapoint", "*", "opentsdbclient", ".", "DataPoint", ")", "{", "datapoint", ".", "Tags", "[", "clusterNameTagName", "]", "=", "tsdbSink", ".", "clusterName", "\n", "}" ]
// putDefaultTags just fills in the default key-value pair for the tags. // OpenTSDB requires at least one non-empty tag otherwise the OpenTSDB will return error and the operation of putting // datapoint will be failed.
[ "putDefaultTags", "just", "fills", "in", "the", "default", "key", "-", "value", "pair", "for", "the", "tags", ".", "OpenTSDB", "requires", "at", "least", "one", "non", "-", "empty", "tag", "otherwise", "the", "OpenTSDB", "will", "return", "error", "and", "the", "operation", "of", "putting", "datapoint", "will", "be", "failed", "." ]
e1e83412787b60d8a70088f09a2cb12339b305c3
https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/sinks/opentsdb/driver.go#L151-L153