libeech

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

commit c1adc61b9c6af64d09843c2f53e7222683ed04aa
parent 4129efb6930f09c75b9c9037579149f538a038d6
Author: z3bra <contactatz3bradotorg>
Date:   Sun Feb 25 08:14:52 -0500

Add function to receive messages

Diffstat:
libeech.c | 37++++++++++++++++++++++++++++++++++++-
1 file changed, 36 insertions(+), 1 deletion(-)
diff --git a/libeech.c b/libeech.c @@ -18,6 +18,9 @@ #include "util.h" #include "libeech.h" +/* return a 4 byte array as a 32 bit integer */ +#define U32(s) ((uint32_t)((s)[0])<<24|((s)[1])<<16|((s)[2])<<8|((s)[3])) + struct peerfds { struct peer **p; struct pollfd *fds; @@ -337,7 +340,6 @@ pwphsrecv(struct peer *p) { ssize_t r; - /* read message length, sent as 4 bytes integer */ while ((r = recv(p->fd, p->buf, 68 - p->buflen, 0)) > 0) p->buflen += r; @@ -364,6 +366,35 @@ pwphsck(struct torrent *t, char *hs, long l) return 0; } +static ssize_t +pwprecv(struct peer *p) +{ + ssize_t s, l, r; + + if (!p->buflen) { + /* read the first 4 bytes to get message length */ + if ((r = recv(p->fd, p->buf, 4, MSG_PEEK)) < 4) + return -1; + } + + /* expected message length */ + l = U32(p->buf) + 4; + + if (l > MSGSIZ) + return -1; + + s = p->buflen; + while ((r = recv(p->fd, p->buf, l - s, 0)) > 0) { + l -= r; + s += r; + } + + if (r < 0) + return -1; + + return l; +} + /* * Standard PWP messages: [LENGTH][TYPE][PAYLOAD] * Length: 4 bytes bigendian; Size of the type + payload @@ -414,7 +445,11 @@ pwprx(struct torrent *t, struct peer *p) delpeer(t->peers, p); return -1; } + p->buflen = 0; p->state |= HANDSHAKERCVD; + } else { + p->buflen = pwprecv(p); + printf("Message ID: %d (%d bytes)\n", p->buf[4], U32(p->buf)); } return 0; }