#include "naut/naut_plugin.h" #include #include #include typedef struct { uint8_t *data; size_t capacity; } memory_storage; static unsigned finished_events; static void *memory_open(const char *root, naut_err *error) { (void)root; memory_storage *storage = calloc(1, sizeof(*storage)); if (!storage) { *error = NAUT_ERR_NOMEM; return NULL; } storage->capacity = 1u << 20; storage->data = calloc(1, storage->capacity); if (!storage->data) { free(storage); *error = NAUT_ERR_NOMEM; return NULL; } *error = NAUT_OK; return storage; } static void memory_close(void *opaque) { memory_storage *storage = opaque; free(storage->data); free(storage); } static naut_err memory_read(void *opaque, int64_t offset, void *buffer, size_t length) { memory_storage *storage = opaque; if (offset < 0 || (uint64_t)offset + length > storage->capacity) return NAUT_ERR_RANGE; memcpy(buffer, storage->data + offset, length); return NAUT_OK; } static naut_err memory_write(void *opaque, int64_t offset, const void *buffer, size_t length) { memory_storage *storage = opaque; if (offset < 0 || (uint64_t)offset + length > storage->capacity) return NAUT_ERR_RANGE; memcpy(storage->data + offset, buffer, length); return NAUT_OK; } static naut_err example_events(void *context, const char *request, char **response) { (void)context; (void)request; char buffer[64]; snprintf(buffer, sizeof buffer, "{\"finished\":%u}", finished_events); *response = strdup(buffer); return *response ? NAUT_OK : NAUT_ERR_NOMEM; } static void on_event(void *context, const naut_event *event) { (void)context; if (event->type == NAUT_EVENT_TORRENT_FINISHED) finished_events++; } naut_err naut_plugin_register(const naut_host_api *host) { if (!host || host->abi_version != NAUT_PLUGIN_ABI_VERSION || host->struct_size < sizeof(*host)) return NAUT_ERR_INVAL; static const naut_storage_backend_v1 storage = { .abi_version = NAUT_PLUGIN_ABI_VERSION, .struct_size = sizeof(storage), .name = "memory", .open = memory_open, .close = memory_close, .read = memory_read, .write = memory_write, }; naut_err error = host->set_plugin_name(host->host_context, "example"); if (error == NAUT_OK) error = host->register_storage_backend(host->host_context, &storage); if (error == NAUT_OK) error = host->register_rpc(host->host_context, "example.events", example_events, NULL); if (error == NAUT_OK) error = host->subscribe_event(host->host_context, on_event, NULL); return error; }