libeech

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

commit 27f38a6292d4d6c6de8ea1712dc5060024b44189
parent 34cb6c512c6609748925c64f4b8058ef3dc30e5d
Author: z3bra <contactatz3bradotorg>
Date:   Wed Oct 18 08:47:49 +0200

Factorize glch_loadtorrent() into smaller functions

Diffstat:
libeech.c | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
torrent.c | 5++++-
2 files changed, 58 insertions(+), 10 deletions(-)
diff --git a/libeech.c b/libeech.c @@ -15,7 +15,13 @@ #include "util.h" #include "libeech.h" + +/* Initialization of the torrent struct */ static char * peerid(); +static int loadfile(struct torrent *, char *); +static int loadtracker(struct torrent *); +static int loadinfohash(struct torrent *); +static int loadpeerid(struct torrent *); static char * peerid() @@ -34,45 +40,84 @@ peerid() return peerid; } -int -glch_loadtorrent(struct torrent *t, char *path) +/* Read torrent file into a memory buffer */ +static int +loadfile(struct torrent *t, char *path) { FILE *f; - char *b, *sp; - struct be be; + char *b; struct stat sb; - /* read torrent file into a memory buffer */ if (stat(path, &sb)) return -1; if (!(f = fopen(path, "r"))) return -1; b = malloc(sb.st_size); + if (!b) + return -1; fread(b, 1, sb.st_size, f); b[sb.st_size - 1] = '\0'; beinit(&t->be, b, sb.st_size); fclose(f); + return 0; +} + +/* Retrieve the "announce" key */ +static int +loadtracker(struct torrent *t) +{ + char *sp; - /* retrieve "announce" key */ sp = bekstr(&t->be, "announce", 8); if (!sp) return -1; memcpy(t->tr, sp, strlen(sp)); + return 0; +} + +/* Calculate the SHA1 hash of the "info" key */ +static int +loadinfohash(struct torrent *t) +{ + char *sp; + struct be be; - /* store SHA1 of the info key */ if (bekv(&t->be, "info", 4, &be) < 0) return -1; sp = be.off; if (benext(&be) < 0) return -1; - sha1((unsigned char *)sp, be.off - sp, t->infohash); + return sha1((unsigned char *)sp, be.off - sp, t->infohash); +} + +/* Generate a random peer ID */ +static int +loadpeerid(struct torrent *t) +{ + char *sp; - /* generate a random peer ID */ sp = peerid(); if (!sp) return -1; memcpy(t->id, sp, 20); t->id[20] = 0; + return 0; +} + +int +glch_loadtorrent(struct torrent *t, char *f) +{ + if (loadfile(t, f) < 0) + return -1; + + if (loadtracker(t) < 0) + return -1; + + if (loadinfohash(t) < 0) + return -1; + + if (loadpeerid(t) < 0) + return -1; return 0; } diff --git a/torrent.c b/torrent.c @@ -1,11 +1,13 @@ #include <stdio.h> #include <stdlib.h> - #include <libeech.h> +#include "util.h" + int main(int argc, char *argv[]) { + char hex[41]; struct torrent t; if (argc < 2) { @@ -16,6 +18,7 @@ main(int argc, char *argv[]) if (!glch_loadtorrent(&t, argv[1])) { printf("Peer ID: %s\n", t.id); printf("Tracker: %s\n", t.tr); + printf("Infokey: %s\n", tohex(t.infohash, hex, 20)); } return 0;