repo
stringlengths 5
67
| sha
stringlengths 40
40
| path
stringlengths 4
234
| url
stringlengths 85
339
| language
stringclasses 6
values | split
stringclasses 3
values | doc
stringlengths 3
51.2k
| sign
stringlengths 5
8.01k
| problem
stringlengths 13
51.2k
| output
stringlengths 0
3.87M
|
---|---|---|---|---|---|---|---|---|---|
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | tracker/udp.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L156-L180 | go | train | // body is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41. | func (c *udpAnnounce) write(h *RequestHeader, body interface{}, trailer []byte) (err error) | // body is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | tracker/udp.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L192-L251 | go | train | // args is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41. | func (c *udpAnnounce) request(action Action, args interface{}, options []byte) (*bytes.Buffer, error) | // args is the binary serializable request body. trailer is optional data
// following it, such as for BEP 41.
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
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | tracker/udp.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/udp.go#L307-L314 | go | train | // TODO: Split on IPv6, as BEP 15 says response peer decoding depends on
// network in use. | func announceUDP(opt Announce, _url *url.URL) (AnnounceResponse, error) | // TODO: Split on IPv6, as BEP 15 says response peer decoding depends on
// network in use.
func announceUDP(opt Announce, _url *url.URL) (AnnounceResponse, error) | {
ua := udpAnnounce{
url: *_url,
a: &opt,
}
defer ua.Close()
return ua.Do(opt.Request)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | misc.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L47-L53 | go | train | // The size in bytes of a metadata extension piece. | func metadataPieceSize(totalSize int, piece int) int | // The size in bytes of a metadata extension piece.
func metadataPieceSize(totalSize int, piece int) int | {
ret := totalSize - piece*(1<<14)
if ret > 1<<14 {
ret = 1 << 14
}
return ret
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | misc.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/misc.go#L56-L74 | go | train | // Return the request that would include the given offset into the torrent data. | func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
r request, ok bool) | // Return the request that would include the given offset into the torrent data.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | peer_protocol/handshake.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/peer_protocol/handshake.go#L76-L137 | go | train | // 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. | func Handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions PeerExtensionBits) (res HandshakeResult, ok bool, err error) | // 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.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/decode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L78-L86 | go | train | // reads data writing it to 'd.buf' until 'sep' byte is encountered, 'sep' byte
// is consumed, but not included into the 'd.buf' | func (d *Decoder) readUntil(sep byte) | // reads data writing it to 'd.buf' until 'sep' byte is encountered, 'sep' byte
// is consumed, but not included into the 'd.buf'
func (d *Decoder) readUntil(sep byte) | {
for {
b := d.readByte()
if b == sep {
return
}
d.buf.WriteByte(b)
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/decode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L105-L149 | go | train | // called when 'i' was consumed | func (d *Decoder) parseInt(v reflect.Value) | // called when 'i' was consumed
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()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/decode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L217-L254 | go | train | // Returns specifics for parsing a dict field value. | func getDictField(dict reflect.Value, key string) dictField | // Returns specifics for parsing a dict field value.
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{}
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/decode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L467-L517 | go | train | // Returns true if there was a value and it's now stored in 'v', otherwise
// there was an end symbol ("e") and no value was stored. | func (d *Decoder) parseValue(v reflect.Value) (bool, error) | // Returns true if there was a value and it's now stored in 'v', otherwise
// there was an end symbol ("e") and no value was stored.
func (d *Decoder) parseValue(v reflect.Value) (bool, error) | {
// we support one level of indirection at the moment
if v.Kind() == reflect.Ptr {
// if the pointer is nil, allocate a new element of the type it
// points to
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
if d.parseUnmarshaler(v) {
return true, nil
}
// common case: interface{}
if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
iface, _ := d.parseValueInterface()
v.Set(reflect.ValueOf(iface))
return true, nil
}
b, err := d.r.ReadByte()
if err != nil {
panic(err)
}
d.Offset++
switch b {
case 'e':
return false, nil
case 'd':
return true, d.parseDict(v)
case 'l':
return true, d.parseList(v)
case 'i':
d.parseInt(v)
return true, nil
default:
if b >= '0' && b <= '9' {
// It's a string.
d.buf.Reset()
// Write the first digit of the length to the buffer.
d.buf.WriteByte(b)
return true, d.parseString(v)
}
d.raiseUnknownValueType(b, d.Offset-1)
}
panic("unreachable")
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/decode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/decode.go#L520-L525 | go | train | // An unknown bencode type character was encountered. | func (d *Decoder) raiseUnknownValueType(b byte, offset int64) | // An unknown bencode type character was encountered.
func (d *Decoder) raiseUnknownValueType(b byte, offset int64) | {
panic(&SyntaxError{
Offset: offset,
What: fmt.Errorf("unknown value type %+q", b),
})
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | tracker_scraper.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker_scraper.go#L99-L131 | go | train | // Return how long to wait before trying again. For most errors, we return 5
// minutes, a relatively quick turn around for DNS changes. | func (me *trackerScraper) announce() (ret trackerAnnounceResult) | // Return how long to wait before trying again. For most errors, we return 5
// minutes, a relatively quick turn around for DNS changes.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | iplist/cidr.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/iplist/cidr.go#L31-L41 | go | train | // Returns the last, inclusive IP in a net.IPNet. | func IPNetLast(in *net.IPNet) (last net.IP) | // Returns the last, inclusive IP in a net.IPNet.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | bencode/encode.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/bencode/encode.go#L82-L97 | go | train | // Returns true if the value implements Marshaler interface and marshaling was
// done successfully. | func (e *Encoder) reflectMarshaler(v reflect.Value) bool | // Returns true if the value implements Marshaler interface and marshaling was
// done successfully.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L45-L52 | go | train | // The relative file path for a multi-file torrent, and the torrent name for a
// single-file torrent. | func (f *File) DisplayPath() string | // The relative file path for a multi-file torrent, and the torrent name for a
// single-file torrent.
func (f *File) DisplayPath() string | {
fip := f.FileInfo().Path
if len(fip) == 0 {
return f.t.info.Name
}
return strings.Join(fip, "/")
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L61-L81 | go | train | // Returns the state of pieces in this file. | func (f *File) State() (ret []FilePieceState) | // Returns the state of pieces in this file.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L112-L120 | go | train | // Sets the minimum priority for pieces in the File. | func (f *File) SetPriority(prio piecePriority) | // Sets the minimum priority for pieces in the File.
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())
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/file.go#L123-L127 | go | train | // Returns the priority per File.SetPriority. | func (f *File) Priority() piecePriority | // Returns the priority per File.SetPriority.
func (f *File) Priority() piecePriority | {
f.t.cl.lock()
defer f.t.cl.unlock()
return f.prio
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L118-L152 | go | train | // Writes out a human readable status of the client, such as for writing to a
// HTTP status page. | func (cl *Client) WriteStatus(_w io.Writer) | // Writes out a human readable status of the client, such as for writing to a
// HTTP status page.
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)
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L352-L365 | go | train | // Stops the client. All connections to peers are closed and all activity will
// come to a halt. | func (cl *Client) Close() | // Stops the client. All connections to peers are closed and all activity will
// come to a halt.
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()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L465-L470 | go | train | // Returns a handle to the given torrent, if it's present in the client. | func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) | // Returns a handle to the given torrent, if it's present in the client.
func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) | {
cl.lock()
defer cl.unlock()
t, ok = cl.torrents[ih]
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L498-L501 | go | train | // Returns whether an address is known to connect to a client with our own ID. | func (cl *Client) dopplegangerAddr(addr string) bool | // Returns whether an address is known to connect to a client with our own ID.
func (cl *Client) dopplegangerAddr(addr string) bool | {
_, ok := cl.dopplegangerAddrs[addr]
return ok
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L504-L583 | go | train | // Returns a connection over UTP or TCP, whichever is first to connect. | func (cl *Client) dialFirst(ctx context.Context, addr string) dialResult | // Returns a connection over UTP or TCP, whichever is first to connect.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L599-L617 | go | train | // Performs initiator handshakes and returns a connection. Returns nil
// *connection if no connection for valid reasons. | func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader bool, remoteAddr IpPort, network string) (c *connection, err error) | // Performs initiator handshakes and returns a connection. Returns nil
// *connection if no connection for valid reasons.
func (cl *Client) handshakesConnection(ctx context.Context, nc net.Conn, t *Torrent, encryptHeader bool, remoteAddr IpPort, network string) (c *connection, err error) | {
c = cl.newConnection(nc, true, remoteAddr, network)
c.headerEncrypted = encryptHeader
ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
defer cancel()
dl, ok := ctx.Deadline()
if !ok {
panic(ctx)
}
err = nc.SetDeadline(dl)
if err != nil {
panic(err)
}
ok, err = cl.initiateHandshakes(c, t)
if !ok {
c = nil
}
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L621-L633 | go | train | // Returns nil connection and nil error if no connection could be established
// for valid reasons. | func (cl *Client) establishOutgoingConnEx(t *Torrent, addr IpPort, ctx context.Context, obfuscatedHeader bool) (c *connection, err error) | // Returns nil connection and nil error if no connection could be established
// for valid reasons.
func (cl *Client) establishOutgoingConnEx(t *Torrent, addr IpPort, ctx context.Context, obfuscatedHeader bool) (c *connection, err error) | {
dr := cl.dialFirst(ctx, addr.String())
nc := dr.Conn
if nc == nil {
return
}
defer func() {
if c == nil || err != nil {
nc.Close()
}
}()
return cl.handshakesConnection(ctx, nc, t, obfuscatedHeader, addr, dr.Network)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L637-L668 | go | train | // Returns nil connection and nil error if no connection could be established
// for valid reasons. | func (cl *Client) establishOutgoingConn(t *Torrent, addr IpPort) (c *connection, err error) | // Returns nil connection and nil error if no connection could be established
// for valid reasons.
func (cl *Client) establishOutgoingConn(t *Torrent, addr IpPort) (c *connection, err error) | {
torrent.Add("establish outgoing connection", 1)
ctx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
cl.rLock()
defer cl.rUnlock()
return t.dialTimeout()
}())
defer cancel()
obfuscatedHeaderFirst := !cl.config.DisableEncryption && !cl.config.PreferNoEncryption
c, err = cl.establishOutgoingConnEx(t, addr, ctx, obfuscatedHeaderFirst)
if err != nil {
return
}
if c != nil {
torrent.Add("initiated conn with preferred header obfuscation", 1)
return
}
if cl.config.ForceEncryption {
// We should have just tried with an obfuscated header. A plaintext
// header can't result in an encrypted connection, so we're done.
if !obfuscatedHeaderFirst {
panic(cl.config.EncryptionPolicy)
}
return
}
// Try again with encryption if we didn't earlier, or without if we did.
c, err = cl.establishOutgoingConnEx(t, addr, ctx, !obfuscatedHeaderFirst)
if c != nil {
torrent.Add("initiated conn with fallback header obfuscation", 1)
}
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L672-L692 | go | train | // Called to dial out and run a connection. The addr we're given is already
// considered half-open. | func (cl *Client) outgoingConnection(t *Torrent, addr IpPort, ps peerSource) | // Called to dial out and run a connection. The addr we're given is already
// considered half-open.
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)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L734-L742 | go | train | // Calls f with any secret keys. | func (cl *Client) forSkeys(f func([]byte) bool) | // Calls f with any secret keys.
func (cl *Client) forSkeys(f func([]byte) bool) | {
cl.lock()
defer cl.unlock()
for ih := range cl.torrents {
if !f(ih[:]) {
break
}
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L745-L781 | go | train | // Do encryption and bittorrent handshakes as receiver. | func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) | // Do encryption and bittorrent handshakes as receiver.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L784-L794 | go | train | // Returns !ok if handshake failed for valid reasons. | func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) | // Returns !ok if handshake failed for valid reasons.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L864-L912 | go | train | // See the order given in Transmission's tr_peerMsgsNew. | func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) | // See the order given in Transmission's tr_peerMsgsNew.
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(),
})
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L929-L968 | go | train | // Process incoming ut_metadata message. | func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error | // Process incoming ut_metadata message.
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")
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L987-L1021 | go | train | // Return a Torrent ready for insertion into a Client. | func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) | // Return a Torrent ready for insertion into a Client.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1038-L1057 | go | train | // 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` | func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) | // 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`
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1065-L1084 | go | train | // Add or merge a torrent spec. If the torrent is already present, the
// trackers will be merged with the existing ones. If the Info isn't yet
// known, it will be set. The display name is replaced if the new spec
// provides one. Returns new if the torrent wasn't already in the client.
// Note that any `Storage` defined on the spec will be ignored if the
// torrent is already present (i.e. `new` return value is `true`) | func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) | // Add or merge a torrent spec. If the torrent is already present, the
// trackers will be merged with the existing ones. If the Info isn't yet
// known, it will be set. The display name is replaced if the new spec
// provides one. Returns new if the torrent wasn't already in the client.
// Note that any `Storage` defined on the spec will be ignored if the
// torrent is already present (i.e. `new` return value is `true`)
func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) | {
t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
if spec.DisplayName != "" {
t.SetDisplayName(spec.DisplayName)
}
if spec.InfoBytes != nil {
err = t.SetInfoBytes(spec.InfoBytes)
if err != nil {
return
}
}
cl.lock()
defer cl.unlock()
if spec.ChunkSize != 0 {
t.setChunkSize(pp.Integer(spec.ChunkSize))
}
t.addTrackers(spec.Trackers)
t.maybeNewConns()
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1114-L1124 | go | train | // Returns true when all torrents are completely downloaded and false if the
// client is stopped before that. | func (cl *Client) WaitAll() bool | // Returns true when all torrents are completely downloaded and false if the
// client is stopped before that.
func (cl *Client) WaitAll() bool | {
cl.lock()
defer cl.unlock()
for !cl.allTorrentsCompleted() {
if cl.closed.IsSet() {
return false
}
cl.event.Wait()
}
return true
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1127-L1131 | go | train | // Returns handles to all the torrents loaded in the Client. | func (cl *Client) Torrents() []*Torrent | // Returns handles to all the torrents loaded in the Client.
func (cl *Client) Torrents() []*Torrent | {
cl.lock()
defer cl.unlock()
return cl.torrentsAsSlice()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | client.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/client.go#L1277-L1279 | go | train | // Our IP as a peer should see it. | func (cl *Client) publicAddr(peer net.IP) IpPort | // Our IP as a peer should see it.
func (cl *Client) publicAddr(peer net.IP) IpPort | {
return IpPort{cl.publicIp(peer), uint16(cl.incomingPeerPort())}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | mse/mse.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L175-L179 | go | train | // Calculate, and send Y, our public key. | func (h *handshake) postY(x *big.Int) error | // Calculate, and send Y, our public key.
func (h *handshake) postY(x *big.Int) error | {
var y big.Int
y.Exp(&g, x, &p)
return h.postWrite(paddedLeft(y.Bytes(), 96))
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | mse/mse.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L322-L339 | go | train | // Looking for b at the end of a. | func suffixMatchLen(a, b []byte) int | // Looking for b at the end of a.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | mse/mse.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/mse/mse.go#L343-L360 | go | train | // Reads from r until b has been seen. Keeps the minimum amount of data in
// memory. | func readUntil(r io.Reader, b []byte) error | // Reads from r until b has been seen. Keeps the minimum amount of data in
// memory.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | tracker/peer.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/tracker/peer.go#L16-L22 | go | train | // Set from the non-compact form in BEP 3. | func (p *Peer) fromDictInterface(d map[string]interface{}) | // Set from the non-compact form in BEP 3.
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))
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | metainfo/announcelist.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/announcelist.go#L6-L15 | go | train | // Whether the AnnounceList should be preferred over a single URL announce. | func (al AnnounceList) OverridesAnnounce(announce string) bool | // Whether the AnnounceList should be preferred over a single URL announce.
func (al AnnounceList) OverridesAnnounce(announce string) bool | {
for _, tier := range al {
for _, url := range tier {
if url != "" || announce == "" {
return true
}
}
}
return false
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | prioritized_peers.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/prioritized_peers.go#L33-L35 | go | train | // Returns true if a peer is replaced. | func (me *prioritizedPeers) Add(p Peer) bool | // Returns true if a peer is replaced.
func (me *prioritizedPeers) Add(p Peer) bool | {
return me.om.ReplaceOrInsert(prioritizedPeersItem{me.getPrio(p), p}) != nil
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | storage/file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L21-L23 | go | train | // The Default path maker just returns the current path | func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string | // The Default path maker just returns the current path
func defaultPathMaker(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string | {
return baseDir
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | storage/file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L44-L46 | go | train | // Allows passing a function to determine the path for storing torrent data | func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl | // Allows passing a function to determine the path for storing torrent data
func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl | {
return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir))
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | storage/file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L103-L118 | go | train | // 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. | func CreateNativeZeroLengthFiles(info *metainfo.Info, dir string) (err error) | // 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.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | storage/file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L126-L152 | go | train | // Returns EOF on short or missing file. | func (fst *fileTorrentImplIO) readFileAt(fi metainfo.FileInfo, b []byte, off int64) (n int, err error) | // Returns EOF on short or missing file.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | storage/file.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/storage/file.go#L155-L181 | go | train | // Only returns EOF at the end of the torrent. Premature EOF is ErrUnexpectedEOF. | func (fst fileTorrentImplIO) ReadAt(b []byte, off int64) (n int, err error) | // Only returns EOF at the end of the torrent. Premature EOF is ErrUnexpectedEOF.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L19-L23 | go | train | // Returns a channel that is closed when the info (.Info()) for the torrent
// has become available. | func (t *Torrent) GotInfo() <-chan struct{} | // Returns a channel that is closed when the info (.Info()) for the torrent
// has become available.
func (t *Torrent) GotInfo() <-chan struct{} | {
t.cl.lock()
defer t.cl.unlock()
return t.gotMetainfo.C()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L26-L30 | go | train | // Returns the metainfo info dictionary, or nil if it's not yet available. | func (t *Torrent) Info() *metainfo.Info | // Returns the metainfo info dictionary, or nil if it's not yet available.
func (t *Torrent) Info() *metainfo.Info | {
t.cl.lock()
defer t.cl.unlock()
return t.info
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L34-L43 | go | train | // Returns a Reader bound to the torrent's data. All read calls block until
// the data requested is actually available. | func (t *Torrent) NewReader() Reader | // Returns a Reader bound to the torrent's data. All read calls block until
// the data requested is actually available.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L48-L52 | go | train | // 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. | func (t *Torrent) PieceStateRuns() []PieceStateRun | // 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.
func (t *Torrent) PieceStateRuns() []PieceStateRun | {
t.cl.rLock()
defer t.cl.rUnlock()
return t.pieceStateRuns()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L67-L72 | go | train | // Get missing bytes count for specific piece. | func (t *Torrent) PieceBytesMissing(piece int) int64 | // Get missing bytes count for specific piece.
func (t *Torrent) PieceBytesMissing(piece int) int64 | {
t.cl.lock()
defer t.cl.unlock()
return int64(t.pieces[piece].bytesLeft())
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L77-L81 | go | train | // 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. | func (t *Torrent) Drop() | // 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.
func (t *Torrent) Drop() | {
t.cl.lock()
t.cl.dropTorrent(t.infoHash)
t.cl.unlock()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L87-L91 | go | train | // 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. | func (t *Torrent) BytesCompleted() int64 | // 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.
func (t *Torrent) BytesCompleted() int64 | {
t.cl.rLock()
defer t.cl.rUnlock()
return t.bytesCompleted()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L101-L105 | go | train | // Returns true if the torrent is currently being seeded. This occurs when the
// client is willing to upload without wanting anything in return. | func (t *Torrent) Seeding() bool | // Returns true if the torrent is currently being seeded. This occurs when the
// client is willing to upload without wanting anything in return.
func (t *Torrent) Seeding() bool | {
t.cl.lock()
defer t.cl.unlock()
return t.seeding()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L109-L116 | go | train | // Clobbers the torrent display name. The display name is used as the torrent
// name if the metainfo is not available. | func (t *Torrent) SetDisplayName(dn string) | // Clobbers the torrent display name. The display name is used as the torrent
// name if the metainfo is not available.
func (t *Torrent) SetDisplayName(dn string) | {
t.nameMu.Lock()
defer t.nameMu.Unlock()
if t.haveInfo() {
return
}
t.displayName = dn
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L132-L136 | go | train | // Returns a run-time generated metainfo for the torrent that includes the
// info bytes and announce-list as currently known to the client. | func (t *Torrent) Metainfo() metainfo.MetaInfo | // Returns a run-time generated metainfo for the torrent that includes the
// info bytes and announce-list as currently known to the client.
func (t *Torrent) Metainfo() metainfo.MetaInfo | {
t.cl.lock()
defer t.cl.unlock()
return t.newMetaInfo()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | t.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/t.go#L156-L160 | go | train | // 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. | func (t *Torrent) DownloadPieces(begin, end pieceIndex) | // 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.
func (t *Torrent) DownloadPieces(begin, end pieceIndex) | {
t.cl.lock()
defer t.cl.unlock()
t.downloadPiecesLocked(begin, end)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L157-L187 | go | train | // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
// pending, and half-open peers. | func (t *Torrent) KnownSwarm() (ks []Peer) | // KnownSwarm returns the known subset of the peers in the Torrent's swarm, including active,
// pending, and half-open peers.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L208-L219 | go | train | // There's a connection to that address already. | func (t *Torrent) addrActive(addr string) bool | // There's a connection to that address already.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L315-L322 | go | train | // Returns the index of the first file containing the piece. files must be
// ordered by offset. | func pieceFirstFileIndex(pieceOffset int64, files []*File) int | // Returns the index of the first file containing the piece. files must be
// ordered by offset.
func pieceFirstFileIndex(pieceOffset int64, files []*File) int | {
for i, f := range files {
if f.offset+f.length > pieceOffset {
return i
}
}
return 0
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L326-L333 | go | train | // Returns the index after the last file containing the piece. files must be
// ordered by offset. | func pieceEndFileIndex(pieceEndOffset int64, files []*File) int | // Returns the index after the last file containing the piece. files must be
// ordered by offset.
func pieceEndFileIndex(pieceEndOffset int64, files []*File) int | {
for i, f := range files {
if f.offset+f.length >= pieceEndOffset {
return i + 1
}
}
return 0
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L387-L402 | go | train | // Called when metadata for a torrent becomes available. | func (t *Torrent) setInfoBytes(b []byte) error | // Called when metadata for a torrent becomes available.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L420-L438 | go | train | // TODO: Propagate errors to disconnect peer. | func (t *Torrent) setMetadataSize(bytes int) (err error) | // TODO: Propagate errors to disconnect peer.
func (t *Torrent) setMetadataSize(bytes int) (err error) | {
if t.haveInfo() {
// We already know the correct metadata size.
return
}
if bytes <= 0 || bytes > 10000000 { // 10MB, pulled from my ass.
return errors.New("bad size")
}
if t.metadataBytes != nil && len(t.metadataBytes) == int(bytes) {
return
}
t.metadataBytes = make([]byte, bytes)
t.metadataCompletedChunks = make([]bool, (bytes+(1<<14)-1)/(1<<14))
t.metadataChanged.Broadcast()
for c := range t.conns {
c.requestPendingMetadata()
}
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L442-L449 | go | train | // 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 "". | func (t *Torrent) name() string | // 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 "".
func (t *Torrent) name() string | {
t.nameMu.RLock()
defer t.nameMu.RUnlock()
if t.haveInfo() {
return t.info.Name
}
return t.displayName
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L499-L530 | go | train | // Produces a small string representing a PieceStateRun. | func pieceStateRunStatusChars(psr PieceStateRun) (ret string) | // Produces a small string representing a PieceStateRun.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L602-L616 | go | train | // Returns a run-time generated MetaInfo that includes the info bytes and
// announce-list as currently known to the client. | func (t *Torrent) newMetaInfo() metainfo.MetaInfo | // Returns a run-time generated MetaInfo that includes the info bytes and
// announce-list as currently known to the client.
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
}
}(),
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L638-L644 | go | train | // Bytes left to give in tracker announces. | func (t *Torrent) bytesLeftAnnounce() uint64 | // Bytes left to give in tracker announces.
func (t *Torrent) bytesLeftAnnounce() uint64 | {
if t.haveInfo() {
return uint64(t.bytesLeft())
} else {
return math.MaxUint64
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L691-L693 | go | train | // Return the request that would include the given offset into the torrent
// data. Returns !ok if there is no such request. | func (t *Torrent) offsetRequest(off int64) (req request, ok bool) | // Return the request that would include the given offset into the torrent
// data. Returns !ok if there is no such request.
func (t *Torrent) offsetRequest(off int64) (req request, ok bool) | {
return torrentOffsetRequest(*t.length, t.info.PieceLength, int64(t.chunkSize), off)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L815-L833 | go | train | // 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. | func (t *Torrent) worstBadConn() *connection | // 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.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L936-L940 | go | train | // Update all piece priorities in one hit. This function should have the same
// output as updatePiecePriority, but across all pieces. | func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) | // Update all piece priorities in one hit. This function should have the same
// output as updatePiecePriority, but across all pieces.
func (t *Torrent) updatePiecePriorities(begin, end pieceIndex) | {
for i := begin; i < end; i++ {
t.updatePiecePriority(i)
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L943-L960 | go | train | // Returns the range of pieces [begin, end) that contains the extent of bytes. | func (t *Torrent) byteRegionPieces(off, size int64) (begin, end pieceIndex) | // Returns the range of pieces [begin, end) that contains the extent of bytes.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L965-L976 | go | train | // 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. | func (t *Torrent) forReaderOffsetPieces(f func(begin, end pieceIndex) (more bool)) (all bool) | // 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.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1074-L1078 | go | train | // Non-blocking read. Client lock is not required. | func (t *Torrent) readAt(b []byte, off int64) (n int, err error) | // Non-blocking read. Client lock is not required.
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())
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1088-L1106 | go | train | // Returns an error if the metadata was completed, but couldn't be set for
// some reason. Blame it on the last peer to contribute. | func (t *Torrent) maybeCompleteMetadata() error | // Returns an error if the metadata was completed, but couldn't be set for
// some reason. Blame it on the last peer to contribute.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1162-L1167 | go | train | // Don't call this before the info is available. | func (t *Torrent) bytesCompleted() int64 | // Don't call this before the info is available.
func (t *Torrent) bytesCompleted() int64 | {
if !t.haveInfo() {
return 0
}
return t.info.TotalLength() - t.bytesLeft()
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1176-L1190 | go | train | // Returns true if connection is removed from torrent.Conns. | func (t *Torrent) deleteConnection(c *connection) (ret bool) | // Returns true if connection is removed from torrent.Conns.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1228-L1243 | go | train | // Returns whether the client should make effort to seed the torrent. | func (t *Torrent) seeding() bool | // Returns whether the client should make effort to seed the torrent.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1287-L1297 | go | train | // Adds and starts tracker scrapers for tracker URLs that aren't already
// running. | func (t *Torrent) startMissingTrackerScrapers() | // Adds and starts tracker scrapers for tracker URLs that aren't already
// running.
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)
}
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1301-L1319 | go | train | // Returns an AnnounceRequest with fields filled out to defaults and current
// values. | func (t *Torrent) announceRequest() tracker.AnnounceRequest | // Returns an AnnounceRequest with fields filled out to defaults and current
// values.
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(),
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1323-L1340 | go | train | // Adds peers revealed in an announce until the announce ends, or we have
// enough peers. | func (t *Torrent) consumeDhtAnnouncePeers(pvs <-chan dht.PeersValues) | // Adds peers revealed in an announce until the announce ends, or we have
// enough peers.
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()
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1402-L1419 | go | train | // The total number of peers in the torrent. | func (t *Torrent) numTotalPeers() int | // The total number of peers in the torrent.
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)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1423-L1436 | go | train | // Reconcile bytes transferred before connection was associated with a
// torrent. | func (t *Torrent) reconcileHandshakeStats(c *connection) | // Reconcile bytes transferred before connection was associated with a
// torrent.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1439-L1475 | go | train | // Returns true if the connection is added. | func (t *Torrent) addConnection(c *connection) (err error) | // Returns true if the connection is added.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1580-L1604 | go | train | // Called when a piece is found to be not complete. | func (t *Torrent) onIncompletePiece(piece pieceIndex) | // Called when a piece is found to be not complete.
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()
}
}
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1641-L1648 | go | train | // Return the connections that touched a piece, and clear the entries while
// doing it. | func (t *Torrent) reapPieceTouchers(piece pieceIndex) (ret []*connection) | // Return the connections that touched a piece, and clear the entries while
// doing it.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1658-L1667 | go | train | // Currently doesn't really queue, but should in the future. | func (t *Torrent) queuePieceCheck(pieceIndex pieceIndex) | // Currently doesn't really queue, but should in the future.
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)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1677-L1690 | go | train | // Start the process of connecting to the given peer for the given torrent if
// appropriate. | func (t *Torrent) initiateConn(peer Peer) | // Start the process of connecting to the given peer for the given torrent if
// appropriate.
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)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | torrent.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/torrent.go#L1706-L1709 | go | train | // All stats that include this Torrent. Useful when we want to increment
// ConnStats but not for every connection. | func (t *Torrent) allStats(f func(*ConnStats)) | // All stats that include this Torrent. Useful when we want to increment
// ConnStats but not for every connection.
func (t *Torrent) allStats(f func(*ConnStats)) | {
f(&t.stats)
f(&t.cl.stats)
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | peer_protocol/decoder.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/peer_protocol/decoder.go#L22-L101 | go | train | // io.EOF is returned if the source terminates cleanly on a message boundary.
// TODO: Is that before or after the message? | func (d *Decoder) Decode(msg *Message) (err error) | // io.EOF is returned if the source terminates cleanly on a message boundary.
// TODO: Is that before or after the message?
func (d *Decoder) Decode(msg *Message) (err error) | {
var length Integer
err = binary.Read(d.R, binary.BigEndian, &length)
if err != nil {
if err != io.EOF {
err = fmt.Errorf("error reading message length: %s", err)
}
return
}
if length > d.MaxLength {
return errors.New("message too long")
}
if length == 0 {
msg.Keepalive = true
return
}
msg.Keepalive = false
r := &io.LimitedReader{R: d.R, N: int64(length)}
// Check that all of r was utilized.
defer func() {
if err != nil {
return
}
if r.N != 0 {
err = fmt.Errorf("%d bytes unused in message type %d", r.N, msg.Type)
}
}()
msg.Keepalive = false
c, err := readByte(r)
if err != nil {
return
}
msg.Type = MessageType(c)
switch msg.Type {
case Choke, Unchoke, Interested, NotInterested, HaveAll, HaveNone:
return
case Have, AllowedFast, Suggest:
err = msg.Index.Read(r)
case Request, Cancel, Reject:
for _, data := range []*Integer{&msg.Index, &msg.Begin, &msg.Length} {
err = data.Read(r)
if err != nil {
break
}
}
case Bitfield:
b := make([]byte, length-1)
_, err = io.ReadFull(r, b)
msg.Bitfield = unmarshalBitfield(b)
case Piece:
for _, pi := range []*Integer{&msg.Index, &msg.Begin} {
err := pi.Read(r)
if err != nil {
return err
}
}
dataLen := r.N
msg.Piece = (*d.Pool.Get().(*[]byte))
if int64(cap(msg.Piece)) < dataLen {
return errors.New("piece data longer than expected")
}
msg.Piece = msg.Piece[:dataLen]
_, err := io.ReadFull(r, msg.Piece)
if err != nil {
return errors.Wrap(err, "reading piece data")
}
case Extended:
b, err := readByte(r)
if err != nil {
break
}
msg.ExtendedID = ExtensionNumber(b)
msg.ExtendedPayload, err = ioutil.ReadAll(r)
case Port:
err = binary.Read(r, binary.BigEndian, &msg.Port)
default:
err = fmt.Errorf("unknown message type %#v", c)
}
return
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | metainfo/info.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L29-L67 | go | train | // This is a helper that sets Files and Pieces from a root path and its
// children. | func (info *Info) BuildFromFilePath(root string) (err error) | // This is a helper that sets Files and Pieces from a root path and its
// children.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | metainfo/info.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L71-L84 | go | train | // Concatenates all the files in the torrent into w. open is a function that
// gets at the contents of the given file. | func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error | // Concatenates all the files in the torrent into w. open is a function that
// gets at the contents of the given file.
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
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | metainfo/info.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L88-L118 | go | train | // Sets Pieces (the block of piece hashes in the Info) by using the passed
// function to get at the torrent data. | func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error | // Sets Pieces (the block of piece hashes in the Info) by using the passed
// function to get at the torrent data.
func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error | {
if info.PieceLength == 0 {
return errors.New("piece length must be non-zero")
}
pr, pw := io.Pipe()
go func() {
err := info.writeFiles(pw, open)
pw.CloseWithError(err)
}()
defer pr.Close()
var pieces []byte
for {
hasher := sha1.New()
wn, err := io.CopyN(hasher, pr, info.PieceLength)
if err == io.EOF {
err = nil
}
if err != nil {
return err
}
if wn == 0 {
break
}
pieces = hasher.Sum(pieces)
if wn < info.PieceLength {
break
}
}
info.Pieces = pieces
return nil
} |
anacrolix/torrent | d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb | metainfo/info.go | https://github.com/anacrolix/torrent/blob/d2400968fc54c3d8a6482d4ca5ff16cc5e5139cb/metainfo/info.go#L142-L152 | go | train | // 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. | func (info *Info) UpvertedFiles() []FileInfo | // 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.
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
} |
kubernetes-retired/heapster | e1e83412787b60d8a70088f09a2cb12339b305c3 | metrics/util/label_copier.go | https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L37-L52 | go | train | // Copy copies the given set of pod labels into a set of metric labels, using the following logic:
// - all labels, unless found in ignoredLabels, are concatenated into a Separator-separated key:value pairs and stored under core.LabelLabels.Key
// - labels found in storedLabels are additionally stored under key provided | func (this *LabelCopier) Copy(in map[string]string, out map[string]string) | // Copy copies the given set of pod labels into a set of metric labels, using the following logic:
// - all labels, unless found in ignoredLabels, are concatenated into a Separator-separated key:value pairs and stored under core.LabelLabels.Key
// - labels found in storedLabels are additionally stored under key provided
func (this *LabelCopier) Copy(in map[string]string, out map[string]string) | {
labels := make([]string, 0, len(in))
for key, value := range in {
if mappedKey, exists := this.storedLabels[key]; exists {
out[mappedKey] = value
}
if _, exists := this.ignoredLabels[key]; !exists {
labels = append(labels, fmt.Sprintf("%s:%s", key, value))
}
}
sort.Strings(labels)
out[core.LabelLabels.Key] = strings.Join(labels, this.labelSeparator)
} |
kubernetes-retired/heapster | e1e83412787b60d8a70088f09a2cb12339b305c3 | metrics/util/label_copier.go | https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L56-L67 | go | train | // makeStoredLabels converts labels into a map for quicker retrieval.
// Incoming labels, if desired, may contain mappings in format "newName=oldName" | func makeStoredLabels(labels []string) map[string]string | // makeStoredLabels converts labels into a map for quicker retrieval.
// Incoming labels, if desired, may contain mappings in format "newName=oldName"
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
} |
kubernetes-retired/heapster | e1e83412787b60d8a70088f09a2cb12339b305c3 | metrics/util/label_copier.go | https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L70-L76 | go | train | // makeIgnoredLabels converts label slice into a map for later use. | func makeIgnoredLabels(labels []string) map[string]string | // makeIgnoredLabels converts label slice into a map for later use.
func makeIgnoredLabels(labels []string) map[string]string | {
ignoredLabels := make(map[string]string)
for _, s := range labels {
ignoredLabels[s] = ""
}
return ignoredLabels
} |
kubernetes-retired/heapster | e1e83412787b60d8a70088f09a2cb12339b305c3 | metrics/util/label_copier.go | https://github.com/kubernetes-retired/heapster/blob/e1e83412787b60d8a70088f09a2cb12339b305c3/metrics/util/label_copier.go#L79-L85 | go | train | // NewLabelCopier creates a new instance of LabelCopier type | func NewLabelCopier(separator string, storedLabels, ignoredLabels []string) (*LabelCopier, error) | // NewLabelCopier creates a new instance of LabelCopier type
func NewLabelCopier(separator string, storedLabels, ignoredLabels []string) (*LabelCopier, error) | {
return &LabelCopier{
labelSeparator: separator,
storedLabels: makeStoredLabels(storedLabels),
ignoredLabels: makeIgnoredLabels(ignoredLabels),
}, nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.