commit a860d6f0ec24bb61d7742f53f3c9c56f931a92fb
parent 1b95d93ca2bc0cd467e48f69c983cd421e53dc23
Author: sin <sin@2f30.org>
Date: Fri, 18 Dec 2015 15:19:35 +0000
More updates to torrent.c
Diffstat:
3 files changed, 27 insertions(+), 15 deletions(-)
diff --git a/ben.c b/ben.c
@@ -175,14 +175,6 @@ bdecode(char *s, char *e, struct ben **b)
return NULL;
}
-void
-bencode(char **buf, size_t *n, struct ben *b)
-{
- *n = b->end - b->start;
- *buf = emalloc(*n);
- memcpy(*buf, b->start, *n);
-}
-
char *
bstr2str(struct ben *b)
{
diff --git a/sbtd.h b/sbtd.h
@@ -35,11 +35,11 @@ struct torrent {
long long length;
long long piecelen;
long long npieces;
+ uint32_t *piecebm;
};
/* ben.c */
char *bdecode(char *, char *, struct ben **);
-void bencode(char **, size_t *, struct ben *);
char *bstr2str(struct ben *);
int bstrcmp(struct ben *, struct ben *);
struct ben *dlook(struct ben *, struct ben *);
@@ -50,6 +50,7 @@ void bprint(struct ben *, int);
/* torrent.c */
struct torrent *loadtorrent(char *);
void unloadtorrent(struct torrent *);
+int piecehash(struct torrent *, long long, uint8_t *);
/* util.c */
void *emalloc(size_t);
diff --git a/torrent.c b/torrent.c
@@ -18,6 +18,7 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include "sbtd.h"
#include "sha1.h"
@@ -25,12 +26,8 @@
static void
calcinfohash(struct torrent *t)
{
- char *buf;
- size_t n;
-
- bencode(&buf, &n, t->info);
- sha1sum((unsigned char *)buf, n, t->infohash);
- free(buf);
+ sha1sum((unsigned char *)t->info->start,
+ t->info->end - t->info->start, t->infohash);
}
struct torrent *
@@ -54,6 +51,16 @@ loadtorrent(char *f)
goto err2;
}
+ t->pieces = dlookstr(t->info, "pieces");
+ if (!t->pieces) {
+ warnx("no pieces field in %s", f);
+ goto err2;
+ }
+ if (t->pieces->len % 20) {
+ warnx("incorrect piece length in %s", f);
+ goto err2;
+ }
+
if (!dlookstr(t->ben, "announce")) {
warnx("no announce field in %s", f);
goto err2;
@@ -73,8 +80,10 @@ loadtorrent(char *f)
t->piecelen = dlookstr(t->info, "piece length")->i;
t->npieces = (t->length + t->piecelen - 1) / t->piecelen;
+ t->piecebm = newbit(t->npieces);
calcinfohash(t);
+
return t;
err2:
bfree(t->ben);
@@ -92,5 +101,15 @@ unloadtorrent(struct torrent *t)
return;
bfree(t->ben);
free(t->buf);
+ free(t->piecebm);
free(t);
}
+
+int
+piecehash(struct torrent *t, long long n, uint8_t *md)
+{
+ if (n < 0 || n >= t->npieces)
+ return -1;
+ memcpy(md, t->pieces->start + n * 20, 20);
+ return 0;
+}