/* Copyright (c) 2026 Juhapekka Piiroinen * All Rights Reserved. * AmoosedWeb project: https://amoosed.com */ #include #include #include #include #include #include /* Usage: native-c-memory ORIGIN VIRTUAL_RESOURCE_PATH * The caller chooses a trusted HTTPS origin. Loopback HTTP is accepted for * development. The example reads a public resource and never prints its bytes. */ static void clear_bytes(uint8_t* bytes, size_t length) { volatile uint8_t* current = bytes; while (length--) *current++ = 0; } int main(int argc, char** argv) { if (argc != 3) { fprintf(stderr, "Usage: native-c-memory ORIGIN VIRTUAL_RESOURCE_PATH\n"); return 2; } uint64_t capabilities = 0; const uint64_t needed = AMW_PREVIEW_CAP_HOSTED_INDEX | AMW_PREVIEW_CAP_MEMORY_READ; if (amw_preview_abi_revision() != AMW_PREVIEW_ABI_REVISION || amw_preview_capabilities(&capabilities) != AMW_PREVIEW_OK || (capabilities & needed) != needed) { fprintf(stderr, "This library lacks the required preview ABI capabilities\n"); return 1; } char error[256] = {0}; amw_preview_site* site = NULL; int32_t status = amw_preview_site_open_hosted(argv[1], (uint64_t)strlen(argv[1]), &site, error, sizeof(error)); if (status != AMW_PREVIEW_OK) { fprintf(stderr, "Index open failed (%" PRId32 "): %s\n", status, error); return 1; } uint64_t indexed_length = 0; status = amw_preview_site_read_memory(site, argv[2], (uint64_t)strlen(argv[2]), NULL, 0, NULL, 0, &indexed_length, error, sizeof(error)); if (status != AMW_PREVIEW_OK || indexed_length > AMW_PREVIEW_MEMORY_LIMIT || indexed_length > SIZE_MAX) { fprintf(stderr, "Size query failed (%" PRId32 "): %s\n", status, error); amw_preview_site_release(site); return 1; } /* A non-NULL buffer and positive capacity also handle a zero-length file. */ const size_t capacity = indexed_length ? (size_t)indexed_length : 1u; uint8_t* bytes = (uint8_t*)malloc(capacity); if (!bytes) { fprintf(stderr, "Cannot allocate the bounded output buffer\n"); amw_preview_site_release(site); return 1; } memset(bytes, 0xa5, capacity); uint64_t verified_length = 0; status = amw_preview_site_read_memory(site, argv[2], (uint64_t)strlen(argv[2]), NULL, 0, bytes, (uint64_t)capacity, &verified_length, error, sizeof(error)); if (status != AMW_PREVIEW_OK || verified_length != indexed_length) { fprintf(stderr, "Verified read failed (%" PRId32 "): %s\n", status, error); clear_bytes(bytes, capacity); free(bytes); amw_preview_site_release(site); return 1; } /* Application code may use bytes[0..verified_length) only after success. * The library leaves this buffer unchanged if verification fails. */ printf("Verified %" PRIu64 " bytes in caller memory\n", verified_length); clear_bytes(bytes, capacity); free(bytes); amw_preview_site_release(site); return 0; }