From 066bb295ed5580123f6056137c9c86b4105cfd16 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Fri, 23 Oct 2026 23:27:08 -0300 Subject: [PATCH] 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 --- Makefile | 26 +- examples/editor/main.c | 8 + libraries/tinyblocks-archive/Makefile | 30 ++ .../tinyblocks-archive/include/tb_archive.h | 27 + libraries/tinyblocks-archive/library.toml | 15 + libraries/tinyblocks-archive/src/tb_archive.c | 209 ++++++++ libraries/tinyblocks-http/Makefile | 30 ++ libraries/tinyblocks-http/include/tb_http.h | 25 + libraries/tinyblocks-http/library.toml | 15 + libraries/tinyblocks-http/src/tb_http.c | 462 ++++++++++++++++++ libraries/tinyblocks-socket/Makefile | 30 ++ .../tinyblocks-socket/include/tb_socket.h | 65 +++ libraries/tinyblocks-socket/library.toml | 15 + libraries/tinyblocks-socket/src/tb_socket.c | 287 +++++++++++ libraries/tinyblocks-ssl/Makefile | 30 ++ libraries/tinyblocks-ssl/include/tb_ssl.h | 41 ++ libraries/tinyblocks-ssl/library.toml | 15 + libraries/tinyblocks-ssl/src/tb_ssl.c | 121 +++++ tests/archive_test.c | 71 +++ tests/http_test.c | 170 +++++++ 20 files changed, 1689 insertions(+), 3 deletions(-) create mode 100644 libraries/tinyblocks-archive/Makefile create mode 100644 libraries/tinyblocks-archive/include/tb_archive.h create mode 100644 libraries/tinyblocks-archive/library.toml create mode 100644 libraries/tinyblocks-archive/src/tb_archive.c create mode 100644 libraries/tinyblocks-http/Makefile create mode 100644 libraries/tinyblocks-http/include/tb_http.h create mode 100644 libraries/tinyblocks-http/library.toml create mode 100644 libraries/tinyblocks-http/src/tb_http.c create mode 100644 libraries/tinyblocks-socket/Makefile create mode 100644 libraries/tinyblocks-socket/include/tb_socket.h create mode 100644 libraries/tinyblocks-socket/library.toml create mode 100644 libraries/tinyblocks-socket/src/tb_socket.c create mode 100644 libraries/tinyblocks-ssl/Makefile create mode 100644 libraries/tinyblocks-ssl/include/tb_ssl.h create mode 100644 libraries/tinyblocks-ssl/library.toml create mode 100644 libraries/tinyblocks-ssl/src/tb_ssl.c create mode 100644 tests/archive_test.c create mode 100644 tests/http_test.c diff --git a/Makefile b/Makefile index d7ba24b..a9737b8 100644 --- a/Makefile +++ b/Makefile @@ -86,10 +86,10 @@ CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l)) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) # Libraries que o editor registra como as de categoria, mas com varios # fontes e o Makefile proprio (o harness nao as compila junto) -APP_LIBS := tensor ai +APP_LIBS := socket ssl http archive tensor ai APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) -APP_LDLIBS := -lpthread +APP_LDLIBS := -lssl -lcrypto -lz -lpthread ED_A := $(ED_DIR)/build/libtinyblocks-editor.a GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a @@ -111,7 +111,7 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ test-toml test-plugin test-blueprint test-a11y test-mcp test-mcp-server test-base64 test-curves test-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ - test-tensor test-ai test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ + test-tensor test-ai test-http test-archive test-syntax test-os test-value test-vars test-scratchblocks test-input test-stdlib test-regex test-markdown test-opentype \ category-libs category-sos libs app-libs \ lib-events lib-control lib-errors lib-input lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ lib-environ \ @@ -628,6 +628,26 @@ $(BUILD)/ai_test: tests/ai_test.c $(AI_SRCS) $(AI_DIR)/src/ai_blocks.c $(AI_DIR) test-ai: $(BUILD)/ai_test ## Roda o teste da ai (ASan/UBSan) ./$(BUILD)/ai_test +# -- Teste de socket + ssl + http (servidor local; internet se houver) --- +NET_SRCS := $(LIBDIR)/tinyblocks-socket/src/tb_socket.c $(LIBDIR)/tinyblocks-ssl/src/tb_ssl.c $(LIBDIR)/tinyblocks-http/src/tb_http.c +NET_INCS := -I$(LIBDIR)/tinyblocks-socket/include -I$(LIBDIR)/tinyblocks-ssl/include -I$(LIBDIR)/tinyblocks-http/include +$(BUILD)/http_test: tests/http_test.c $(NET_SRCS) static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) $(NET_INCS) $(NET_SRCS) tests/http_test.c -o $@ \ + -Wl,--start-group $(LIB_A) -Wl,--end-group -lssl -lcrypto -lpthread -lm + +test-http: $(BUILD)/http_test ## Roda o teste de socket/ssl/http (ASan/UBSan) + ./$(BUILD)/http_test + +# -- Teste da library archive (.tar / .tar.gz) --- +$(BUILD)/archive_test: tests/archive_test.c $(LIBDIR)/tinyblocks-archive/src/tb_archive.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(LIBDIR)/tinyblocks-archive/include $(LIBDIR)/tinyblocks-archive/src/tb_archive.c \ + tests/archive_test.c -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group -lz -lm + +test-archive: $(BUILD)/archive_test ## Roda o teste da archive (ASan/UBSan) + ./$(BUILD)/archive_test + # -- Teste da library curves --- $(BUILD)/curves_test: tests/curves_test.c $(CV_DIR)/src/tb_curves.c static @mkdir -p $(BUILD) diff --git a/examples/editor/main.c b/examples/editor/main.c index 481fab4..fa8ad99 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -35,6 +35,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include @@ -80,6 +84,10 @@ int main(int argc, char** argv) { reg_core(rt, "tinyblocks-pen", tb_pen_get_library); reg_core(rt, "tinyblocks-fs", tb_fs_get_library); reg_core(rt, "tinyblocks-os", tb_os_get_library); + reg_core(rt, "tinyblocks-socket", tb_socket_get_library); + reg_core(rt, "tinyblocks-ssl", tb_ssl_get_library); + reg_core(rt, "tinyblocks-http", tb_http_get_library); + reg_core(rt, "tinyblocks-archive", tb_archive_get_library); reg_core(rt, "tinyblocks-tensor", tb_tensor_get_library); reg_core(rt, "tinyblocks-ai", tb_ai_get_library); diff --git a/libraries/tinyblocks-archive/Makefile b/libraries/tinyblocks-archive/Makefile new file mode 100644 index 0000000..dbddef8 --- /dev/null +++ b/libraries/tinyblocks-archive/Makefile @@ -0,0 +1,30 @@ +# Makefile da library archive (categoria "Arquivos compactados") +# Constroi build/libtinyblocks-archive.a e build/libtinyblocks-archive.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +SRCS := src/tb_archive.c +OBJS := $(BUILD)/tb_archive.o +LIB_A := $(BUILD)/libtinyblocks-archive.a +LIB_SO := $(BUILD)/libtinyblocks-archive.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ -lz + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-archive/include/tb_archive.h b/libraries/tinyblocks-archive/include/tb_archive.h new file mode 100644 index 0000000..86bed62 --- /dev/null +++ b/libraries/tinyblocks-archive/include/tb_archive.h @@ -0,0 +1,27 @@ +/* + * TinyBlocks - tb_archive.h + * Library tinyblocks-archive: arquivos .tar e .tar.gz / .tgz (dependencia + * de terceiros: zlib). Registra a categoria "Arquivos compactados". + * + * Extrair recusa caminhos absolutos ou com "..": nada sai da pasta de + * destino. Entende tar ustar, nomes longos do GNU ('L') e o caminho de + * cabecalhos pax ('x'). + */ +#ifndef TINYBLOCKS_ARCHIVE_H +#define TINYBLOCKS_ARCHIVE_H + +#include +#include +#include +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_archive_get_library(void); + +/* -- API C --- */ +/* Extrai tudo para dir (cria as pastas); devolve quantos arquivos ou -1 */ +TB_API int tb_archive_extract(const char* path, const char* dir); +/* Nomes dos arquivos dentro (lista JSON, ref nova) ou NULL */ +TB_API TinyBlocks_JsonValue* tb_archive_list(const char* path); +TB_API const char* tb_archive_last_error(void); + +#endif /* TINYBLOCKS_ARCHIVE_H */ diff --git a/libraries/tinyblocks-archive/library.toml b/libraries/tinyblocks-archive/library.toml new file mode 100644 index 0000000..219b202 --- /dev/null +++ b/libraries/tinyblocks-archive/library.toml @@ -0,0 +1,15 @@ +# Metadados da library archive. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-archive" +version = "1.0.0" +category = "Arquivos compactados" +description = "Arquivos .tar e .tar.gz: listar e extrair (zlib)" +color = [158, 115, 64, 255] +dark = [122, 87, 43, 255] + +[build] +sources = ["src/tb_archive.c"] +includes = ["include"] +shared = "build/libtinyblocks-archive.so" +static = "build/libtinyblocks-archive.a" +depends = [] diff --git a/libraries/tinyblocks-archive/src/tb_archive.c b/libraries/tinyblocks-archive/src/tb_archive.c new file mode 100644 index 0000000..3cfdd28 --- /dev/null +++ b/libraries/tinyblocks-archive/src/tb_archive.c @@ -0,0 +1,209 @@ +/* + * TinyBlocks - tb_archive.c + * Leitura de .tar / .tar.gz pela zlib (gzread le os dois) e os blocos da + * categoria "Arquivos compactados". + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include + +#include "tb_archive.h" + +static char s_err[256]; +const char* tb_archive_last_error(void) { return s_err; } + +static void set_err(const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + vsnprintf(s_err, sizeof(s_err), fmt, ap); + va_end(ap); +} + +static long long octal(const char* p, size_t n) { + long long v = 0; + for (size_t i = 0; i < n && p[i]; i++) { + if (p[i] == ' ') continue; + if (p[i] < '0' || p[i] > '7') break; + v = v * 8 + (p[i] - '0'); + } + return v; +} + +static bool safe_name(const char* n) { + if (!n[0] || n[0] == '/') return false; + for (const char* p = n; *p; ) { + const char* e = strchr(p, '/'); + size_t len = e ? (size_t)(e - p) : strlen(p); + if (len == 2 && p[0] == '.' && p[1] == '.') return false; + if (!e) break; + p = e + 1; + } + return true; +} + +static void mkdirs(const char* path, bool last_too) { + char buf[2048]; + snprintf(buf, sizeof(buf), "%s", path); + for (char* p = buf + 1; *p; p++) + if (*p == '/') { *p = 0; mkdir(buf, 0755); *p = '/'; } + if (last_too) mkdir(buf, 0755); +} + +/* Le exatamente n bytes (false no fim/erro) */ +static bool rd(gzFile f, void* buf, size_t n) { + char* p = buf; + while (n > 0) { + int k = gzread(f, p, n > (1u << 30) ? (1u << 30) : (unsigned)n); + if (k <= 0) return false; + p += k; n -= (size_t)k; + } + return true; +} + +static bool skip(gzFile f, long long n) { + char buf[65536]; + while (n > 0) { + size_t k = n > (long long)sizeof(buf) ? sizeof(buf) : (size_t)n; + if (!rd(f, buf, k)) return false; + n -= (long long)k; + } + return true; +} + +/* Percorre o tar: cada arquivo chama fn(nome, tamanho, f, ud) com o leitor no + comeco dos dados; fn le os dados (ou nao: o que sobrar e pulado). */ +typedef bool (*EntryFn)(const char* name, long long size, char type, gzFile f, long long* consumed, void* ud); + +static int walk(const char* path, EntryFn fn, void* ud) { + gzFile f = gzopen(path, "rb"); + if (!f) { set_err("não abriu '%s'", path); return -1; } + gzbuffer(f, 1 << 17); + char hdr[512], longname[4096] = ""; + int count = 0, zeros = 0; + for (;;) { + if (!rd(f, hdr, 512)) { if (zeros || count) break; set_err("'%s' não é um tar (ou está cortado)", path); gzclose(f); return -1; } + bool all_zero = true; + for (int i = 0; i < 512; i++) if (hdr[i]) { all_zero = false; break; } + if (all_zero) { if (++zeros == 2) break; continue; } + zeros = 0; + if (memcmp(hdr + 257, "ustar", 5) != 0 && count == 0 && hdr[156] != 'L' && hdr[156] != 'x' && hdr[156] != 'g') { + unsigned long sum = 0, want = (unsigned long)octal(hdr + 148, 8); + for (int i = 0; i < 512; i++) sum += (unsigned char)(i >= 148 && i < 156 ? ' ' : hdr[i]); + if (sum != want) { set_err("'%s' não é um tar", path); gzclose(f); return -1; } + } + long long size = octal(hdr + 124, 12); + long long padded = (size + 511) / 512 * 512; + char type = hdr[156]; + if (type == 'L' || type == 'x') { /* nome longo / pax: o proximo cabecalho usa */ + char* data = malloc((size_t)padded + 1); + if (!data || !rd(f, data, (size_t)padded)) { free(data); set_err("'%s' cortado", path); gzclose(f); return -1; } + data[size] = 0; + if (type == 'L') snprintf(longname, sizeof(longname), "%s", data); + else { + char* p = strstr(data, " path="); + if (p) { p += 6; char* e = strchr(p, '\n'); if (e) *e = 0; snprintf(longname, sizeof(longname), "%s", p); } + } + free(data); + continue; + } + if (type == 'g') { skip(f, padded); continue; } + char name[4096]; + if (longname[0]) { snprintf(name, sizeof(name), "%s", longname); longname[0] = 0; } + else { + char base[101], prefix[156]; + memcpy(base, hdr, 100); base[100] = 0; + memcpy(prefix, hdr + 345, 155); prefix[155] = 0; + if (prefix[0]) snprintf(name, sizeof(name), "%s/%s", prefix, base); + else snprintf(name, sizeof(name), "%s", base); + } + long long used = 0; + if (!fn(name, size, type, f, &used, ud)) { gzclose(f); return -1; } + if (!skip(f, padded - used)) { set_err("'%s' cortado em '%s'", path, name); gzclose(f); return -1; } + if (type == '0' || type == '\0' || type == '7') count++; + } + gzclose(f); + return count; +} + +/* -- extrair -------------------------------------------------------------- */ +static bool extract_one(const char* name, long long size, char type, gzFile f, long long* used, void* ud) { + const char* dir = ud; + if (!safe_name(name)) return true; /* fora da pasta: ignora */ + char out[4200]; + snprintf(out, sizeof(out), "%s/%s", dir, name); + if (type == '5') { mkdirs(out, true); return true; } + if (type != '0' && type != '\0' && type != '7') return true; /* links etc.: pula */ + mkdirs(out, false); + FILE* o = fopen(out, "wb"); + if (!o) { set_err("não abriu '%.300s' para gravar", out); return false; } + char buf[65536]; + long long left = size; + while (left > 0) { + size_t k = left > (long long)sizeof(buf) ? sizeof(buf) : (size_t)left; + if (!rd(f, buf, k) || fwrite(buf, 1, k, o) != k) { fclose(o); set_err("falha ao extrair '%.300s'", name); return false; } + left -= (long long)k; + } + *used = size; + return fclose(o) == 0; +} + +int tb_archive_extract(const char* path, const char* dir) { + mkdirs(dir, true); + return walk(path, extract_one, (void*)dir); +} + +/* -- listar --------------------------------------------------------------- */ +static bool list_one(const char* name, long long size, char type, gzFile f, long long* used, void* ud) { + (void)size; (void)f; (void)used; + if (type != '0' && type != '\0' && type != '7') return true; + TinyBlocks_JsonValue* s = tb_json_string(name); + tb_json_array_push((TinyBlocks_JsonValue*)ud, s); + tb_json_release(s); + return true; +} + +TinyBlocks_JsonValue* tb_archive_list(const char* path) { + TinyBlocks_JsonValue* arr = tb_json_array(); + if (walk(path, list_one, arr) < 0) { tb_json_release(arr); return NULL; } + return arr; +} + +/* == Blocos =========================================================== */ +static void eval_extract(TinyBlocks_Block* self, TinyBlocks* rt) { + int n = tb_archive_extract(tb_block_input_text(self, rt, 0), tb_block_input_text(self, rt, 1)); + if (n < 0) tinyblocks_set_error(rt, "%s", s_err); + self->dirty = false; +} + +static void eval_list(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* l = tb_archive_list(tb_block_input_text(self, rt, 0)); + if (!l) tinyblocks_set_error(rt, "%s", s_err); + else { tb_block_set_output(self, 0, tb_value_json(l)); tb_json_release(l); } + self->dirty = false; +} + +static bool archive_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { "Arquivos compactados", {0.62f, 0.45f, 0.25f, 1.f}, {0.48f, 0.34f, 0.17f, 1.f} }; + tb_library_set_category(lib, &cat); + static const TinyBlocks_SlotDesc two[] = {{"arquivo", TB_VALUE_TEXT}, {"pasta", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc one[] = {{"arquivo", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc out[] = {{"lista", TB_VALUE_JSON}}; + TinyBlocks_TypeBlock* a = tb_type_block_create(rt, "Archive.Extract", two, 2, NULL, 0, eval_extract); + TinyBlocks_TypeBlock* b = tb_type_block_create(rt, "Archive.List", one, 1, out, 1, eval_list); + if (!a || !b) return false; + tb_type_block_set_label(a, "extraia %1 para a pasta %2", "dados.tar.gz|dados"); + tb_type_block_set_label(b, "arquivos dentro de %1", "dados.tar.gz"); + tb_meta_declare("Archive.Extract", "eval_extract", __FILE__, "Extrai um .tar ou .tar.gz (nada sai da pasta)"); + tb_meta_declare("Archive.List", "eval_list", __FILE__, "Lista os arquivos de um .tar ou .tar.gz"); + return tb_library_add(lib, &a->base) && tb_library_add(lib, &b->base); +} + +TINYBLOCKS_DEFINE_LIBRARY(archive, "tinyblocks-archive", "1.0.0", archive_init, NULL) + +const TinyBlocks_LibraryDescriptor* tb_archive_get_library(void) { + return &_tb_lib_desc_archive; +} diff --git a/libraries/tinyblocks-http/Makefile b/libraries/tinyblocks-http/Makefile new file mode 100644 index 0000000..cf93642 --- /dev/null +++ b/libraries/tinyblocks-http/Makefile @@ -0,0 +1,30 @@ +# Makefile da library http (categoria "HTTP") +# Constroi build/libtinyblocks-http.a e build/libtinyblocks-http.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-socket/include -I../tinyblocks-ssl/include + +SRCS := src/tb_http.c +OBJS := $(BUILD)/tb_http.o +LIB_A := $(BUILD)/libtinyblocks-http.a +LIB_SO := $(BUILD)/libtinyblocks-http.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ -lpthread + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-http/include/tb_http.h b/libraries/tinyblocks-http/include/tb_http.h new file mode 100644 index 0000000..8cb69bd --- /dev/null +++ b/libraries/tinyblocks-http/include/tb_http.h @@ -0,0 +1,25 @@ +/* + * TinyBlocks - tb_http.h + * Library tinyblocks-http: cliente HTTP/1.1 sobre a interface TbStream. + * Registra a categoria "HTTP". + * + * http:// usa a conexao TCP da tinyblocks-socket; https:// embrulha essa + * conexao em TLS pela tinyblocks-ssl (se ela estiver carregada). As duas sao + * achadas pelo runtime (tabelas no lib_userdata): esta library so conhece a + * interface TbStream. Segue redirecionamentos (ate 8, inclusive de http + * para https), entende Content-Length e "chunked". + * + * Baixar e ASSINCRONO: "baixe (url) para (arquivo)" comeca numa thread e + * volta na hora; o programa espera com + * repita ate que + * O arquivo so ganha o nome final quando chega inteiro (antes: + * .parte). "conteudo de (url)" busca um texto de uma vez. + */ +#ifndef TINYBLOCKS_HTTP_H +#define TINYBLOCKS_HTTP_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_http_get_library(void); + +#endif /* TINYBLOCKS_HTTP_H */ diff --git a/libraries/tinyblocks-http/library.toml b/libraries/tinyblocks-http/library.toml new file mode 100644 index 0000000..891bc31 --- /dev/null +++ b/libraries/tinyblocks-http/library.toml @@ -0,0 +1,15 @@ +# Metadados da library http. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-http" +version = "1.0.0" +category = "HTTP" +description = "Cliente HTTP/1.1 sobre TbStream: http:// (socket) e https:// (ssl), redirecionamentos, chunked e download em segundo plano" +color = [51, 140, 217, 255] +dark = [33, 107, 173, 255] + +[build] +sources = ["src/tb_http.c"] +includes = ["include"] +shared = "build/libtinyblocks-http.so" +static = "build/libtinyblocks-http.a" +depends = ["socket", "ssl"] diff --git a/libraries/tinyblocks-http/src/tb_http.c b/libraries/tinyblocks-http/src/tb_http.c new file mode 100644 index 0000000..b909f26 --- /dev/null +++ b/libraries/tinyblocks-http/src/tb_http.c @@ -0,0 +1,462 @@ +/* + * 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, 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); + 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, 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); + 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, 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 = '/'; + } +} + +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)); + FILE* f = NULL; + 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"); + 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; + 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"); + } + 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); + 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; +} diff --git a/libraries/tinyblocks-socket/Makefile b/libraries/tinyblocks-socket/Makefile new file mode 100644 index 0000000..dd7ed6a --- /dev/null +++ b/libraries/tinyblocks-socket/Makefile @@ -0,0 +1,30 @@ +# Makefile da library socket (categoria "Socket") +# Constroi build/libtinyblocks-socket.a e build/libtinyblocks-socket.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +SRCS := src/tb_socket.c +OBJS := $(BUILD)/tb_socket.o +LIB_A := $(BUILD)/libtinyblocks-socket.a +LIB_SO := $(BUILD)/libtinyblocks-socket.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-socket/include/tb_socket.h b/libraries/tinyblocks-socket/include/tb_socket.h new file mode 100644 index 0000000..29d9fb0 --- /dev/null +++ b/libraries/tinyblocks-socket/include/tb_socket.h @@ -0,0 +1,65 @@ +/* + * TinyBlocks - tb_socket.h + * Library tinyblocks-socket: conexoes TCP (sockets POSIX). Registra a + * categoria "Socket". + * + * Define a interface TbStream, um fluxo de bytes com classe (read, write, + * close). A conexao TCP e um TbStream; a tinyblocks-openssl embrulha um + * TbStream TCP num TbStream TLS; a tinyblocks-http so fala com TbStream, sem + * saber se ha TLS por baixo. + * + * Como as outras libraries chegam aqui sem linkar: a tabela TbSocketApi fica + * no lib_userdata da library (tb_socket_api(rt)). + * + * Blocos: "conecte a (host) porta (p)" devolve a conexao (um bloco-handle); + * "envie", "receba uma linha", "receba ate N bytes", "feche" e + * "endereco de (host)". + */ +#ifndef TINYBLOCKS_SOCKET_H +#define TINYBLOCKS_SOCKET_H + +#include +#include +#include + +#define TB_SOCKET_LIB "tinyblocks-socket" +#define TB_SOCKET_API_VERSION 1 + +typedef struct TbStream TbStream; + +/* Classe de um fluxo: read devolve bytes lidos (0 = fim, -1 = erro) */ +typedef struct TbStreamClass { + const char* name; /* "tcp", "tls" */ + long (*read)(TbStream* s, void* buf, size_t cap); + long (*write)(TbStream* s, const void* buf, size_t n); + void (*close)(TbStream* s); /* fecha e libera s */ +} TbStreamClass; + +struct TbStream { + const TbStreamClass* cls; + int fd; /* socket por baixo (-1 se nenhum) */ + void* impl; /* dados da classe (ex.: o SSL*) */ + char err[160]; /* ultimo erro deste fluxo */ +}; + +typedef struct TbSocketApi { + int version; /* TB_SOCKET_API_VERSION */ + /* TCP: NULL em erro (mensagem em err). timeout_ms <= 0 = 30 s. */ + TbStream* (*tcp_connect)(const char* host, int port, int timeout_ms, char* err, size_t cap); + /* Escreve tudo (repete o write ate acabar); false em erro */ + bool (*write_all)(TbStream* s, const void* buf, size_t n); +} TbSocketApi; + +TB_API const TinyBlocks_LibraryDescriptor* tb_socket_get_library(void); + +static inline const TbSocketApi* tb_socket_api(TinyBlocks* rt) { + TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, TB_SOCKET_LIB); + const TbSocketApi* api = lib ? (const TbSocketApi*)lib->lib_userdata : NULL; + return api && api->version == TB_SOCKET_API_VERSION ? api : NULL; +} + +static inline long tb_stream_read(TbStream* s, void* buf, size_t cap) { return s->cls->read(s, buf, cap); } +static inline long tb_stream_write(TbStream* s, const void* buf, size_t n) { return s->cls->write(s, buf, n); } +static inline void tb_stream_close(TbStream* s) { if (s) s->cls->close(s); } + +#endif /* TINYBLOCKS_SOCKET_H */ diff --git a/libraries/tinyblocks-socket/library.toml b/libraries/tinyblocks-socket/library.toml new file mode 100644 index 0000000..b64d288 --- /dev/null +++ b/libraries/tinyblocks-socket/library.toml @@ -0,0 +1,15 @@ +# Metadados da library socket. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-socket" +version = "1.0.0" +category = "Socket" +description = "Conexoes TCP (fluxos TbStream) e blocos para conectar, enviar e receber" +color = [51, 153, 158, 255] +dark = [33, 115, 120, 255] + +[build] +sources = ["src/tb_socket.c"] +includes = ["include"] +shared = "build/libtinyblocks-socket.so" +static = "build/libtinyblocks-socket.a" +depends = [] diff --git a/libraries/tinyblocks-socket/src/tb_socket.c b/libraries/tinyblocks-socket/src/tb_socket.c new file mode 100644 index 0000000..2436b4f --- /dev/null +++ b/libraries/tinyblocks-socket/src/tb_socket.c @@ -0,0 +1,287 @@ +/* + * TinyBlocks - tb_socket.c + * Conexoes TCP como TbStream e os blocos da categoria "Socket". + */ +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tb_socket.h" + +/* == TCP como TbStream ================================================ */ +static long tcp_read(TbStream* s, void* buf, size_t cap) { + for (;;) { + ssize_t n = recv(s->fd, buf, cap, 0); + if (n >= 0) return (long)n; + if (errno == EINTR) continue; + snprintf(s->err, sizeof(s->err), "%s", errno == EAGAIN || errno == EWOULDBLOCK ? "tempo esgotado esperando dados" : strerror(errno)); + return -1; + } +} + +static long tcp_write(TbStream* s, const void* buf, size_t n) { + for (;;) { + ssize_t w = send(s->fd, buf, n, MSG_NOSIGNAL); + if (w >= 0) return (long)w; + if (errno == EINTR) continue; + snprintf(s->err, sizeof(s->err), "%s", strerror(errno)); + return -1; + } +} + +static void tcp_close(TbStream* s) { + if (s->fd >= 0) close(s->fd); + free(s); +} + +static const TbStreamClass s_tcp = { "tcp", tcp_read, tcp_write, tcp_close }; + +static TbStream* tcp_connect(const char* host, int port, int timeout_ms, char* err, size_t cap) { + if (timeout_ms <= 0) timeout_ms = 30000; + char ps[16]; + snprintf(ps, sizeof(ps), "%d", port); + struct addrinfo hints, *res = NULL; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + int rc = getaddrinfo(host, ps, &hints, &res); + if (rc != 0) { snprintf(err, cap, "não achei o endereço de '%s' (%s)", host, gai_strerror(rc)); return NULL; } + int fd = -1; + char last[128] = "nenhum endereço respondeu"; + for (struct addrinfo* a = res; a; a = a->ai_next) { + fd = socket(a->ai_family, a->ai_socktype, a->ai_protocol); + if (fd < 0) continue; + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, fl | O_NONBLOCK); /* connect com prazo */ + int c = connect(fd, a->ai_addr, a->ai_addrlen); + if (c < 0 && errno == EINPROGRESS) { + struct pollfd pf = { fd, POLLOUT, 0 }; + int pr = poll(&pf, 1, timeout_ms); + int soerr = 0; socklen_t sl = sizeof(soerr); + if (pr == 1) getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &sl); + c = (pr == 1 && soerr == 0) ? 0 : -1; + if (c) snprintf(last, sizeof(last), "%s", pr == 0 ? "tempo esgotado conectando" : strerror(soerr ? soerr : errno)); + } else if (c < 0) snprintf(last, sizeof(last), "%s", strerror(errno)); + if (c == 0) { fcntl(fd, F_SETFL, fl); break; } + close(fd); fd = -1; + } + freeaddrinfo(res); + if (fd < 0) { snprintf(err, cap, "não conectou a %s:%d: %s", host, port, last); return NULL; } + struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 }; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + int one = 1; + setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one)); + TbStream* s = calloc(1, sizeof(TbStream)); + if (!s) { close(fd); snprintf(err, cap, "sem memória"); return NULL; } + s->cls = &s_tcp; + s->fd = fd; + return s; +} + +static bool write_all(TbStream* s, const void* buf, size_t n) { + const char* p = buf; + while (n > 0) { + long w = tb_stream_write(s, p, n); + if (w <= 0) return false; + p += w; n -= (size_t)w; + } + return true; +} + +static const TbSocketApi s_api = { TB_SOCKET_API_VERSION, tcp_connect, write_all }; + +/* == Bloco-handle da conexao ========================================== */ +typedef struct { TbStream* s; TinyBlocks_Block* owner; } ConnData; +typedef struct { TinyBlocks_Block* handle; } Producer; + +static TinyBlocks_TypeBlock* s_t_conn; + +static void conn_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + ConnData* c = self->userdata; + if (!c) return; + tb_stream_close(c->s); + c->s = NULL; + if (c->owner && c->owner->userdata && ((Producer*)c->owner->userdata)->handle == self) + ((Producer*)c->owner->userdata)->handle = NULL; +} + +static size_t conn_text(TinyBlocks_Block* self, char* out, size_t cap) { + ConnData* c = self->userdata; + return (size_t)snprintf(out, cap, c && c->s ? "conexão %s aberta" : "conexão fechada", c && c->s ? c->s->cls->name : ""); +} + +static void producer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { + Producer* p = self->userdata; + if (p && p->handle) { + TinyBlocks_Block* h = p->handle; + p->handle = NULL; + ((ConnData*)h->userdata)->owner = NULL; + tb_block_destroy(h, rt); + } +} + +static ConnData* conn_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_BLOCK && v.as.block && v.as.block->type == s_t_conn) { + ConnData* c = v.as.block->userdata; + if (c && c->s) return c; + tinyblocks_set_error(rt, "a conexão está fechada"); + return NULL; + } + tinyblocks_set_error(rt, "esperava uma conexão e veio %s", tb_value_type_name(v)); + return NULL; +} + +/* == Blocos =========================================================== */ +static void eval_connect(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + const char* host = tb_block_input_text(self, rt, 0); + int port = (int)tb_block_input_integer(self, rt, 1, 80); + char err[192]; + TbStream* s = tcp_connect(host, port, 15000, err, sizeof(err)); + if (!s) { tinyblocks_set_error(rt, "%s", err); return; } + Producer* p = self->userdata; + if (!p->handle) { + p->handle = tb_block_create(rt, s_t_conn); + if (!p->handle) { tb_stream_close(s); return; } + ((ConnData*)p->handle->userdata)->owner = self; + } + ConnData* c = p->handle->userdata; + tb_stream_close(c->s); + c->s = s; + tb_block_set_output(self, 0, tb_value_block(p->handle)); +} + +static void eval_send(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + const char* txt = tb_block_input_text(self, rt, 0); + ConnData* c = conn_in(self, rt, 1); + if (c && !write_all(c->s, txt, strlen(txt))) tinyblocks_set_error(rt, "falha ao enviar: %s", c->s->err); +} + +static void eval_recv_line(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + ConnData* c = conn_in(self, rt, 0); + if (!c) return; + char buf[4096]; + size_t n = 0; + while (n + 1 < sizeof(buf)) { /* byte a byte: nao le alem da linha */ + char ch; + long r = tb_stream_read(c->s, &ch, 1); + if (r <= 0) { if (r < 0 && !n) { tinyblocks_set_error(rt, "falha ao receber: %s", c->s->err); return; } break; } + if (ch == '\n') break; + if (ch != '\r') buf[n++] = ch; + } + buf[n] = 0; + tb_block_set_output(self, 0, tb_value_text(buf)); +} + +static void eval_recv(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + ConnData* c = conn_in(self, rt, 0); + if (!c) return; + long want = (long)tb_block_input_integer(self, rt, 1, 1024); + if (want < 1) want = 1; + if (want > 1 << 24) want = 1 << 24; + char* buf = malloc((size_t)want + 1); + if (!buf) return; + long r = tb_stream_read(c->s, buf, (size_t)want); + if (r < 0) { tinyblocks_set_error(rt, "falha ao receber: %s", c->s->err); r = 0; } + buf[r] = 0; + tb_block_set_output(self, 0, tb_value_text(buf)); + free(buf); +} + +static void eval_close(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + if (v.kind == TB_VALUE_BLOCK && v.as.block && v.as.block->type == s_t_conn) { + ConnData* c = v.as.block->userdata; + tb_stream_close(c->s); + c->s = NULL; + } +} + +static void eval_resolve(TinyBlocks_Block* self, TinyBlocks* rt) { + self->dirty = false; + const char* host = tb_block_input_text(self, rt, 0); + struct addrinfo hints, *res = NULL; + memset(&hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_STREAM; + int rc = getaddrinfo(host, NULL, &hints, &res); + if (rc != 0) { tinyblocks_set_error(rt, "não achei o endereço de '%s' (%s)", host, gai_strerror(rc)); return; } + char ip[INET6_ADDRSTRLEN] = ""; + if (res->ai_family == AF_INET) inet_ntop(AF_INET, &((struct sockaddr_in*)res->ai_addr)->sin_addr, ip, sizeof(ip)); + else inet_ntop(AF_INET6, &((struct sockaddr_in6*)res->ai_addr)->sin6_addr, ip, sizeof(ip)); + freeaddrinfo(res); + tb_block_set_output(self, 0, tb_value_text(ip)); +} + +/* == 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); + if (fn == eval_connect) tb_type_block_set_instance_hooks(t, sizeof(Producer), NULL, producer_deinit); + return tb_library_add(lib, &t->base); +} + +static bool socket_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { "Socket", {0.20f, 0.60f, 0.62f, 1.f}, {0.13f, 0.45f, 0.47f, 1.f} }; + tb_library_set_category(lib, &cat); + lib->lib_userdata = (void*)&s_api; + s_t_conn = tb_type_block_create(rt, "Socket._Conexao", NULL, 0, NULL, 0, NULL); + if (!s_t_conn) return false; + tb_type_block_set_flags(s_t_conn, TB_TYPE_HIDDEN); + tb_type_block_set_instance_hooks(s_t_conn, sizeof(ConnData), NULL, conn_deinit); + tb_type_block_set_value_text(s_t_conn, conn_text); + if (!tb_library_add(lib, &s_t_conn->base)) return false; + + static const TinyBlocks_SlotDesc host_port[] = {{"host", TB_VALUE_TEXT}, {"porta", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc txt_conn[] = {{"texto", TB_VALUE_TEXT}, {"conexão", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc conn[] = {{"conexão", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc conn_n[] = {{"conexão", TB_VALUE_NONE}, {"bytes", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc host[] = {{"host", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc out_conn[] = {{"conexão", TB_VALUE_BLOCK}}; + static const TinyBlocks_SlotDesc out_txt[] = {{"texto", TB_VALUE_TEXT}}; + return reg(rt, lib, "Socket.Connect", "conecte a %1 porta %2", "example.com|80", host_port, 2, out_conn, 1, + eval_connect, "eval_connect", "Abre uma conexão TCP") + && reg(rt, lib, "Socket.Send", "envie %1 por %2", "olá\\n|", txt_conn, 2, NULL, 0, + eval_send, "eval_send", "Envia o texto pela conexão") + && reg(rt, lib, "Socket.RecvLine", "receba uma linha de %1", "", conn, 1, out_txt, 1, + eval_recv_line, "eval_recv_line", "Lê até o fim da linha (espera até 15 s)") + && reg(rt, lib, "Socket.Recv", "receba até %2 bytes de %1", "|1024", conn_n, 2, out_txt, 1, + eval_recv, "eval_recv", "Lê o que chegar (até N bytes)") + && reg(rt, lib, "Socket.Close", "feche %1", "", conn, 1, NULL, 0, + eval_close, "eval_close", "Fecha a conexão") + && reg(rt, lib, "Socket.Resolve", "endereço de %1", "example.com", host, 1, out_txt, 1, + eval_resolve, "eval_resolve", "IP do computador com esse nome (DNS)"); +} + +static void socket_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; + lib->lib_userdata = NULL; +} + +TINYBLOCKS_DEFINE_LIBRARY(socket, "tinyblocks-socket", "1.0.0", socket_init, socket_deinit) + +const TinyBlocks_LibraryDescriptor* tb_socket_get_library(void) { + return &_tb_lib_desc_socket; +} diff --git a/libraries/tinyblocks-ssl/Makefile b/libraries/tinyblocks-ssl/Makefile new file mode 100644 index 0000000..92da1fa --- /dev/null +++ b/libraries/tinyblocks-ssl/Makefile @@ -0,0 +1,30 @@ +# Makefile da library ssl (categoria "SSL") +# Constroi build/libtinyblocks-ssl.a e build/libtinyblocks-ssl.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-socket/include + +SRCS := src/tb_ssl.c +OBJS := $(BUILD)/tb_ssl.o +LIB_A := $(BUILD)/libtinyblocks-ssl.a +LIB_SO := $(BUILD)/libtinyblocks-ssl.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h) + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJS) + ar rcs $@ $^ + +$(LIB_SO): $(OBJS) + $(CC) -shared -o $@ $^ -lssl -lcrypto + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-ssl/include/tb_ssl.h b/libraries/tinyblocks-ssl/include/tb_ssl.h new file mode 100644 index 0000000..84fcad9 --- /dev/null +++ b/libraries/tinyblocks-ssl/include/tb_ssl.h @@ -0,0 +1,41 @@ +/* + * TinyBlocks - tb_ssl.h + * Library tinyblocks-ssl: TLS (dependencia de terceiros: OpenSSL). Registra + * a categoria "SSL". + * + * Embrulha um TbStream TCP (tinyblocks-socket) num TbStream TLS: ler e + * escrever passam a ser cifrados, e quem usa o fluxo (ex.: a + * tinyblocks-http, para o https://) nao muda nada. O certificado do + * servidor e conferido com os certificados do sistema e com o nome do host + * (SNI + verificacao do nome). + * + * Tabela TbSslApi no lib_userdata da library (tb_ssl_api(rt)). + */ +#ifndef TINYBLOCKS_SSL_H +#define TINYBLOCKS_SSL_H + +#include +#include +#include +#include "tb_socket.h" + +#define TB_SSL_LIB "tinyblocks-ssl" +#define TB_SSL_API_VERSION 1 + +typedef struct TbSslApi { + int version; /* TB_SSL_API_VERSION */ + /* Faz o aperto de mao TLS sobre tcp (fica dono dele: fecha junto). + NULL em erro (tcp ja fechado; mensagem em err). */ + TbStream* (*wrap)(TbStream* tcp, const char* host, char* err, size_t cap); + const char* (*version_text)(void); /* "OpenSSL 3.0.13 ..." */ +} TbSslApi; + +TB_API const TinyBlocks_LibraryDescriptor* tb_ssl_get_library(void); + +static inline const TbSslApi* tb_ssl_api(TinyBlocks* rt) { + TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, TB_SSL_LIB); + const TbSslApi* api = lib ? (const TbSslApi*)lib->lib_userdata : NULL; + return api && api->version == TB_SSL_API_VERSION ? api : NULL; +} + +#endif /* TINYBLOCKS_SSL_H */ diff --git a/libraries/tinyblocks-ssl/library.toml b/libraries/tinyblocks-ssl/library.toml new file mode 100644 index 0000000..9226eb2 --- /dev/null +++ b/libraries/tinyblocks-ssl/library.toml @@ -0,0 +1,15 @@ +# Metadados da library ssl. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-ssl" +version = "1.0.0" +category = "SSL" +description = "TLS (OpenSSL): embrulha uma conexao TCP num fluxo cifrado, com certificado conferido" +color = [102, 140, 77, 255] +dark = [74, 107, 54, 255] + +[build] +sources = ["src/tb_ssl.c"] +includes = ["include"] +shared = "build/libtinyblocks-ssl.so" +static = "build/libtinyblocks-ssl.a" +depends = ["socket"] diff --git a/libraries/tinyblocks-ssl/src/tb_ssl.c b/libraries/tinyblocks-ssl/src/tb_ssl.c new file mode 100644 index 0000000..920f198 --- /dev/null +++ b/libraries/tinyblocks-ssl/src/tb_ssl.c @@ -0,0 +1,121 @@ +/* + * TinyBlocks - tb_ssl.c + * TLS sobre TbStream com OpenSSL: o fluxo "tls" le e escreve pelo SSL* + * ligado ao socket do fluxo TCP que ele embrulha. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include + +#include +#include +#include + +#include "tb_ssl.h" + +static SSL_CTX* s_ctx; + +typedef struct { SSL* ssl; TbStream* tcp; } Tls; + +static void ssl_err(char* out, size_t cap, const char* what) { + unsigned long e = ERR_get_error(); + char buf[200] = ""; + if (e) ERR_error_string_n(e, buf, sizeof(buf)); + snprintf(out, cap, "%s%s%s", what, buf[0] ? ": " : "", buf); +} + +static long tls_read(TbStream* s, void* buf, size_t cap) { + Tls* t = s->impl; + int n = SSL_read(t->ssl, buf, (int)(cap > 1 << 30 ? 1 << 30 : cap)); + if (n > 0) return n; + int e = SSL_get_error(t->ssl, n); + if (e == SSL_ERROR_ZERO_RETURN) return 0; /* o servidor fechou direito */ + if (e == SSL_ERROR_SYSCALL && ERR_peek_error() == 0) return 0; /* fechou sem close_notify */ + ssl_err(s->err, sizeof(s->err), "falha ao ler (TLS)"); + return -1; +} + +static long tls_write(TbStream* s, const void* buf, size_t n) { + Tls* t = s->impl; + int w = SSL_write(t->ssl, buf, (int)(n > 1 << 30 ? 1 << 30 : n)); + if (w > 0) return w; + ssl_err(s->err, sizeof(s->err), "falha ao escrever (TLS)"); + return -1; +} + +static void tls_close(TbStream* s) { + Tls* t = s->impl; + if (t) { + if (t->ssl) { SSL_shutdown(t->ssl); SSL_free(t->ssl); } + tb_stream_close(t->tcp); + free(t); + } + free(s); +} + +static const TbStreamClass s_tls = { "tls", tls_read, tls_write, tls_close }; + +static TbStream* tls_wrap(TbStream* tcp, const char* host, char* err, size_t cap) { + if (!s_ctx) { snprintf(err, cap, "TLS não inicializado"); tb_stream_close(tcp); return NULL; } + SSL* ssl = SSL_new(s_ctx); + if (!ssl) { ssl_err(err, cap, "SSL_new"); tb_stream_close(tcp); return NULL; } + SSL_set_fd(ssl, tcp->fd); + SSL_set_tlsext_host_name(ssl, host); /* SNI */ + SSL_set1_host(ssl, host); /* o certificado tem de ser deste host */ + if (SSL_connect(ssl) != 1) { + long v = SSL_get_verify_result(ssl); + if (v != X509_V_OK) snprintf(err, cap, "certificado de %s recusado: %s", host, X509_verify_cert_error_string(v)); + else ssl_err(err, cap, "aperto de mão TLS falhou"); + SSL_free(ssl); + tb_stream_close(tcp); + return NULL; + } + TbStream* s = calloc(1, sizeof(TbStream)); + Tls* t = calloc(1, sizeof(Tls)); + if (!s || !t) { free(s); free(t); SSL_free(ssl); tb_stream_close(tcp); snprintf(err, cap, "sem memória"); return NULL; } + t->ssl = ssl; t->tcp = tcp; + s->cls = &s_tls; s->fd = tcp->fd; s->impl = t; + return s; +} + +static const char* version_text(void) { return OpenSSL_version(OPENSSL_VERSION); } + +static const TbSslApi s_api = { TB_SSL_API_VERSION, tls_wrap, version_text }; + +static void eval_version(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_block_set_output(self, 0, tb_value_text(version_text())); + self->dirty = false; +} + +static bool ssl_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { "SSL", {0.40f, 0.55f, 0.30f, 1.f}, {0.29f, 0.42f, 0.21f, 1.f} }; + tb_library_set_category(lib, &cat); + OPENSSL_init_ssl(0, NULL); + s_ctx = SSL_CTX_new(TLS_client_method()); + if (!s_ctx) return false; + SSL_CTX_set_min_proto_version(s_ctx, TLS1_2_VERSION); + SSL_CTX_set_verify(s_ctx, SSL_VERIFY_PEER, NULL); + SSL_CTX_set_default_verify_paths(s_ctx); /* certificados do sistema */ + lib->lib_userdata = (void*)&s_api; + static const TinyBlocks_SlotDesc out[] = {{"versão", TB_VALUE_TEXT}}; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "SSL.Version", NULL, 0, out, 1, eval_version); + if (!t) return false; + tb_type_block_set_label(t, "versão do SSL", NULL); + tb_meta_declare("SSL.Version", "eval_version", __FILE__, "Versão da biblioteca de TLS"); + return tb_library_add(lib, &t->base); +} + +static void ssl_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; + lib->lib_userdata = NULL; + SSL_CTX_free(s_ctx); + s_ctx = NULL; +} + +TINYBLOCKS_DEFINE_LIBRARY(ssl, "tinyblocks-ssl", "1.0.0", ssl_init, ssl_deinit) + +const TinyBlocks_LibraryDescriptor* tb_ssl_get_library(void) { + return &_tb_lib_desc_ssl; +} diff --git a/tests/archive_test.c b/tests/archive_test.c new file mode 100644 index 0000000..5a1cdf7 --- /dev/null +++ b/tests/archive_test.c @@ -0,0 +1,71 @@ +/* + * archive_test.c - testa a tinyblocks-archive: .tar.gz e .tar com pastas e + * nome longo (GNU/pax), e um tar malicioso com "../" que nao pode sair da + * pasta de destino. Os arquivos de teste sao feitos pelo tar e pelo Python. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include + +#include +#include + +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) + +static bool file_is(const char* path, const char* want) { + FILE* f = fopen(path, "r"); + if (!f) return false; + char buf[256] = ""; + size_t n = fread(buf, 1, sizeof(buf) - 1, f); + buf[n] = 0; + fclose(f); + return !strcmp(buf, want); +} + +int main(void) { + const char* longdir = "pasta_com_um_nome_bem_comprido_para_passar_dos_cem_caracteres_do_cabecalho_ustar_antigo"; + char cmd[2048]; + snprintf(cmd, sizeof(cmd), + "rm -rf /tmp/tb_arch && mkdir -p /tmp/tb_arch/src/a/%s && cd /tmp/tb_arch/src && " + "printf 'ola' > a/um.txt && printf 'longo' > a/%s/arquivo_de_nome_longo_tambem.txt && " + "tar czf ../teste.tar.gz a && tar cf ../teste.tar a && " + "python3 -I -c \"import tarfile,io; t=tarfile.open('../mau.tar.gz','w:gz'); " + "i=tarfile.TarInfo('../fora.txt'); d=b'x'; i.size=1; t.addfile(i, io.BytesIO(d)); " + "i=tarfile.TarInfo('/abs.txt'); i.size=1; t.addfile(i, io.BytesIO(d)); " + "i=tarfile.TarInfo('dentro.txt'); i.size=1; t.addfile(i, io.BytesIO(d)); t.close()\"", + longdir, longdir); + if (system(cmd) != 0) { printf("FAIL não criou os arquivos de teste\n"); return 1; } + + TinyBlocks* rt = NULL; + tinyblocks_init(&rt, NULL); + tb_library_register(rt, tb_archive_get_library()); + + TinyBlocks_JsonValue* l = tb_archive_list("/tmp/tb_arch/teste.tar.gz"); + CHECK(l && tb_json_array_length(l) == 2, "lista os 2 arquivos do .tar.gz"); + tb_json_release(l); + int n = tb_archive_extract("/tmp/tb_arch/teste.tar.gz", "/tmp/tb_arch/out"); + char p[1024]; + snprintf(p, sizeof(p), "/tmp/tb_arch/out/a/%s/arquivo_de_nome_longo_tambem.txt", longdir); + CHECK(n == 2 && file_is("/tmp/tb_arch/out/a/um.txt", "ola") && file_is(p, "longo"), "extrai o .tar.gz com pastas e nome longo"); + n = tb_archive_extract("/tmp/tb_arch/teste.tar", "/tmp/tb_arch/out2"); + CHECK(n == 2 && file_is("/tmp/tb_arch/out2/a/um.txt", "ola"), "extrai .tar sem compressão"); + n = tb_archive_extract("/tmp/tb_arch/mau.tar.gz", "/tmp/tb_arch/out3"); + CHECK(file_is("/tmp/tb_arch/out3/dentro.txt", "x") && access("/tmp/tb_arch/fora.txt", F_OK) != 0 && access("/abs.txt", F_OK) != 0, + "\"../\" e caminho absoluto não saem da pasta"); + CHECK(tb_archive_extract("/tmp/tb_arch/src/a/um.txt", "/tmp/tb_arch/out4") < 0 && strstr(tb_archive_last_error(), "tar"), + "arquivo que não é tar dá erro"); + + /* pelo bloco */ + TinyBlocks_Block* b = tb_block_create(rt, tb_type_block_find(rt, "Archive.List")); + TinyBlocks_Value v = tb_value_text("/tmp/tb_arch/teste.tar"); + tb_block_set_default(b, 0, v); tb_value_free(&v); + tb_block_eval(b, rt); + CHECK(b->outputs[0].kind == TB_VALUE_JSON && tb_json_array_length(b->outputs[0].as.json) == 2, "bloco \"arquivos dentro de\""); + tinyblocks_deinit(&rt); + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +} diff --git a/tests/http_test.c b/tests/http_test.c new file mode 100644 index 0000000..d89957d --- /dev/null +++ b/tests/http_test.c @@ -0,0 +1,170 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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, "