http: download interrompido continua de onde parou

Um <arquivo>.parte que ja existe vai no pedido como "Range: bytes=N-":
com 206 o download anexa ao .parte; com 200 (servidor sem Range)
recomeca; com 416 apaga o .parte e tenta do zero. O .parte nao e mais
apagado num erro de transferencia, para a proxima tentativa continuar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-26 23:50:45 -03:00
1 parent 51f55e60ff
commit 829bc67142
2 files changed
+58 -11

No files matched your search

+26 -9
View File
@@ -105,7 +105,8 @@ static void resp_free(Resp* r) {
}
/* Faz um pedido (sem seguir redirecionamento); NULL em erro (err) */
static Resp* request_once(const Net* net, const Url* u, const char* method, const char* body, char* err, size_t cap) {
static Resp* request_once(const Net* net, const Url* u, const char* method, const char* body, const char* extra,
char* err, size_t cap) {
if (u->https && !net->ssl) { snprintf(err, cap, "https:// precisa da library tinyblocks-ssl carregada"); return NULL; }
TbStream* s = net->sock->tcp_connect(u->host, u->port, 30000, err, cap);
if (!s) return NULL;
@@ -117,6 +118,7 @@ static Resp* request_once(const Net* net, const Url* u, const char* method, cons
"%s %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: TinyBlocks/1.0\r\nAccept: */*\r\n"
"Accept-Encoding: identity\r\nConnection: close\r\n", method, u->path, u->host);
if (body) n += snprintf(head + n, sizeof(head) - (size_t)n, "Content-Type: %s\r\nContent-Length: %zu\r\n", ctype, blen);
if (extra) n += snprintf(head + n, sizeof(head) - (size_t)n, "%s", extra);
n += snprintf(head + n, sizeof(head) - (size_t)n, "\r\n");
if (!net->sock->write_all(s, head, (size_t)n) || (body && !net->sock->write_all(s, body, blen))) {
snprintf(err, cap, "falha ao enviar o pedido: %s", s->err);
@@ -184,13 +186,14 @@ static long body_read(Resp* r, char* out, size_t cap) {
}
/* Pedido seguindo redirecionamentos */
static Resp* request(const Net* net, const char* url, const char* method, const char* body, char* err, size_t cap) {
static Resp* request(const Net* net, const char* url, const char* method, const char* body, const char* extra,
char* err, size_t cap) {
char cur[4400];
snprintf(cur, sizeof(cur), "%s", url);
for (int hop = 0; hop < 8; hop++) {
Url u;
if (!url_parse(cur, &u, err, cap)) return NULL;
Resp* r = request_once(net, &u, method, body, err, cap);
Resp* r = request_once(net, &u, method, body, extra, err, cap);
if (!r) return NULL;
bool redir = (r->status == 301 || r->status == 302 || r->status == 303 || r->status == 307 || r->status == 308) && r->location[0];
if (!redir) return r;
@@ -208,7 +211,7 @@ static Resp* request(const Net* net, const char* url, const char* method, const
static int s_last_status;
static char* fetch_text(const Net* net, const char* url, const char* method, const char* body, char* err, size_t cap) {
Resp* r = request(net, url, method, body, err, cap);
Resp* r = request(net, url, method, body, NULL, err, cap);
if (!r) return NULL;
s_last_status = r->status;
size_t n = 0, bcap = 65536;
@@ -255,22 +258,37 @@ static void mkdirs_for(const char* path) {
}
}
/* Baixa para <arquivo>.parte e renomeia no fim. Um .parte que ja existe
(download interrompido) continua de onde parou: "Range: bytes=N-" e o
servidor responde 206; se ele ignorar (200), recomeca do zero. */
static void* dl_thread(void* arg) {
Dl* d = arg;
char err[256] = "";
char part[1100];
snprintf(part, sizeof(part), "%s.parte", d->path);
Resp* r = request(&d->net, d->url, "GET", NULL, err, sizeof(err));
struct stat st;
long long have = stat(part, &st) == 0 ? (long long)st.st_size : 0;
char range[64] = "";
if (have > 0) snprintf(range, sizeof(range), "Range: bytes=%lld-\r\n", have);
Resp* r = request(&d->net, d->url, "GET", NULL, have > 0 ? range : NULL, err, sizeof(err));
if (r && r->status == 416) { /* o .parte nao serve: do zero */
resp_free(r);
remove(part);
have = 0;
r = request(&d->net, d->url, "GET", NULL, NULL, err, sizeof(err));
}
FILE* f = NULL;
bool resume = r && r->status == 206 && have > 0;
if (r && (r->status < 200 || r->status >= 300)) { snprintf(err, sizeof(err), "o servidor respondeu %d", r->status); }
else if (r) {
mkdirs_for(d->path);
f = fopen(part, "wb");
f = fopen(part, resume ? "ab" : "wb");
if (!f) snprintf(err, sizeof(err), "não abriu '%.200s' para gravar", part);
}
if (r && f) {
pthread_mutex_lock(&s_mu);
d->total = r->length;
d->got = resume ? have : 0;
d->total = r->length < 0 ? -1 : r->length + (resume ? have : 0);
pthread_mutex_unlock(&s_mu);
char* buf = malloc(1 << 16);
while (buf && !s_quit) {
@@ -283,12 +301,11 @@ static void* dl_thread(void* arg) {
pthread_mutex_unlock(&s_mu);
}
free(buf);
if (s_quit && !err[0]) snprintf(err, sizeof(err), "interrompido");
if (s_quit && !err[0]) snprintf(err, sizeof(err), "interrompido (o .parte fica: baixar de novo continua)");
}
if (f) {
if (fclose(f) != 0 && !err[0]) snprintf(err, sizeof(err), "falha ao gravar '%.200s'", part);
if (!err[0] && rename(part, d->path) != 0) snprintf(err, sizeof(err), "não renomeou para '%.200s'", d->path);
if (err[0]) remove(part);
}
resp_free(r);
pthread_mutex_lock(&s_mu);
+32 -2
View File
@@ -24,10 +24,12 @@ static int fails = 0;
/* -- servidor local ------------------------------------------------------- */
static int s_port;
static int s_range_from = -1; /* o servidor recebeu "Range: bytes=N-" */
static const char* BIG = "0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ0123456789ABCDEFGHIJ";
static void* server(void* arg) {
int ls = *(int*)arg;
for (int k = 0; k < 6; k++) {
for (int k = 0; k < 7; k++) {
int c = accept(ls, NULL, NULL);
if (c < 0) break;
char req[2048] = "";
@@ -45,7 +47,16 @@ static void* server(void* arg) {
}
const char* resp;
char buf[512];
if (strstr(req, "GET /chunk ")) resp = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nola, \r\n6\r\nmundo!\r\n0\r\n\r\n";
if (strstr(req, "GET /grande ")) {
const char* rg = strstr(req, "Range: bytes=");
int from = rg ? atoi(rg + 13) : 0;
if (rg) s_range_from = from;
size_t len = strlen(BIG) - (size_t)from;
snprintf(buf, sizeof(buf), rg ? "HTTP/1.1 206 Partial Content\r\nContent-Length: %zu\r\n\r\n%s"
: "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", len, BIG + from);
resp = buf;
}
else if (strstr(req, "GET /chunk ")) resp = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nola, \r\n6\r\nmundo!\r\n0\r\n\r\n";
else if (strstr(req, "GET /redir ")) resp = "HTTP/1.1 302 Found\r\nLocation: /len\r\nContent-Length: 0\r\n\r\n";
else if (strstr(req, "GET /len ")) resp = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\ncom tamanho!";
else if (strstr(req, "POST /eco ")) {
@@ -130,6 +141,25 @@ int main(void) {
char txt[64];
tb_value_to_text(con->outputs[0], txt, sizeof(txt));
CHECK(!strcmp(txt, "conexão tcp aberta"), "a conexão aparece como \"conexão tcp aberta\"");
/* download que continua: o .parte tem os 40 primeiros bytes */
{
FILE* pf = fopen("/tmp/tb_http_resume.bin.parte", "wb");
fwrite(BIG, 1, 40, pf); fclose(pf);
remove("/tmp/tb_http_resume.bin");
snprintf(url, sizeof(url), "http://127.0.0.1:%d/grande", s_port);
TinyBlocks_Block* dl = blk(rt, "Http.Download", url, "/tmp/tb_http_resume.bin");
tb_block_eval(dl, rt);
TinyBlocks_Block* dn = blk(rt, "Http.Done", "/tmp/tb_http_resume.bin", NULL);
for (int w = 0; w < 100; w++) {
dn->dirty = true; tb_block_eval(dn, rt);
if (dn->outputs[0].as.integer) break;
struct timespec ts = { 0, 20000000 }; nanosleep(&ts, NULL);
}
char got[256] = "";
FILE* f = fopen("/tmp/tb_http_resume.bin", "rb");
if (f) { size_t k = fread(got, 1, sizeof(got) - 1, f); got[k] = 0; fclose(f); }
CHECK(s_range_from == 40 && !strcmp(got, BIG), "download interrompido continua (Range: bytes=40-, 206)");
}
pthread_join(th, NULL);
/* com internet */