libeech

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

commit e93c18236b4d74ace9d237ffaf1ec75b7c17ea72
parent 0d1a23c249eff31fecba9735ac0a4d537e3144e6
Author: z3bra <contactatz3bradotorg>
Date:   Sat Feb 10 12:35:25 +0100

Use a structure to handle peer's socket polling

Diffstat:
libeech.c | 55++++++++++++++++++++++++++++++++++---------------------
1 file changed, 34 insertions(+), 21 deletions(-)
diff --git a/libeech.c b/libeech.c @@ -18,6 +18,11 @@ #include "util.h" #include "libeech.h" +struct peerfds { + struct peer **p; + struct pollfd *fds; +}; + /* helpers to retrieve attributes from metadata */ static char * peerid(); static long torrentsize(struct torrent *); @@ -302,41 +307,49 @@ netconn(char *host, int port) static int netloop(struct torrent *t, int timeout) { - int i, npeer = 0; - nfds_t nfds; + int r, npeer = 0; + nfds_t i, nfds; struct peer *p; - struct pollfd *fds; + struct peerfds pfds; nfds = peercnt(t->peers); - fds = malloc(nfds * sizeof(*fds)); - if (!fds) + if (nfds < 1) return -1; + pfds.p = malloc(nfds * sizeof(*pfds.p)); + pfds.fds = malloc(nfds * sizeof(*pfds.fds)); + for (i = 0, p = t->peers; p; p = p->next) { - if (p->fd < 0) - fds[i].fd = p->fd; - fds[i].events = POLLIN|POLLOUT; + if (p->fd > 0) { + pfds.p[i] = p; + pfds.fds[i].fd = p->fd; + pfds.fds[i].events = POLLIN|POLLOUT|POLLERR; + i++; + } } + nfds = i; /* poll all peers for TCP events */ - if (!poll(fds, nfds, timeout)) - return -1; + if ((r = poll(pfds.fds, nfds, timeout)) < 1) + return r; - for (i = 0, p = t->peers; p; p = p->next) { - if (fds[i].revents & POLLOUT) { + for (i = 0; i < nfds; i++) { + //printf("fd:%d ev:%d\n", pfds.p[i]->fd, pfds.fds[i].revents); + if (pfds.fds[i].revents & POLLOUT) { /* send handshake */ - if (!(p->state & HANDSHAKESENT)) { - pwphs(t, p); - p->state |= HANDSHAKESENT; + if (!(pfds.p[i]->state & HANDSHAKESENT)) { + pwphs(t, pfds.p[i]); + pfds.p[i]->state |= HANDSHAKESENT; } } - if (fds[i].revents & POLLIN) { + + if (pfds.fds[i].revents & POLLIN) { /* receive and verify handshake */ - if (!(p->state & HANDSHAKERCVD)) { - if (pwphsrecv(p) >= 68) - p->state |= HANDSHAKERCVD; - if (pwphsck(t, p->buf, p->buflen)) - p->state |= CONNECTED; + if (!(pfds.p[i]->state & HANDSHAKERCVD)) { + if (pwphsrecv(pfds.p[i]) >= 68) + pfds.p[i]->state |= HANDSHAKERCVD; + if (!pwphsck(t, pfds.p[i]->buf, pfds.p[i]->buflen)) + pfds.p[i]->state |= CONNECTED; } } }