/* * 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 */