#ifndef SCORPIOX_IO_H #define SCORPIOX_IO_H /* * scorpiox-io.h — pluggable IO backend for scorpiox C libraries. * * C libraries own all logic: URLs, request bodies, JSON parsing, state. * The backend owns only transport (HTTP) — libcurl on desktop, * URLSession on iOS/macOS. * * Contract: * - http_get/http_post: 0 = request completed (*http_code set, *out_body * set to a malloc'd NUL-terminated body), -1 = transport failure * (*out_err set to a malloc'd message, *out_body stays NULL). * - Buffers allocated by the backend are freed with the backend's free_buf. * - The backend MUST be synchronous (it blocks until the response is in). * - Call scorpiox_*_set_io() ONCE before any high-level call. * * Each library has its own setter (picobot_set_io / auth_set_io) because * backend state is per-library. Install the SAME scorpiox_io struct into * every library you link. */ #include #include typedef struct scorpiox_io { void *ctx; int (*http_get) (void *ctx, const char *url, char **out_body, long *http_code, char **out_err); /* content_type may be NULL (backend default: application/x-www-form-urlencoded) */ int (*http_post)(void *ctx, const char *url, const char *body, const char *content_type, char **out_body, long *http_code, char **out_err); void (*free_buf)(void *ctx, void *ptr); } scorpiox_io; /* * Portable RFC 3986 percent-encode (no libcurl needed). * Returns a malloc'd NUL-terminated string; caller frees with free(). * Returns NULL on allocation failure or NULL input. */ static inline char *scorpiox_percent_encode(const char *s) { if (!s) return 0; static const char hex[] = "0123456789ABCDEF"; size_t len = 0; for (const char *p = s; *p; p++) { char c = *p; int unreserved = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~'; len += unreserved ? 1 : 3; } char *out = (char *)malloc(len + 1); if (!out) return 0; char *o = out; for (const char *p = s; *p; p++) { char c = *p; int unreserved = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~'; if (unreserved) *o++ = c; else { *o++ = '%'; *o++ = hex[(unsigned char)c >> 4]; *o++ = hex[(unsigned char)c & 15]; } } *o = 0; return out; } #endif /* SCORPIOX_IO_H */