tAdd function to receive messages - libeech - bittorrent library
(HTM) git clone git://z3bra.org/libeech.git
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit c1adc61b9c6af64d09843c2f53e7222683ed04aa
(DIR) parent 4129efb6930f09c75b9c9037579149f538a038d6
(HTM) Author: z3bra <contactatz3bradotorg>
Date: Sun, 25 Feb 2018 08:14:52 -0500
Add function to receive messages
Diffstat:
M libeech.c | 37 ++++++++++++++++++++++++++++++-
1 file changed, 36 insertions(+), 1 deletion(-)
---
(DIR) diff --git a/libeech.c b/libeech.c
t@@ -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;
t@@ -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;
t@@ -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
t@@ -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;
}