libeech

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

commit dfdb0fe7098b4c2789baac70e528ec734cfe82b5
parent 4677f08d67ca79c4bd76bd9dfa1ac161b30869f4
Author: z3bra <contactatz3bradotorg>
Date:   Sat Nov  4 21:11:08 +0100

netloop() to handle peer connections

Diffstat:
libeech.c | 55++++++++++++++++++++++++++++++++++++++++++++++++++++++-
libeech.h | 1+
torrent.c | 4++++
3 files changed, 59 insertions(+), 1 deletion(-)
diff --git a/libeech.c b/libeech.c @@ -3,6 +3,7 @@ #include <fcntl.h> #include <limits.h> #include <netdb.h> +#include <poll.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> @@ -35,6 +36,9 @@ static ssize_t pwphs(struct torrent *, struct peer *); static ssize_t pwphsrecv(struct peer *); static int pwphsck(struct torrent *, char *, long); +/* p2p network management */ +static int netloop(struct torrent *, int); + static char * peerid() { @@ -246,7 +250,7 @@ delpeer(struct peer *pl, struct peer *p) static int peercnt(struct peer *pl) { - return (pl ? 1 : 0) + peercnt(pl->next); + return (pl ? 1 + peercnt(pl->next) : 0); } static ssize_t @@ -295,6 +299,49 @@ pwphsck(struct torrent *t, char *hs, long l) return 0; } +static int +netloop(struct torrent *t, int timeout) +{ + int i, npeer = 0; + nfds_t nfds; + struct peer *p; + struct pollfd *fds; + + nfds = peercnt(t->peers); + fds = malloc(nfds * sizeof(*fds)); + if (!fds) + return -1; + + for (i = 0, p = t->peers; p; p = p->next) { + fds[i].fd = p->fd; + fds[i].events = POLLIN|POLLOUT; + } + + /* poll all peers for TCP events */ + if (!poll(fds, nfds, timeout)) { + printf("timeout!\n"); + return -1; + } + for (i = 0, p = t->peers; p; p = p->next) { + if (fds[i].revents & POLLOUT) { + /* send handshake */ + if (!(p->state & HANDSHAKESENT)) { + pwphs(t, p); + p->state |= HANDSHAKESENT; + } + } + if (fds[i].revents & POLLIN) { + /* receive and verify handshake */ + if (!(p->state & HANDSHAKERCVD)) { + if (pwphsrecv(p) > 0 && !pwphsck(t, p->buf, p->buflen)) + p->state |= HANDSHAKERCVD; + } + } + } + + return npeer; +} + int glch_loadtorrent(struct torrent *t, char *b, size_t s) { @@ -346,3 +393,9 @@ glch_addpeer(struct torrent *t, char *host, int port) return 0; } + +int +glch_leech(struct torrent *t, int timeout) +{ + return netloop(t, timeout); +} diff --git a/libeech.h b/libeech.h @@ -48,3 +48,4 @@ struct torrent { int glch_loadtorrent(struct torrent *, char *, size_t); int glch_addpeer(struct torrent *, char *, int); +int glch_leech(struct torrent *, int); diff --git a/torrent.c b/torrent.c @@ -63,5 +63,9 @@ main(int argc, char *argv[]) for (i=0; i<t.nfile; i++) printf("\t%s\n", t.files[i].path); + glch_addpeer(&t, "localhost", 6937); + for (;;) + glch_leech(&t, 5000); + return 0; }