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 fnctl(child
->in
, F_SETFD
, FD_CLOEXEC
);
90 fnctl(child
->out
, F_SETFD
, FD_CLOEXEC
);
91 setbuffer(fdopen(infds
[1], "w"), NULL
, 0);
92 setbuffer(fdopen(outfds
[0], "r"), NULL
, 0);
98 static bool write_all(int fd
, const char* buf
, int n
)
101 int w
= write(fd
, buf
, n
);
102 if (w
< 0) return false;
109 static void set_child_last_active(Child
*child
)
111 struct timespec clock_mono
;
112 clock_gettime(CLOCK_MONOTONIC
, &clock_mono
);
113 child
->last_active
= clock_mono
.tv_sec
;
116 /* Write anything written timelily on `in` to `out`,
117 * optionally converting \n to \r\n and space-stuffing gemini-magic lines.
118 * Return -1 on read error, 0 on HUP, else 1. */
119 static int stream_text(int in
, int out
,
120 bool convert_newlines
,
123 int read_timeout
, int pause_timeout
) {
125 struct pollfd pfd
= { in
, POLLIN
| POLLHUP
, 0 };
129 // TODO: timeouts should really be based on cpu time of child process, not
130 // wall clock time. This is particularly important for raw output, where
131 // an unfortunately timed sleep could lead to invalid responses.
133 /* Note we set no total maximum time or output size limit; we leave it to
134 * the user to e.g. set a ulimit to handle runaway processes. */
135 poll(&pfd
, 1, read_timeout
);
136 while (pfd
.revents
& POLLIN
) {
137 const int r
= read(in
, buf
, 256 - 1);
138 if (r
< 0) return false;
143 if ((escape_pre
|| escape_all
) && backticks
>= 0) {
147 if (backticks
== 3) {
148 write(out
, " ```", 4);
153 } else while (--backticks
>= 0) write(out
, "`", 1);
156 if (escape_all
&& escape
> 0) {
157 if (escape
== '\n') {
158 if (*b
== '#' || *b
== '>') {
160 } else if (*b
== '=' || *b
== '*') {
166 if ((escape
== '=' && *b
== '>')
167 || (escape
== '*' && *b
== ' ')) {
170 write(out
, &escape
, 1);
175 if (convert_newlines
&& *b
== '\n') {
176 write(out
, "\r\n", 2);
179 } else write(out
, b
, 1);
183 poll(&pfd
, 1, pause_timeout
);
185 while (--backticks
>= 0) write(out
, "`", 1);
186 if (escape
> 0 && escape
!= '\n') write(out
, &escape
, 1);
187 return (!(pfd
.revents
& POLLHUP
));
190 void respond(void *object
, const Request_Info
*request_info
, int socket
)
192 State
*state
= (State
*)object
;
194 #define put(s) write_all(socket, s, strlen(s))
196 if (!request_info
->tls_client_hash
) {
197 put("60 Client certificate required\r\n");
201 Child
*child
= NULL
, *slot
= NULL
;
202 bool spawned
= false;
204 /* Find child with this cert hash, or spawn new.
205 * For simplicity, we use a static array of children rather than
206 * allocating dynamically. This wastes a few KB of memory; you may want to
207 * rewrite this if memory is tight. We also don't bother to keep the list
208 * sorted, but just strcmp for each child. Terribly wasteful. */
209 for (int i
= 0; i
< state
->num_children
; ++i
) {
210 Child
*const c
= &state
->children
[i
];
212 if (0 == strncmp(c
->owner
,
213 request_info
->tls_client_hash
, 64)) {
218 if (slot
== NULL
|| (slot
->exists
219 && slot
->last_active
> c
->last_active
)) {
222 } else if (slot
== NULL
|| slot
->exists
) slot
= c
;
226 if (slot
== NULL
|| (slot
->exists
&& state
->num_children
< state
->max_children
)) {
227 slot
= &state
->children
[state
->num_children
++];
232 // TODO: would be nice to queue a regretful message for the owner
233 // of the child we're killing...
237 child
->exists
= false;
240 memset(child
, 0, sizeof(Child
));
242 if (request_info
->tls_client_hash
== NULL
) child
->owner
[0] = 0;
243 else strncpy(child
->owner
, request_info
->tls_client_hash
, 64);
245 if (!spawn(state
->command
, state
->args
, child
, socket
)) {
246 put("40 Spawn failure.\r\n");
250 set_child_last_active(child
);
251 child
->exists
= true;
256 const char *q
= request_info
->query_string_decoded
;
262 } else if (0 == strncmp(q
, "help", strlen(q
))) {
263 put("20 text/gemini\r\n");
264 put("An input line not beginning with '!' will be passed to the process.\r\n");
265 put("A newline will be appended unless the line ends with a trailing backslash.\r\n");
267 put("# gemrepl meta commands\r\n");
268 put("=> ?!help !help: This help\r\n");
269 put("=> ?!kill !kill: kill process (and start again)\r\n");
270 if (state
->format
!= raw
) {
271 put("=> ?!nolink !nolink: suppress input link\r\n");
272 put("=> ?!showlink !showlink: show input link\r\n");
273 put("=> ?!plain !plain: use text/plain for responses\r\n");
274 put("=> ?!gemtext !gemtext: use text/gemini for responses (default)\r\n");
276 put("=> ?!C !C: pass ^C (SIGINT) to process\r\n");
277 put("=> ?!? !?: Prompt for input\r\n");
278 put("=> ?!! !!: Literal '!'\r\n");
280 } else if (0 == strncmp(q
, "kill", strlen(q
))) {
281 kill(-child
->pid
, SIGKILL
);
283 } else if (0 == strncmp(q
, "C", strlen(q
))) {
284 kill(-child
->pid
, SIGINT
);
286 } else if (0 == strncmp(q
, "nolink", strlen(q
))) {
287 // TODO: might be better to have this be a permanent option
288 // attached to the cert rather than the child.
289 child
->nolink
= true;
290 put("20 text/gemini\r\n");
291 put("Input links disabled.\r\n");
292 put("=> ?!showlink Re-enable input links\r\n");
294 } else if (0 == strncmp(q
, "showlink", strlen(q
))) {
295 child
->nolink
= false;
296 put("20 text/gemini\r\n");
297 put("Input links enabled.\r\n");
298 put("=> ?!? Input command\r\n");
300 } else if (0 == strncmp(q
, "plain", strlen(q
))) {
302 put("20 text/gemini\r\n");
303 put("Plaintext mode enabled.\r\n");
304 put("=> ?!gemtext Re-enable gemtext\r\n");
306 } else if (0 == strncmp(q
, "gemtext", strlen(q
))) {
307 child
->plain
= false;
308 put("20 text/gemini\r\n");
309 put("Gemtext mode enabled.\r\n");
310 put("=> ?!? Input command\r\n");
312 } else if (*q
!= '!') {
313 put("40 Unknown gemrepl meta-command (use '!!' for a literal '!')\r\n");
318 if (state
->format
!= raw
) {
319 if (child
->plain
) put("20 text/plain\r\n");
320 else put("20 text/gemini\r\n");
323 put("[gemrepl child spawned. Input \"!help\" for meta-commands]\r\n");
326 if (!(child
->nolink
|| child
->plain
)) put("=> ?!? Input command\r\n");
329 if (!spawned
) kill(-child
->pid
, SIGCONT
);
331 int qlen
= strlen(q
);
332 if (!spawned
|| qlen
> 0) {
334 if (q
[qlen
-1] == '\\') {
338 signal(SIGPIPE
, SIG_IGN
);
339 bool succ
= (write(child
->in
, q
, qlen
) == qlen
340 && (!newline
|| write(child
->in
, "\n", 1) == 1));
341 signal(SIGPIPE
, SIG_DFL
);
343 put("[gemrepl: error when writing to child]\r\n");
347 if (state
->format
== pre
&& !child
->plain
) put("```\r\n");
348 const int succ
= stream_text(child
->out
, socket
,
349 state
->convert_newlines
,
350 state
->format
== pre
&& !child
->plain
,
351 state
->format
== unwrapped
&& !child
->plain
,
352 state
->read_timeout
, state
->pause_timeout
);
353 if (state
->format
== pre
&& !child
->plain
) put("\r\n```\r\n");
355 if (succ
< 0) put("[gemrepl: error when reading from child]\r\n");
356 else if (succ
== 0) {
357 // got HUP; sleep briefly to give child a chance to exit
361 set_child_last_active(child
);
363 if (waitpid(child
->pid
, NULL
, WNOHANG
) == child
->pid
) {
364 put("[gemrepl: child process terminated]");
367 child
->exists
= false;
369 kill(-child
->pid
, SIGSTOP
);
373 /* How long in ms to wait for child to output something */
374 #define DEF_READ_TIMEOUT 3000
376 /* How long in ms child can pause between writes before we consider it to have
377 * finished writing */
378 #define DEF_PAUSE_TIMEOUT 300
382 printf("Usage: gemrepl [OPTION]... -s PATH COMMAND [ARG]...\n");
383 printf(" -h --help This help\n");
384 printf(" -s PATH --socket=PATH Path for socket file, which will be created\n");
385 printf(" -m NUM --max-children=NUM Max concurrent children to spawn (%d)\n", MAX_CHILDREN
);
386 printf(" -t MS --read-timeout=MS Time to wait for child to start writing (%d)\n", DEF_READ_TIMEOUT
);
387 printf(" -T MS --pause-timeout=MS Silence period after which child is paused (%d)\n", DEF_PAUSE_TIMEOUT
);
388 printf(" -n --lf-crlf Convert \\n to \\r\\n (default unless --format=raw)\n");
389 printf(" -N --no-lf-crlf Preserve newlines\n");
390 printf(" -f FMT --format=FMT Format of output of command. Possible formats:\n");
391 printf(" gemtext: text/gemini (default)\n");
392 printf(" pre: preformatted text\n");
393 printf(" unwrapped: plain text without hard wrapping\n");
394 printf(" raw: gemini protocol output, including response headers\n");
398 int main(int argc
, char **argv
)
405 State
*state
= malloc(sizeof(State
));
407 fprintf(stderr
, "Failed to allocate memory for state.");
411 state
->max_children
= MAX_CHILDREN
;
412 state
->read_timeout
= DEF_READ_TIMEOUT
;
413 state
->pause_timeout
= DEF_PAUSE_TIMEOUT
;
414 state
->format
= gemtext
;
416 int convert_newlines
= -1;
418 const struct option longoptions
[] =
419 { { "help", 0, NULL
, 'h' }
420 , { "socket", 1, NULL
, 's' }
421 , { "format", 1, NULL
, 'f' }
422 , { "max-children", 1, NULL
, 'm' }
423 , { "read-timeout", 1, NULL
, 't' }
424 , { "pause-timeout", 1, NULL
, 'T' }
425 , { "lf-crlf", 0, NULL
, 'n' }
426 , { "no-lf-crlf", 0, NULL
, 'N' }
430 const char *socketname
= NULL
;
431 while (-1 != (o
= getopt_long(argc
, argv
, "+hs:f:m:t:T:nN", longoptions
, NULL
))) {
441 if (0 == strcmp(optarg
, "gemtext")) state
->format
=gemtext
;
442 else if (0 == strcmp(optarg
, "pre")) state
->format
=pre
;
443 else if (0 == strcmp(optarg
, "unwrapped")) state
->format
=unwrapped
;
444 else if (0 == strcmp(optarg
, "raw")) state
->format
=raw
;
446 printf("Unknown format.\n");
451 state
->max_children
= atoi(optarg
);
452 if (state
->max_children
<= 0 || state
->max_children
> MAX_CHILDREN
) {
453 printf("Bad value for max children.\n");
454 printf("You may need to increase MAX_CHILDREN in the source.\n");
459 state
->read_timeout
= atoi(optarg
);
460 if (state
->read_timeout
< 0) {
461 printf("Bad value for read timeout.\n");
466 state
->pause_timeout
= atoi(optarg
);
467 if (state
->pause_timeout
< 0) {
468 printf("Bad value for pause timeout.\n");
473 convert_newlines
= 1;
476 convert_newlines
= 0;
481 if (argv
[optind
] == NULL
|| socketname
== NULL
) {
486 state
->command
= argv
[optind
];
487 state
->args
= &argv
[optind
];
488 state
->convert_newlines
= convert_newlines
< 0 ? state
->format
!= raw
: convert_newlines
;
490 runSCGI(socketname
, respond
, state
);