Files
tinyblocks/tests/http_test.c
T
mguinhosandClaude Opus 5.5 066bb295ed tinyblocks-socket, -ssl, -http e -archive: internet e arquivos compactados em blocos
socket: conexao TCP como TbStream (fluxo com classe read/write/close) e
blocos para conectar, enviar, receber e resolver endereco.
ssl: embrulha um TbStream TCP em TLS (OpenSSL), com SNI e certificado
conferido pelo sistema e pelo nome do host.
http: cliente HTTP/1.1 so sobre TbStream; https:// quando a ssl esta
carregada; Content-Length, chunked e redirecionamentos; GET e POST de
texto e download em segundo plano (.parte ate terminar) com progresso.
archive: lista e extrai .tar e .tar.gz (zlib), nomes longos GNU/pax;
recusa entradas com "../" ou caminho absoluto.

As camadas se acham pelas tabelas no lib_userdata, sem linkar umas com as
outras. test-http usa um servidor local (e a internet, se houver);
test-archive cria os arquivos com tar e Python.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 23:27:08 -03:00

171 lines
7.6 KiB
C

/*
* http_test.c - testa tinyblocks-socket, -ssl e -http pelos blocos.
* Um servidor local (thread) responde com Content-Length, chunked e
* redirecionamento; com internet, tambem um GET https e um download.
*/
#define _POSIX_C_SOURCE 200809L
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include <tinyblocks/tinyblocks.h>
#include <tb_socket.h>
#include <tb_ssl.h>
#include <tb_http.h>
static int fails = 0;
#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0)
/* -- servidor local ------------------------------------------------------- */
static int s_port;
static void* server(void* arg) {
int ls = *(int*)arg;
for (int k = 0; k < 6; k++) {
int c = accept(ls, NULL, NULL);
if (c < 0) break;
char req[2048] = "";
size_t got = 0;
for (;;) { /* cabecalho inteiro + corpo (Content-Length) */
ssize_t n = recv(c, req + got, sizeof(req) - 1 - got, 0);
if (n <= 0) break;
got += (size_t)n; req[got] = 0;
if (strstr(req, "linha")) break; /* o teste do socket manda so uma linha */
char* end = strstr(req, "\r\n\r\n");
if (!end) continue;
const char* cl = strstr(req, "Content-Length: ");
size_t want = cl ? (size_t)atoi(cl + 16) : 0;
if (got - (size_t)(end + 4 - req) >= want) break;
}
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";
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 ")) {
const char* body = strstr(req, "\r\n\r\n");
snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\nContent-Length: %zu\r\n\r\n%s", body ? strlen(body + 4) : 0, body ? body + 4 : "");
resp = buf;
}
else if (strstr(req, "linha")) resp = "pong do servidor\r\nresto";
else resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 3\r\n\r\nnao";
send(c, resp, strlen(resp), 0);
close(c);
}
close(ls);
return NULL;
}
static TinyBlocks_Block* blk(TinyBlocks* rt, const char* type, const char* a, const char* b) {
TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type));
if (a) { TinyBlocks_Value v = tb_value_text(a); tb_block_set_default(x, 0, v); tb_value_free(&v); }
if (b) { TinyBlocks_Value v = tb_value_text(b); tb_block_set_default(x, 1, v); tb_value_free(&v); }
return x;
}
static const char* text_of(TinyBlocks* rt, TinyBlocks_Block* b) {
b->dirty = true;
tb_block_eval(b, rt);
return b->outputs[0].kind == TB_VALUE_TEXT ? b->outputs[0].as.text : "";
}
int main(void) {
setvbuf(stdout, NULL, _IOLBF, 0);
int ls = socket(AF_INET, SOCK_STREAM, 0);
int one = 1;
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
bind(ls, (struct sockaddr*)&a, sizeof(a));
socklen_t al = sizeof(a);
getsockname(ls, (struct sockaddr*)&a, &al);
s_port = ntohs(a.sin_port);
listen(ls, 8);
pthread_t th;
pthread_create(&th, NULL, server, &ls);
TinyBlocks* rt = NULL;
tinyblocks_init(&rt, NULL);
tb_library_register(rt, tb_socket_get_library());
tb_library_register(rt, tb_ssl_get_library());
tb_library_register(rt, tb_http_get_library());
CHECK(tb_socket_api(rt) && tb_ssl_api(rt), "socket e ssl publicam as tabelas");
char url[128];
snprintf(url, sizeof(url), "http://127.0.0.1:%d/len", s_port);
TinyBlocks_Block* get = blk(rt, "Http.Get", url, NULL);
CHECK(!strcmp(text_of(rt, get), "com tamanho!"), "GET com Content-Length");
snprintf(url, sizeof(url), "http://127.0.0.1:%d/chunk", s_port);
get = blk(rt, "Http.Get", url, NULL);
CHECK(!strcmp(text_of(rt, get), "ola, mundo!"), "GET com chunked");
snprintf(url, sizeof(url), "http://127.0.0.1:%d/redir", s_port);
get = blk(rt, "Http.Get", url, NULL);
CHECK(!strcmp(text_of(rt, get), "com tamanho!"), "segue o redirecionamento (Location relativa)");
snprintf(url, sizeof(url), "http://127.0.0.1:%d/eco", s_port);
TinyBlocks_Block* post = blk(rt, "Http.Post", url, "{\"a\": 1}");
CHECK(!strcmp(text_of(rt, post), "{\"a\": 1}"), "POST manda o corpo");
TinyBlocks_Block* st = blk(rt, "Http.Status", NULL, NULL);
tb_block_eval(st, rt);
CHECK(st->outputs[0].as.integer == 200, "código da última resposta = 200");
/* blocos de socket: conectar, enviar, receber uma linha */
char port[16];
snprintf(port, sizeof(port), "%d", s_port);
TinyBlocks_Block* con = blk(rt, "Socket.Connect", "127.0.0.1", NULL);
tb_block_set_default(con, 1, tb_value_integer(s_port));
tb_block_eval(con, rt);
TinyBlocks_Block* snd = blk(rt, "Socket.Send", "linha\r\n", NULL);
tb_block_connect(snd, 1, con, 0);
con->dirty = false;
tb_block_eval(snd, rt);
TinyBlocks_Block* rl = blk(rt, "Socket.RecvLine", NULL, NULL);
tb_block_connect(rl, 0, con, 0);
rl->dirty = true; tb_block_eval(rl, rt);
CHECK(!strcmp(rl->outputs[0].as.text, "pong do servidor"), "socket: envia e recebe uma linha");
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\"");
pthread_join(th, NULL);
/* com internet */
TinyBlocks_Block* web = blk(rt, "Http.Get", "https://example.com/", NULL);
const char* page = text_of(rt, web);
if (tinyblocks_last_error(rt)[0] && strstr(tinyblocks_last_error(rt), "endereço")) {
printf("pulado: sem internet (%s)\n", tinyblocks_last_error(rt));
tinyblocks_clear_error(rt);
} else {
CHECK(strstr(page, "Example Domain") != NULL, "GET https://example.com (TLS com certificado conferido)");
tinyblocks_clear_error(rt);
TinyBlocks_Block* bad = blk(rt, "Http.Get", "https://expired.badssl.com/", NULL);
text_of(rt, bad);
CHECK(strstr(tinyblocks_last_error(rt), "certificado") != NULL, "certificado vencido é recusado");
tinyblocks_clear_error(rt);
remove("/tmp/tb_http_test.html");
TinyBlocks_Block* dl = blk(rt, "Http.Download", "http://example.com/", "/tmp/tb_http_test.html");
tb_block_eval(dl, rt);
TinyBlocks_Block* done = blk(rt, "Http.Done", "/tmp/tb_http_test.html", NULL);
int waited = 0;
for (; waited < 200; waited++) {
done->dirty = true; tb_block_eval(done, rt);
if (done->outputs[0].as.integer) break;
struct timespec ts = { 0, 50000000 }; nanosleep(&ts, NULL);
}
TinyBlocks_Block* er = blk(rt, "Http.Error", "/tmp/tb_http_test.html", NULL);
const char* e = text_of(rt, er);
FILE* f = fopen("/tmp/tb_http_test.html", "r");
char head[64] = "";
if (f) { size_t k = fread(head, 1, sizeof(head) - 1, f); head[k] = 0; fclose(f); }
printf(" download: %s\n", e[0] ? e : "sem erro");
CHECK(!e[0] && strstr(head, "<!doctype") != NULL, "download em segundo plano termina e grava o arquivo");
}
tinyblocks_deinit(&rt);
if (fails) printf("\n%d FALHA(S)\n", fails);
else printf("\nTUDO OK\n");
return fails != 0;
}