10 #include <sys/types.h>
16 /* If you increase this too far, you may run into file descriptor limits */
17 #define MAX_CHILDREN 256
19 typedef struct Child
{
31 typedef enum output_format
38 typedef struct State
{
42 bool convert_newlines
;
49 Child children
[MAX_CHILDREN
];
52 static bool spawn(const char *command
, char *const *args
, Child
*child
, int socket
)
54 int infds
[2], outfds
[2];
55 if (pipe(infds
) == -1 || pipe(outfds
) == -1) {
60 const pid_t pid
= fork();
74 setbuffer(stdin
, NULL
, 0);
75 setbuffer(stdout
, NULL
, 0);
78 snprintf(tlsenv
, 81, "TLS_CLIENT_HASH=%s", child
->owner
);
80 execvp(command
, args
);
88 child
->out
= outfds
[0];
89 setbuffer(fdopen(infds
[1], "w"), NULL
, 0);
90 setbuffer(fdopen(outfds
[0], "r"), NULL
, 0);
96 static bool write_all(int fd
, const char* buf
, int n
)
99 int w
= write(fd
, buf
, n
);
100 if (w
< 0) return false;
107 static void set_child_last_active(Child
*child
)
109 struct timespec clock_mono
;
110 clock_gettime(CLOCK_MONOTONIC
, &clock_mono
);
111 child
->last_active
= clock_mono
.tv_sec
;
114 /* Write anything written timelily on `in` to `out`,
115 * optionally converting \n to \r\n and space-stuffing gemini-magic lines.
116 * Return -1 on read error, 0 on HUP, else 1. */
117 static int stream_text(int in
, int out
,
118 bool convert_newlines
,
121 int read_timeout
, int pause_timeout
) {
123 struct pollfd pfd
= { in
, POLLIN
| POLLHUP
, 0 };
127 // TODO: timeouts should really be based on cpu time of child process, not
128 // wall clock time. This is particularly important for raw output, where
129 // an unfortunately timed sleep could lead to invalid responses.
131 /* Note we set no total maximum time or output size limit; we leave it to
132 * the user to e.g. set a ulimit to handle runaway processes. */
133 poll(&pfd
, 1, read_timeout
);
134 while (pfd
.revents
& POLLIN
) {
135 const int r
= read(in
, buf
, 256 - 1);
136 if (r
< 0) return false;
141 if ((escape_pre
|| escape_all
) && backticks
>= 0) {
145 if (backticks
== 3) {
146 write(out
, " ```", 4);
151 } else while (--backticks
>= 0) write(out
, "`", 1);
154 if (escape_all
&& escape
> 0) {
155 if (escape
== '\n') {
156 if (*b
== '#' || *b
== '>') {
158 } else if (*b
== '=' || *b
== '*') {
164 if ((escape
== '=' && *b
== '>')
165 || (escape
== '*' && *b
== ' ')) {
168 write(out
, &escape
, 1);
173 if (convert_newlines
&& *b
== '\n') {
174 write(out
, "\r\n", 2);
177 } else write(out
, b
, 1);
181 poll(&pfd
, 1, pause_timeout
);
183 while (--backticks
>= 0) write(out
, "`", 1);
184 if (escape
> 0 && escape
!= '\n') write(out
, &escape
, 1);
185 return (!(pfd
.revents
& POLLHUP
));
188 void respond(void *object
, const Request_Info
*request_info
, int socket
)
190 State
*state
= (State
*)object
;
192 #define put(s) write_all(socket, s, strlen(s))
194 if (!request_info
->tls_client_hash
) {
195 put("60 Client certificate required\r\n");
199 Child
*child
= NULL
, *slot
= NULL
;
200 bool spawned
= false;
202 /* Find child with this cert hash, or spawn new.
203 * For simplicity, we use a static array of children rather than
204 * allocating dynamically. This wastes a few KB of memory; you may want to
205 * rewrite this if memory is tight. We also don't bother to keep the list
206 * sorted, but just strcmp for each child. Terribly wasteful. */
207 for (int i
= 0; i
< state
->num_children
; ++i
) {
208 Child
*const c
= &state
->children
[i
];
210 if (0 == strncmp(c
->owner
,
211 request_info
->tls_client_hash
, 64)) {
216 if (slot
== NULL
|| (slot
->exists
217 && slot
->last_active
> c
->last_active
)) {
220 } else if (slot
== NULL
|| slot
->exists
) slot
= c
;
224 if (slot
== NULL
|| (slot
->exists
&& state
->num_children
< state
->max_children
)) {
225 slot
= &state
->children
[state
->num_children
++];
230 // TODO: would be nice to queue a regretful message for the owner
231 // of the child we're killing...
235 child
->exists
= false;
238 memset(child
, 0, sizeof(Child
));
240 if (request_info
->tls_client_hash
== NULL
) child
->owner
[0] = 0;
241 else strncpy(child
->owner
, request_info
->tls_client_hash
, 64);
243 if (!spawn(state
->command
, state
->args
, child
, socket
)) {
244 put("40 Spawn failure.\r\n");
248 set_child_last_active(child
);
249 child
->exists
= true;
254 const char *q
= request_info
->query_string_decoded
;
260 } else if (0 == strncmp(q
, "help", strlen(q
))) {
261 put("20 text/gemini\r\n");
262 put("An input line not beginning with '!' will be passed to the process.\r\n");
263 put("A newline will be appended unless the line ends with a trailing backslash.\r\n");
265 put("# gemrepl meta commands\r\n");
266 put("=> ?!help !help: This help\r\n");
267 put("=> ?!kill !kill: kill process (and start again)\r\n");
268 if (state
->format
!= raw
) {
269 put("=> ?!nolink !nolink: suppress input link\r\n");
270 put("=> ?!showlink !showlink: show input link\r\n");
271 put("=> ?!plain !plain: use text/plain for responses\r\n");
272 put("=> ?!gemtext !gemtext: use text/gemini for responses (default)\r\n");
274 put("=> ?!C !C: pass ^C (SIGINT) to process\r\n");
275 put("=> ?!? !?: Prompt for input\r\n");
276 put("=> ?!! !!: Literal '!'\r\n");
278 } else if (0 == strncmp(q
, "kill", strlen(q
))) {
279 kill(-child
->pid
, SIGKILL
);
281 } else if (0 == strncmp(q
, "C", strlen(q
))) {
282 kill(-child
->pid
, SIGINT
);
284 } else if (0 == strncmp(q
, "nolink", strlen(q
))) {
285 // TODO: might be better to have this be a permanent option
286 // attached to the cert rather than the child.
287 child
->nolink
= true;
288 put("20 text/gemini\r\n");
289 put("Input links disabled.\r\n");
290 put("=> ?!showlink Re-enable input links\r\n");
292 } else if (0 == strncmp(q
, "showlink", strlen(q
))) {
293 child
->nolink
= false;
294 put("20 text/gemini\r\n");
295 put("Input links enabled.\r\n");
296 put("=> ?!? Input command\r\n");
298 } else if (0 == strncmp(q
, "plain", strlen(q
))) {
300 put("20 text/gemini\r\n");
301 put("Plaintext mode enabled.\r\n");
302 put("=> ?!gemtext Re-enable gemtext\r\n");
304 } else if (0 == strncmp(q
, "gemtext", strlen(q
))) {
305 child
->plain
= false;
306 put("20 text/gemini\r\n");
307 put("Gemtext mode enabled.\r\n");
308 put("=> ?!? Input command\r\n");
310 } else if (*q
!= '!') {
311 put("40 Unknown gemrepl meta-command (use '!!' for a literal '!')\r\n");
316 if (state
->format
!= raw
) {
317 if (child
->plain
) put("20 text/plain\r\n");
318 else put("20 text/gemini\r\n");
321 put("[gemrepl child spawned. Input \"!help\" for meta-commands]\r\n");
324 if (!(child
->nolink
|| child
->plain
)) put("=> ?!? Input command\r\n");
327 if (!spawned
) kill(-child
->pid
, SIGCONT
);
329 int qlen
= strlen(q
);
330 if (!spawned
|| qlen
> 0) {
332 if (q
[qlen
-1] == '\\') {
336 signal(SIGPIPE
, SIG_IGN
);
337 bool succ
= (write(child
->in
, q
, qlen
) == qlen
338 && (!newline
|| write(child
->in
, "\n", 1) == 1));
339 signal(SIGPIPE
, SIG_DFL
);
341 put("[gemrepl: error when writing to child]\r\n");
345 if (state
->format
== pre
&& !child
->plain
) put("```\r\n");
346 const int succ
= stream_text(child
->out
, socket
,
347 state
->convert_newlines
,
348 state
->format
== pre
&& !child
->plain
,
349 state
->format
== unwrapped
&& !child
->plain
,
350 state
->read_timeout
, state
->pause_timeout
);
351 if (state
->format
== pre
&& !child
->plain
) put("\r\n```\r\n");
353 if (succ
< 0) put("[gemrepl: error when reading from child]\r\n");
354 else if (succ
== 0) {
355 // got HUP; sleep briefly to give child a chance to exit
359 set_child_last_active(child
);
361 if (waitpid(child
->pid
, NULL
, WNOHANG
) == child
->pid
) {
362 put("[gemrepl: child process terminated]");
365 child
->exists
= false;
367 kill(-child
->pid
, SIGSTOP
);
371 /* How long in ms to wait for child to output something */
372 #define DEF_READ_TIMEOUT 3000
374 /* How long in ms child can pause between writes before we consider it to have
375 * finished writing */
376 #define DEF_PAUSE_TIMEOUT 300
380 printf("Usage: gemrepl [OPTION]... -s PATH COMMAND [ARG]...\n");
381 printf(" -h --help This help\n");
382 printf(" -s PATH --socket=PATH Path for socket file, which will be created\n");
383 printf(" -m NUM --max-children=NUM Max concurrent children to spawn (%d)\n", MAX_CHILDREN
);
384 printf(" -t MS --read-timeout=MS Time to wait for child to start writing (%d)\n", DEF_READ_TIMEOUT
);
385 printf(" -T MS --pause-timeout=MS Silence period after which child is paused (%d)\n", DEF_PAUSE_TIMEOUT
);
386 printf(" -n --lf-crlf Convert \\n to \\r\\n (default unless --format=raw)\n");
387 printf(" -N --no-lf-crlf Preserve newlines\n");
388 printf(" -f FMT --format=FMT Format of output of command. Possible formats:\n");
389 printf(" gemtext: text/gemini (default)\n");
390 printf(" pre: preformatted text\n");
391 printf(" unwrapped: plain text without hard wrapping\n");
392 printf(" raw: gemini protocol output, including response headers\n");
396 int main(int argc
, char **argv
)
403 State
*state
= malloc(sizeof(State
));
405 fprintf(stderr
, "Failed to allocate memory for state.");
409 state
->max_children
= MAX_CHILDREN
;
410 state
->read_timeout
= DEF_READ_TIMEOUT
;
411 state
->pause_timeout
= DEF_PAUSE_TIMEOUT
;
412 state
->format
= gemtext
;
414 int convert_newlines
= -1;
416 const struct option longoptions
[] =
417 { { "help", 0, NULL
, 'h' }
418 , { "socket", 1, NULL
, 's' }
419 , { "format", 1, NULL
, 'f' }
420 , { "max-children", 1, NULL
, 'm' }
421 , { "read-timeout", 1, NULL
, 't' }
422 , { "pause-timeout", 1, NULL
, 'T' }
423 , { "lf-crlf", 0, NULL
, 'n' }
424 , { "no-lf-crlf", 0, NULL
, 'N' }
428 const char *socketname
= NULL
;
429 while (-1 != (o
= getopt_long(argc
, argv
, "+hs:f:m:t:T:nN", longoptions
, NULL
))) {
439 if (0 == strcmp(optarg
, "gemtext")) state
->format
=gemtext
;
440 else if (0 == strcmp(optarg
, "pre")) state
->format
=pre
;
441 else if (0 == strcmp(optarg
, "unwrapped")) state
->format
=unwrapped
;
442 else if (0 == strcmp(optarg
, "raw")) state
->format
=raw
;
444 printf("Unknown format.\n");
449 state
->max_children
= atoi(optarg
);
450 if (state
->max_children
<= 0 || state
->max_children
> MAX_CHILDREN
) {
451 printf("Bad value for max children.\n");
452 printf("You may need to increase MAX_CHILDREN in the source.\n");
457 state
->read_timeout
= atoi(optarg
);
458 if (state
->read_timeout
< 0) {
459 printf("Bad value for read timeout.\n");
464 state
->pause_timeout
= atoi(optarg
);
465 if (state
->pause_timeout
< 0) {
466 printf("Bad value for pause timeout.\n");
471 convert_newlines
= 1;
474 convert_newlines
= 0;
479 if (argv
[optind
] == NULL
|| socketname
== NULL
) {
484 state
->command
= argv
[optind
];
485 state
->args
= &argv
[optind
];
486 state
->convert_newlines
= convert_newlines
< 0 ? state
->format
!= raw
: convert_newlines
;
488 runSCGI(socketname
, respond
, state
);