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>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-23 23:27:08 -03:00
1 parent 05fdb094ed
commit 066bb295ed
20 files changed
+1689 -3

No files matched your search

+30
View File
@@ -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)
@@ -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 <stdbool.h>
#include <stddef.h>
#include <tinyblocks/tinyblocks.h>
#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 */
+15
View File
@@ -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 = []
+287
View File
@@ -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 <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/time.h>
#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;
}