libeech

BitTorrent library
git clone git://z3bra.org/libeech.git
Log | Files | Refs | README | LICENSE

commit 03ccf2b025a14a05633ab312cdad29745d5071db
parent 98d359fa4fc5e1b1f9ac22e8c92fbfe04abea44b
Author: z3bra <contactatz3bradotorg>
Date:   Mon,  9 Jul 2018 09:01:04 +0200

Request one block at a time in pwptxrq()

Diffstat:
libeech.c | 63++++++++++++++++++++++++++++++++++++---------------------------
libeech.h | 8+++++---
2 files changed, 41 insertions(+), 30 deletions(-)

diff --git a/libeech.c b/libeech.c @@ -623,46 +623,55 @@ pwptxbf(struct torrent *t, struct peer *p) static ssize_t pwptxrq(struct torrent *t, struct peer *p) { - int i; char m[MSGSIZ]; - ssize_t bl; + ssize_t i, bl, bo; /* Find a missing piece we can get from the peer */ - for (i = 0; i < t->npiece && (bit(t->bf, i) || !bit(p->bf, i)); i++); + if (p->piece.n < 0) { + for (i = 0; i < t->npiece && (bit(t->bf, i) || !bit(p->bf, i)); i++); + memset(p->piece.bl, 0, sizeof(p->piece.bl)); + memset(p->piece.rq, 0, sizeof(p->piece.rq)); - if (i == t->npiece) - return -1; + if (i == t->npiece) + return -1; - p->piece.n = i; - p->piece.sz = (i == t->npiece - 1) ? t->sz % t->psz : t->psz; + p->piece.n = i; + p->piece.sz = (i == t->npiece - 1) ? t->sz % t->psz : t->psz; + } - i = 0; - while (i < p->piece.sz) { - bl = BLKSIZ; - if (i + BLKSIZ > p->piece.sz) - bl = p->piece.sz - i; + /* Find a block that hasn't been requested yet */ + for (i = 0; i < BLKNUM && bit(p->piece.rq, i); i++); - memset(m, 0, MSGSIZ); + bo = i * BLKSIZ; + bl = BLKSIZ; + if (bo + BLKSIZ > p->piece.sz) + bl = p->piece.sz - bo; - /* Message length */ - U32(m) = htonl(13); + /* All blocks requested */ + if (bo >= p->piece.sz) + return -1; - /* Message type */ - m[4] = REQUEST; - /* Piece index */ - U32(m+5) = htonl(p->piece.n); + memset(m, 0, MSGSIZ); - /* Block offset */ - U32(m+9) = htonl(i); + /* Message length */ + U32(m) = htonl(13); - /* Block length */ - U32(m+13) = htonl(bl); + /* Message type */ + m[4] = REQUEST; - pwpsend(p, m, 17); + /* Piece index */ + U32(m+5) = htonl(p->piece.n); - i += bl; - } + /* Block offset */ + U32(m+9) = htonl(bo); + + /* Block length */ + U32(m+13) = htonl(bl); + + pwpsend(p, m, 17); + + setbit(p->piece.rq, i); return 0; } @@ -814,7 +823,7 @@ pwptx(struct torrent *t, struct peer *p) p->state |= AMINTERESTED; } - if (!(p->state & AMCHOKING) && p->piece.n < 0) + if (!(p->state & AMCHOKING)) pwptxrq(t, p); } diff --git a/libeech.h b/libeech.h @@ -3,11 +3,13 @@ #include "be.h" -#define PCENUM 65535 #define PCESIZ 1048576 #define BLKSIZ 16384 #define MSGSIZ ((BLKSIZ) + 13) +#define PCENUM 65535 +#define BLKNUM ((PCESIZ)/(BLKSIZ)+!!((PCESIZ)%(BLKSIZ))) + enum { CONNECTED = 1 << 0, HANDSHAKESENT = 1 << 1, @@ -24,8 +26,8 @@ struct piece { int n; ssize_t sz; char blks[PCESIZ]; - char rq[PCESIZ / BLKSIZ + !!(PCESIZ % BLKSIZ)]; - char bl[PCESIZ / BLKSIZ + !!(PCESIZ % BLKSIZ)]; + char rq[BLKNUM / 8 + !!(BLKNUM % 8)]; + char bl[BLKNUM / 8 + !!(BLKNUM % 8)]; }; struct peer {