/* * TinyBlocks - tb_http.c * Cliente HTTP/1.1 sobre TbStream (tcp da tinyblocks-socket, tls da * tinyblocks-ssl) e os blocos da categoria "HTTP". */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include "tb_socket.h" #include "tb_ssl.h" #include "tb_http.h" /* As camadas de baixo, achadas no runtime antes de cada pedido */ typedef struct { const TbSocketApi* sock; const TbSslApi* ssl; } Net; static bool net_of(TinyBlocks* rt, Net* n) { n->sock = tb_socket_api(rt); n->ssl = tb_ssl_api(rt); if (!n->sock) tinyblocks_set_error(rt, "o HTTP precisa da library tinyblocks-socket carregada"); return n->sock != NULL; } /* == URL ============================================================== */ typedef struct { bool https; char host[256]; int port; char path[2048]; } Url; static bool url_parse(const char* s, Url* u, char* err, size_t cap) { memset(u, 0, sizeof(*u)); if (!strncasecmp(s, "https://", 8)) { u->https = true; s += 8; u->port = 443; } else if (!strncasecmp(s, "http://", 7)) { s += 7; u->port = 80; } else { snprintf(err, cap, "endereço sem http:// ou https://: %.200s", s); return false; } size_t h = strcspn(s, ":/?#"); if (!h || h >= sizeof(u->host)) { snprintf(err, cap, "endereço sem nome de computador"); return false; } memcpy(u->host, s, h); s += h; if (*s == ':') { u->port = atoi(s + 1); s += 1 + strspn(s + 1, "0123456789"); } snprintf(u->path, sizeof(u->path), "%s", *s == '/' ? s : "/"); if (*s == '?') snprintf(u->path, sizeof(u->path), "/%s", s); char* hash = strchr(u->path, '#'); if (hash) *hash = 0; return true; } /* Location relativa vira absoluta */ static void url_join(const Url* base, const char* loc, char* out, size_t cap) { if (!strncasecmp(loc, "http://", 7) || !strncasecmp(loc, "https://", 8)) snprintf(out, cap, "%s", loc); else if (loc[0] == '/' && loc[1] == '/') snprintf(out, cap, "%s:%s", base->https ? "https" : "http", loc); else if (loc[0] == '/') snprintf(out, cap, "%s://%s:%d%s", base->https ? "https" : "http", base->host, base->port, loc); else { char dir[sizeof(base->path)]; snprintf(dir, sizeof(dir), "%s", base->path); char* sl = strrchr(dir, '/'); if (sl) sl[1] = 0; snprintf(out, cap, "%s://%s:%d%s%s", base->https ? "https" : "http", base->host, base->port, dir, loc); } } /* == Resposta ========================================================= */ typedef struct { TbStream* s; int status; long long length; /* -1 = desconhecido */ bool chunked; char location[2048]; /* leitura do corpo */ char buf[65536]; size_t pos, len; long long chunk_left; /* chunked: bytes que faltam do pedaco */ long long body_left; /* Content-Length: bytes que faltam */ bool eof; char err[256]; } Resp; static bool fill(Resp* r) { if (r->pos < r->len) return true; long n = tb_stream_read(r->s, r->buf, sizeof(r->buf)); if (n < 0) { snprintf(r->err, sizeof(r->err), "%s", r->s->err); return false; } r->pos = 0; r->len = (size_t)n; return n > 0; } static bool read_line(Resp* r, char* out, size_t cap) { size_t n = 0; for (;;) { if (!fill(r)) return false; char c = r->buf[r->pos++]; if (c == '\n') break; if (c != '\r' && n + 1 < cap) out[n++] = c; } out[n] = 0; return true; } static void resp_free(Resp* r) { if (!r) return; tb_stream_close(r->s); free(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, 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; if (u->https && !(s = net->ssl->wrap(s, u->host, err, cap))) return NULL; char head[4096]; size_t blen = body ? strlen(body) : 0; const char* ctype = body && (body[0] == '{' || body[0] == '[') ? "application/json" : "text/plain; charset=utf-8"; int n = snprintf(head, sizeof(head), "%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); tb_stream_close(s); return NULL; } Resp* r = calloc(1, sizeof(Resp)); if (!r) { tb_stream_close(s); snprintf(err, cap, "sem memória"); return NULL; } r->s = s; r->length = -1; char line[4096]; if (!read_line(r, line, sizeof(line)) || sscanf(line, "HTTP/%*d.%*d %d", &r->status) != 1) { snprintf(err, cap, "resposta inválida de %.100s%s%.120s", u->host, r->err[0] ? ": " : "", r->err); resp_free(r); return NULL; } while (read_line(r, line, sizeof(line)) && line[0]) { char* colon = strchr(line, ':'); if (!colon) continue; *colon = 0; char* v = colon + 1; while (*v == ' ' || *v == '\t') v++; if (!strcasecmp(line, "content-length")) r->length = atoll(v); else if (!strcasecmp(line, "transfer-encoding") && strstr(v, "chunked")) r->chunked = true; else if (!strcasecmp(line, "location")) snprintf(r->location, sizeof(r->location), "%s", v); } r->body_left = r->chunked ? -1 : r->length; r->chunk_left = 0; if (!strcmp(method, "HEAD") || r->status == 204 || r->status == 304) r->eof = true; return r; } /* Le do corpo (cuida do chunked); 0 = acabou, -1 = erro (r->err) */ static long body_read(Resp* r, char* out, size_t cap) { if (r->eof) return 0; if (r->chunked) { if (r->chunk_left == 0) { char line[128]; if (!read_line(r, line, sizeof(line))) { if (!r->err[0]) snprintf(r->err, sizeof(r->err), "conexão fechou no meio do chunked"); return -1; } if (!line[0] && !read_line(r, line, sizeof(line))) return -1; /* CRLF depois do pedaco anterior */ r->chunk_left = strtoll(line, NULL, 16); if (r->chunk_left == 0) { r->eof = true; return 0; } } if (!fill(r)) { if (!r->err[0]) snprintf(r->err, sizeof(r->err), "conexão fechou no meio do chunked"); return -1; } size_t n = r->len - r->pos; if ((long long)n > r->chunk_left) n = (size_t)r->chunk_left; if (n > cap) n = cap; memcpy(out, r->buf + r->pos, n); r->pos += n; r->chunk_left -= (long long)n; return (long)n; } if (r->body_left == 0) { r->eof = true; return 0; } if (!fill(r)) { if (r->err[0]) return -1; if (r->body_left > 0) { snprintf(r->err, sizeof(r->err), "a conexão fechou faltando %lld bytes", r->body_left); return -1; } r->eof = true; return 0; /* sem Content-Length: ate fechar */ } size_t n = r->len - r->pos; if (r->body_left > 0 && (long long)n > r->body_left) n = (size_t)r->body_left; if (n > cap) n = cap; memcpy(out, r->buf + r->pos, n); r->pos += n; if (r->body_left > 0) r->body_left -= (long long)n; return (long)n; } /* Pedido seguindo redirecionamentos */ 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, 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; char next[4400]; url_join(&u, r->location, next, sizeof(next)); snprintf(cur, sizeof(cur), "%s", next); if (r->status == 303) { method = "GET"; body = NULL; } resp_free(r); } snprintf(err, cap, "redirecionamentos demais"); return NULL; } /* == Pedidos de uma vez (texto) ======================================= */ 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, NULL, err, cap); if (!r) return NULL; s_last_status = r->status; size_t n = 0, bcap = 65536; char* out = malloc(bcap); while (out) { if (n + 65536 > bcap) { if (bcap >= (size_t)16 << 20) { snprintf(err, cap, "resposta maior que 16 MB (use \"baixe\")"); free(out); out = NULL; break; } char* p = realloc(out, bcap * 2); if (!p) { free(out); out = NULL; break; } out = p; bcap *= 2; } long k = body_read(r, out + n, bcap - n - 1); if (k < 0) { snprintf(err, cap, "%s", r->err); free(out); out = NULL; break; } if (k == 0) { out[n] = 0; break; } n += (size_t)k; } resp_free(r); return out; } /* == Downloads assincronos ============================================ */ typedef struct Dl { char url[2048]; char path[1024]; Net net; long long got, total; /* total -1 = desconhecido */ bool done; char err[256]; pthread_t th; bool joined; struct Dl* next; } Dl; static pthread_mutex_t s_mu = PTHREAD_MUTEX_INITIALIZER; static Dl* s_dls; static volatile bool s_quit; static void mkdirs_for(const char* path) { char buf[1024]; snprintf(buf, sizeof(buf), "%s", path); for (char* p = buf + 1; *p; p++) { if (*p != '/') continue; *p = 0; mkdir(buf, 0755); *p = '/'; } } /* Baixa para .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); 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, 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->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) { long k = body_read(r, buf, 1 << 16); if (k < 0) { snprintf(err, sizeof(err), "%s", r->err); break; } if (k == 0) break; if (fwrite(buf, 1, (size_t)k, f) != (size_t)k) { snprintf(err, sizeof(err), "disco cheio? (%s)", strerror(errno)); break; } pthread_mutex_lock(&s_mu); d->got += k; pthread_mutex_unlock(&s_mu); } free(buf); 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); } resp_free(r); pthread_mutex_lock(&s_mu); snprintf(d->err, sizeof(d->err), "%s", err); d->done = true; pthread_mutex_unlock(&s_mu); return NULL; } static Dl* dl_find(const char* path) { for (Dl* d = s_dls; d; d = d->next) if (!strcmp(d->path, path)) return d; return NULL; } /* == Blocos =========================================================== */ static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; Net net; if (!net_of(rt, &net)) return; char err[256] = ""; char* t = fetch_text(&net, tb_block_input_text(self, rt, 0), "GET", NULL, err, sizeof(err)); if (!t) { tinyblocks_set_error(rt, "%s", err); return; } tb_block_set_output(self, 0, tb_value_text(t)); free(t); } static void eval_post(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; Net net; if (!net_of(rt, &net)) return; char err[256] = ""; char* t = fetch_text(&net, tb_block_input_text(self, rt, 0), "POST", tb_block_input_text(self, rt, 1), err, sizeof(err)); if (!t) { tinyblocks_set_error(rt, "%s", err); return; } tb_block_set_output(self, 0, tb_value_text(t)); free(t); } static void eval_status(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; tb_block_set_output(self, 0, tb_value_integer(s_last_status)); self->dirty = false; } static void eval_download(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; Net net; if (!net_of(rt, &net)) return; const char* url = tb_block_input_text(self, rt, 0); const char* path = tb_block_input_text(self, rt, 1); if (!path[0]) { tinyblocks_set_error(rt, "baixe: falta o arquivo de destino"); return; } pthread_mutex_lock(&s_mu); Dl* d = dl_find(path); if (d && !d->done) { /* ja esta baixando */ pthread_mutex_unlock(&s_mu); tinyblocks_set_error(rt, "'%s' já está sendo baixado", path); return; } if (d) { /* de novo: reaproveita a entrada */ if (!d->joined) { pthread_join(d->th, NULL); d->joined = true; } } else { d = calloc(1, sizeof(Dl)); if (!d) { pthread_mutex_unlock(&s_mu); return; } d->next = s_dls; s_dls = d; } snprintf(d->url, sizeof(d->url), "%s", url); snprintf(d->path, sizeof(d->path), "%s", path); d->net = net; d->got = 0; d->total = -1; d->done = false; d->err[0] = 0; d->joined = false; s_quit = false; if (pthread_create(&d->th, NULL, dl_thread, d) != 0) { d->done = true; d->joined = true; snprintf(d->err, sizeof(d->err), "não criou a thread do download"); } pthread_mutex_unlock(&s_mu); } static void eval_progress(TinyBlocks_Block* self, TinyBlocks* rt) { pthread_mutex_lock(&s_mu); Dl* d = dl_find(tb_block_input_text(self, rt, 0)); double p = !d ? 0 : d->done && !d->err[0] ? 1 : d->total > 0 ? (double)d->got / (double)d->total : 0; pthread_mutex_unlock(&s_mu); tb_block_set_output(self, 0, tb_value_real(p)); self->dirty = false; } static void eval_bytes(TinyBlocks_Block* self, TinyBlocks* rt) { pthread_mutex_lock(&s_mu); Dl* d = dl_find(tb_block_input_text(self, rt, 0)); long long got = d ? d->got : 0; pthread_mutex_unlock(&s_mu); tb_block_set_output(self, 0, tb_value_integer(got)); self->dirty = false; } static void eval_done(TinyBlocks_Block* self, TinyBlocks* rt) { pthread_mutex_lock(&s_mu); Dl* d = dl_find(tb_block_input_text(self, rt, 0)); bool done = !d || d->done; /* nenhum download = nada a esperar */ pthread_mutex_unlock(&s_mu); tb_block_set_output(self, 0, tb_value_integer(done)); self->dirty = false; } static void eval_error(TinyBlocks_Block* self, TinyBlocks* rt) { char e[256] = ""; pthread_mutex_lock(&s_mu); Dl* d = dl_find(tb_block_input_text(self, rt, 0)); if (d && d->done) snprintf(e, sizeof(e), "%s", d->err); pthread_mutex_unlock(&s_mu); tb_block_set_output(self, 0, tb_value_text(e)); self->dirty = false; } /* == Registro ========================================================= */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, const char* label, const char* defs, const TinyBlocks_SlotDesc* in, uint32_t ni, const TinyBlocks_SlotDesc* out, uint32_t no, void (*fn)(TinyBlocks_Block*, TinyBlocks*), const char* fname, const char* doc) { TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); if (!t) return false; tb_type_block_set_label(t, label, defs); tb_meta_declare(name, fname, __FILE__, doc); return tb_library_add(lib, &t->base); } static bool http_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "HTTP", {0.20f, 0.55f, 0.85f, 1.f}, {0.13f, 0.42f, 0.68f, 1.f} }; tb_library_set_category(lib, &cat); static const TinyBlocks_SlotDesc url[] = {{"endereço", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc url_body[] = {{"endereço", TB_VALUE_TEXT}, {"corpo", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc url_path[] = {{"endereço", TB_VALUE_TEXT}, {"arquivo", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc path[] = {{"arquivo", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc out_txt[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc out_num[] = {{"valor", TB_VALUE_NONE}}; static const TinyBlocks_SlotDesc out_bool[] = {{"terminou?", TB_VALUE_INTEGER}}; return reg(rt, lib, "Http.Get", "conteúdo de %1", "https://example.com", url, 1, out_txt, 1, eval_get, "eval_get", "Busca o texto do endereço (GET; até 16 MB)") && reg(rt, lib, "Http.Post", "resposta de POST para %1 com %2", "https://example.com|{}", url_body, 2, out_txt, 1, eval_post, "eval_post", "Envia o corpo (JSON se começar com { ou [) e devolve a resposta") && reg(rt, lib, "Http.Status", "código da última resposta", NULL, NULL, 0, out_num, 1, eval_status, "eval_status", "Status HTTP do último conteúdo/POST (200, 404...)") && reg(rt, lib, "Http.Download", "baixe %1 para %2", "https://example.com|pagina.html", url_path, 2, NULL, 0, eval_download, "eval_download", "Começa a baixar o endereço para o arquivo (em segundo plano)") && reg(rt, lib, "Http.Done", "download de %1 terminou?", "pagina.html", path, 1, out_bool, 1, eval_done, "eval_done", "Verdadeiro quando o download do arquivo acabou (bem ou mal)") && reg(rt, lib, "Http.Progress", "progresso do download de %1", "pagina.html", path, 1, out_num, 1, eval_progress, "eval_progress", "0 a 1 (0 enquanto o tamanho for desconhecido)") && reg(rt, lib, "Http.Bytes", "bytes baixados de %1", "pagina.html", path, 1, out_num, 1, eval_bytes, "eval_bytes", "Quantos bytes já chegaram") && reg(rt, lib, "Http.Error", "erro do download de %1", "pagina.html", path, 1, out_txt, 1, eval_error, "eval_error", "Mensagem do erro (vazio = deu certo)"); } static void http_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; s_quit = true; /* downloads param no proximo pedaco */ pthread_mutex_lock(&s_mu); Dl* d = s_dls; s_dls = NULL; pthread_mutex_unlock(&s_mu); while (d) { Dl* n = d->next; if (!d->joined) pthread_join(d->th, NULL); free(d); d = n; } } TINYBLOCKS_DEFINE_LIBRARY(http, "tinyblocks-http", "1.0.0", http_init, http_deinit) const TinyBlocks_LibraryDescriptor* tb_http_get_library(void) { return &_tb_lib_desc_http; }