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"
29 #define FCGI_VERSION_1 1
31 /* subset of records that matters to us */
32 #define FCGI_BEGIN_REQUEST 1
33 #define FCGI_END_REQUEST 3
38 #define SUM(a, b) (((a) << 8) + (b))
51 struct fcgi_end_req_body {
52 unsigned char app_status3;
53 unsigned char app_status2;
54 unsigned char app_status1;
55 unsigned char app_status0;
56 unsigned char proto_status;
57 unsigned char reserved[3];
61 prepare_header(struct fcgi_header *h, int type, int id, size_t size,
64 memset(h, 0, sizeof(*h));
66 h->version = FCGI_VERSION_1;
68 h->req_id1 = (id >> 8);
69 h->req_id0 = (id & 0xFF);
70 h->content_len1 = (size >> 8);
71 h->content_len0 = (size & 0xFF);
78 must_read(int sock, void *d, size_t len)
83 switch (r = read(sock, d, len)) {
88 if (r == (ssize_t)len)
97 consume(int fd, size_t len)
103 if ((l = len) > sizeof(buf))
105 if (must_read(fd, buf, l) == -1)
114 read_header(struct fcgi_header *hdr)
116 if (must_read(0, hdr, sizeof(*hdr)) == -1)
117 errx(1, "must_read failed");
120 /* read and consume a record of the given type */
122 assert_record(int type)
124 struct fcgi_header hdr;
128 if (hdr.type != type)
129 errx(1, "expected record type %d; got %d",
132 consume(0, SUM(hdr.content_len1, hdr.content_len0));
133 consume(0, hdr.padding);
139 struct fcgi_header hdr;
140 struct fcgi_end_req_body end;
144 msg = "20 text/gemini\r\n# Hello, world!\n";
148 warnx("waiting for a request");
149 assert_record(FCGI_BEGIN_REQUEST);
155 consume(0, SUM(hdr.content_len1, hdr.content_len0));
156 consume(0, hdr.padding);
158 if (hdr.type != FCGI_PARAMS)
159 errx(1, "got %d; expecting PARAMS", hdr.type);
161 if (hdr.content_len0 == 0 &&
162 hdr.content_len1 == 0 &&
167 assert_record(FCGI_STDIN);
169 warnx("sending the response");
171 prepare_header(&hdr, FCGI_STDOUT, 1, len, 0);
172 write(0, &hdr, sizeof(hdr));
175 warnx("closing the request");
177 prepare_header(&hdr, FCGI_END_REQUEST, 1, sizeof(end), 0);
178 write(0, &hdr, sizeof(hdr));
179 memset(&end, 0, sizeof(end));
180 write(0, &end, sizeof(end));