/* Test-only Messages API stand-in: plain HTTP on 127.0.0.1, one scripted
* response per connection, every request saved for inspection. It exits on
* its own deadline, so a failed test cannot leave it running.
*
* Usage: fake_server PORT_FILE LOG_DIR DEADLINE_SECONDS SPEC...
* sse:FILE 200, chunked, FILE in 97-byte chunks
* status:CODE:FILE CODE with FILE as the body (- for none), Retry-After: 0
* head:CODE:FILE:H CODE with FILE as the body (- for none) and the header
* lines H, '|' between them ("retry-after: 900|x-a: 1")
* retry:CODE:SECS CODE with no body, Retry-After: SECS
* cut:FILE:N 200, chunked, the first N bytes of FILE, then close
* hang:FILE:N 200, chunked, the first N bytes of FILE, then hold
* slow:FILE:MS 200, chunked, FILE in 97-byte chunks MS apart
* gate:FILE:N:PATH 200, chunked, the first N bytes of FILE, then the rest once PATH exists
* (a reply that lasts until the test says, not for a time)
* at:PATH=SPEC SPEC (any of the above) for every request whose path is PATH,
* before and apart from the numbered specs: free checks such as
* GET /api/v1/key, /user/balance and /v1/models, which arrive together
* and in no fixed order
* Connection k gets the k-th SPEC that is not an at: one; the last repeats. Requests are saved as
* LOG_DIR/k.req (headers and body). A POST to a path ending in /count_tokens
* (the Messages API's counter) takes no SPEC: it is answered 200 with
* {"input_tokens":N}, N the request body's length in bytes. */
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
static time_t deadline;
static void die(const char *what) {
perror(what);
exit(2);
}
static char *slurp(const char *path, size_t *len) {
FILE *f = fopen(path, "rb");
char *buf;
long n = 0;
if (!f || fseek(f, 0, SEEK_END) != 0 || (n = ftell(f)) < 0 || fseek(f, 0, SEEK_SET) != 0) {
die(path);
}
buf = malloc((size_t)n + 1);
if (!buf || fread(buf, 1, (size_t)n, f) != (size_t)n) {
die(path);
}
fclose(f);
*len = (size_t)n;
return buf;
}
static int send_all(int fd, const char *p, size_t n) {
while (n > 0) {
ssize_t w = send(fd, p, n, 0);
if (w < 0) {
if (errno == EINTR) {
continue;
}
return -1;
}
p += w;
n -= (size_t)w;
}
return 0;
}
static int send_chunks(int fd, const char *p, size_t n, int gap_ms) {
char head[32];
for (size_t off = 0; off < n; off += 97) {
size_t k = n - off < 97 ? n - off : 97;
if (gap_ms > 0 && off > 0) {
struct timespec t = {gap_ms / 1000, (long)(gap_ms % 1000) * 1000000L};
nanosleep(&t, NULL);
}
int h = snprintf(head, sizeof head, "%zx\r\n", k);
if (send_all(fd, head, (size_t)h) != 0 || send_all(fd, p + off, k) != 0 || send_all(fd, "\r\n", 2) != 0) {
return -1;
}
}
return 0;
}
/* Reads one request (headers, then Content-Length bytes) and saves it. */
/* Saves the request; its body length when it is a count_tokens POST, else -1.
* path, when not NULL, gets the request target without its query. */
static long read_request(int fd, const char *log_path, char *path, size_t pathcap) {
long counted = -1;
size_t cap = 1 << 20, used = 0, want = 0;
char *buf = malloc(cap + 1), *end = NULL;
FILE *f;
if (!buf) {
die("malloc");
}
while (!end || used < want) {
struct pollfd p = {fd, POLLIN, 0};
ssize_t r;
if (time(NULL) >= deadline || poll(&p, 1, 1000) < 0) {
break;
}
if (!(p.revents & (POLLIN | POLLHUP))) {
continue;
}
r = recv(fd, buf + used, cap - used, 0);
if (r <= 0) {
break;
}
used += (size_t)r;
buf[used] = '\0';
if (!end && (end = strstr(buf, "\r\n\r\n"))) {
const char *cl = strstr(buf, "Content-Length: ");
want = (size_t)(end + 4 - buf) + (cl ? strtoul(cl + 16, NULL, 10) : 0);
}
if (used == cap) {
break;
}
}
if (path) {
const char *sp = strchr(buf, ' '), *end_sp = sp ? strchr(sp + 1, ' ') : NULL;
size_t n = end_sp ? (size_t)(end_sp - sp - 1) : 0;
n = n + 1 < pathcap ? n : pathcap - 1;
if (sp) {
memcpy(path, sp + 1, n);
}
path[sp ? n : 0] = '\0';
path[strcspn(path, "?")] = '\0';
}
f = fopen(log_path, "wb");
if (!f || fwrite(buf, 1, used, f) != used || fclose(f) != 0) {
die(log_path);
}
if (end && strncmp(buf, "POST ", 5) == 0) {
const char *sp = strchr(buf + 5, ' ');
if (sp && sp - (buf + 5) >= 13 && strncmp(sp - 13, "/count_tokens", 13) == 0) {
counted = (long)(used - (size_t)(end + 4 - buf));
}
}
free(buf);
return counted;
}
static void respond(int fd, const char *spec) {
char kind[16], file[1024], *colon;
const char *rest;
size_t len = 0;
char *body;
colon = strchr(spec, ':');
if (!colon || (size_t)(colon - spec) >= sizeof kind) {
die("bad spec");
}
memcpy(kind, spec, (size_t)(colon - spec));
kind[colon - spec] = '\0';
rest = colon + 1;
if (strcmp(kind, "retry") == 0) {
char head[256];
int code = atoi(rest), h;
const char *secs = strchr(rest, ':');
h = snprintf(head, sizeof head,
"HTTP/1.1 %d Scripted\r\nContent-Type: application/json\r\nRetry-After: %d\r\n"
"request-id: req_fake\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
code, secs ? atoi(secs + 1) : 0);
(void)send_all(fd, head, (size_t)h);
return;
}
if (strcmp(kind, "head") == 0) {
char head[2048], path[1024], extra[1024];
int code = atoi(rest), h;
const char *p = strchr(rest, ':'), *q = p ? strchr(p + 1, ':') : NULL;
if (!p || !q) {
die("bad head spec");
}
(void)snprintf(path, sizeof path, "%.*s", (int)(q - p - 1), p + 1);
(void)snprintf(extra, sizeof extra, "%s", q + 1);
for (char *c = extra; *c; c++) {
if (*c == '|') {
*c = '\n';
}
}
body = strcmp(path, "-") != 0 ? slurp(path, &len) : NULL;
h = snprintf(head, sizeof head, "HTTP/1.1 %d Scripted\r\nContent-Type: application/json\r\n", code);
for (char *line = extra; *line;) {
char *nl = strchr(line, '\n');
h += snprintf(head + h, sizeof head - (size_t)h, "%.*s\r\n", nl ? (int)(nl - line) : (int)strlen(line), line);
line = nl ? nl + 1 : line + strlen(line);
}
h += snprintf(head + h, sizeof head - (size_t)h, "request-id: req_fake\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n", len);
(void)(send_all(fd, head, (size_t)h) || (body && send_all(fd, body, len)));
free(body);
return;
}
if (strcmp(kind, "status") == 0) {
char head[256];
int code = atoi(rest), h;
const char *path = strchr(rest, ':');
body = path && strcmp(path + 1, "-") != 0 ? slurp(path + 1, &len) : NULL;
h = snprintf(head, sizeof head,
"HTTP/1.1 %d Scripted\r\nContent-Type: application/json\r\nRetry-After: 0\r\n"
"request-id: req_fake\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n",
code, len);
(void)(send_all(fd, head, (size_t)h) || (body && send_all(fd, body, len)));
free(body);
return;
}
{
size_t limit = (size_t)-1;
int gap_ms = 0;
const char *last = strrchr(rest, ':');
char gate[1024] = "";
size_t whole;
static const char head[] = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nrequest-id: req_fake\r\n"
"Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
if (strcmp(kind, "sse") == 0) {
(void)snprintf(file, sizeof file, "%s", rest);
} else if (strcmp(kind, "gate") == 0) {
const char *mid;
(void)snprintf(gate, sizeof gate, "%s", last ? last + 1 : "");
for (mid = last ? last - 1 : rest; mid > rest && *mid != ':'; mid--) {
}
if (!last || mid <= rest) {
die("bad spec");
}
(void)snprintf(file, sizeof file, "%.*s", (int)(mid - rest), rest);
limit = strtoul(mid + 1, NULL, 10);
} else {
if (!last) {
die("bad spec");
}
(void)snprintf(file, sizeof file, "%.*s", (int)(last - rest), rest);
if (strcmp(kind, "slow") == 0) {
gap_ms = atoi(last + 1);
} else {
limit = strtoul(last + 1, NULL, 10);
}
}
body = slurp(file, &len);
whole = len;
if (limit < len) {
len = limit;
}
if (send_all(fd, head, sizeof head - 1) != 0 || send_chunks(fd, body, len, gap_ms) != 0) {
free(body);
return;
}
if (gate[0]) {
while (access(gate, F_OK) != 0 && time(NULL) < deadline) {
char sink[256];
struct pollfd p = {fd, POLLIN, 0};
if (poll(&p, 1, 50) > 0 && recv(fd, sink, sizeof sink, 0) <= 0) {
free(body);
return; /* the client went away */
}
}
if (send_chunks(fd, body + len, whole - len, 0) == 0) {
(void)send_all(fd, "0\r\n\r\n", 5);
}
}
free(body);
if (strcmp(kind, "sse") == 0 || strcmp(kind, "slow") == 0) {
(void)send_all(fd, "0\r\n\r\n", 5);
} else if (strcmp(kind, "hang") == 0) {
while (time(NULL) < deadline) {
char sink[256];
struct pollfd p = {fd, POLLIN, 0};
if (poll(&p, 1, 200) > 0 && recv(fd, sink, sizeof sink, 0) <= 0) {
break; /* the client went away */
}
}
}
}
}
/* The SPEC of the first at:PATH=SPEC argument for PATH, or NULL. */
static const char *routed_spec(int argc, char **argv, const char *path) {
for (int i = 4; i < argc; i++) {
const char *eq = strncmp(argv[i], "at:", 3) == 0 ? strchr(argv[i], '=') : NULL;
if (eq && strlen(path) == (size_t)(eq - argv[i] - 3) && strncmp(argv[i] + 3, path, strlen(path)) == 0) {
return eq + 1;
}
}
return NULL;
}
int main(int argc, char **argv) {
const char *plain[64], *routed;
int nplain = 0;
struct sockaddr_in addr;
socklen_t alen = sizeof addr;
int lfd, one = 1;
FILE *pf;
if (argc < 5) {
fprintf(stderr, "usage: fake_server PORT_FILE LOG_DIR DEADLINE_SECONDS SPEC...\n");
return 2;
}
for (int i = 4; i < argc && nplain < 64; i++) {
if (strncmp(argv[i], "at:", 3) != 0) {
plain[nplain++] = argv[i];
}
}
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
deadline = time(NULL) + atoi(argv[3]);
lfd = socket(AF_INET, SOCK_STREAM, 0);
if (lfd < 0 || setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) != 0) {
die("socket");
}
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(lfd, (struct sockaddr *)&addr, sizeof addr) != 0 || listen(lfd, 8) != 0 ||
getsockname(lfd, (struct sockaddr *)&addr, &alen) != 0) {
die("bind");
}
{
char tmp[1100];
(void)snprintf(tmp, sizeof tmp, "%s.tmp", argv[1]);
pf = fopen(tmp, "w");
if (!pf || fprintf(pf, "%d\n", ntohs(addr.sin_port)) < 0 || fclose(pf) != 0 || rename(tmp, argv[1]) != 0) {
die(argv[1]);
}
}
for (int k = 1, spec = 0; time(NULL) < deadline; k++) {
struct pollfd p = {lfd, POLLIN, 0};
char log_path[1100], path[512];
long counted;
int fd;
if (poll(&p, 1, 200) <= 0) {
k--;
continue;
}
fd = accept(lfd, NULL, NULL);
if (fd < 0) {
k--;
continue;
}
(void)snprintf(log_path, sizeof log_path, "%s/%d.req", argv[2], k);
counted = read_request(fd, log_path, path, sizeof path);
if (counted >= 0) {
char reply[160];
int n = snprintf(reply, sizeof reply, "{\"input_tokens\":%ld}", counted);
char head[160];
int h = snprintf(head, sizeof head,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nrequest-id: req_fake\r\n"
"Content-Length: %d\r\nConnection: close\r\n\r\n",
n);
(void)(send_all(fd, head, (size_t)h) || send_all(fd, reply, (size_t)n));
} else if ((routed = routed_spec(argc, argv, path))) {
/* its own process: a routed hang must not hold up the checks that arrive beside it */
pid_t pid = fork();
if (pid == 0) {
respond(fd, routed);
_exit(0);
}
} else if (nplain > 0) {
respond(fd, plain[spec < nplain ? spec : nplain - 1]);
spec++;
} else {
static const char none[] = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
(void)send_all(fd, none, sizeof none - 1);
}
close(fd);
}
return 0;
}