2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 * Test program for fastcgi. It speaks the protocol over stdin.
19 * Can't handle more than one request at the same time.
22 #include "../config.h"
30 #define FCGI_VERSION_1 1
32 /* subset of records that matters to us */
33 #define FCGI_BEGIN_REQUEST 1
34 #define FCGI_END_REQUEST 3
39 #define SUM(a, b) (((a) << 8) + (b))
52 struct fcgi_end_req_body {
53 unsigned char app_status3;
54 unsigned char app_status2;
55 unsigned char app_status1;
56 unsigned char app_status0;
57 unsigned char proto_status;
58 unsigned char reserved[3];
62 prepare_header(struct fcgi_header *h, int type, int id, size_t size,
65 memset(h, 0, sizeof(*h));
67 h->version = FCGI_VERSION_1;
69 h->req_id1 = (id >> 8);
70 h->req_id0 = (id & 0xFF);
71 h->content_len1 = (size >> 8);
72 h->content_len0 = (size & 0xFF);
79 must_read(int sock, void *d, size_t len)
84 switch (r = read(sock, d, len)) {
89 if (r == (ssize_t)len)
98 consume(int fd, size_t len)
104 if ((l = len) > sizeof(buf))
106 if (must_read(fd, buf, l) == -1)
115 read_header(struct fcgi_header *hdr)
117 if (must_read(0, hdr, sizeof(*hdr)) == -1)
121 /* read and consume a record of the given type */
123 assert_record(int type)
125 struct fcgi_header hdr;
129 if (hdr.type != type)
130 errx(1, "expected record type %d; got %d",
133 consume(0, SUM(hdr.content_len1, hdr.content_len0));
134 consume(0, hdr.padding);
140 struct fcgi_header hdr;
141 struct fcgi_end_req_body end;
145 msg = "20 text/gemini\r\n# Hello, world!\n";
149 warnx("waiting for a request");
150 assert_record(FCGI_BEGIN_REQUEST);
156 consume(0, SUM(hdr.content_len1, hdr.content_len0));
157 consume(0, hdr.padding);
159 if (hdr.type != FCGI_PARAMS)
160 errx(1, "got %d; expecting PARAMS", hdr.type);
162 if (hdr.content_len0 == 0 &&
163 hdr.content_len1 == 0 &&
168 assert_record(FCGI_STDIN);
170 warnx("sending the response");
172 prepare_header(&hdr, FCGI_STDOUT, 1, len, 0);
173 write(0, &hdr, sizeof(hdr));
176 warnx("closing the request");
178 prepare_header(&hdr, FCGI_END_REQUEST, 1, sizeof(end), 0);
179 write(0, &hdr, sizeof(hdr));
180 memset(&end, 0, sizeof(end));
181 write(0, &end, sizeof(end));