Blob


1 /*
2 * Copyright (c) 2022, 2023 Omar Polo <op@omarpolo.com>
3 *
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.
7 *
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.
15 */
17 #include "gmid.h"
19 #include <sys/stat.h>
20 #include <sys/wait.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <getopt.h>
25 #include <locale.h>
26 #include <libgen.h>
27 #include <signal.h>
28 #include <string.h>
29 #include <syslog.h>
30 #include <unistd.h>
31 #include <vis.h>
33 #include "log.h"
35 static int gen_eckey = 1;
37 int privsep_process;
39 static const struct option opts[] = {
40 {"help", no_argument, NULL, 'h'},
41 {"version", no_argument, NULL, 'V'},
42 {NULL, 0, NULL, 0},
43 };
45 void
46 log_request(struct client *c, int code, const char *meta)
47 {
48 char b[GEMINI_URL_LEN];
49 char cntmp[64], cn[64] = "-";
50 const char *t;
52 if (c->iri.schema != NULL) {
53 /* serialize the IRI */
54 strlcpy(b, c->iri.schema, sizeof(b));
55 strlcat(b, "://", sizeof(b));
57 /* log the decoded host name, but if it was invalid
58 * use the raw one. */
59 if (*c->domain != '\0')
60 strlcat(b, c->domain, sizeof(b));
61 else
62 strlcat(b, c->iri.host, sizeof(b));
64 if (*c->iri.path != '/')
65 strlcat(b, "/", sizeof(b));
66 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
67 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
68 strlcat(b, "?", sizeof(b));
69 strlcat(b, c->iri.query, sizeof(b));
70 }
71 } else {
72 if ((t = c->req) == NULL)
73 t = "";
74 strlcpy(b, t, sizeof(b));
75 }
77 if (tls_peer_cert_provided(c->ctx)) {
78 const char *subj;
79 char *n;
81 subj = tls_peer_cert_subject(c->ctx);
82 if ((n = strstr(subj, "/CN=")) != NULL) {
83 strlcpy(cntmp, subj + 4, sizeof(cntmp));
84 if ((n = strchr(cntmp, '/')) != NULL)
85 *n = '\0';
86 strnvis(cn, cntmp, sizeof(cn), VIS_WHITE|VIS_DQ);
87 }
88 }
90 fprintf(stderr, "%s %s %s %s %d %s\n", c->rhost, cn,
91 *c->domain == '\0' ? c->iri.host : c->domain, b, code, meta);
92 }
94 void
95 load_local_cert(struct vhost *h, const char *hostname, const char *dir)
96 {
97 char *cert, *key;
99 if (asprintf(&cert, "%s/%s.pem", dir, hostname) == -1)
100 fatal("asprintf");
101 if (asprintf(&key, "%s/%s.key", dir, hostname) == -1)
102 fatal("asprintf");
104 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
105 gencert(hostname, cert, key, gen_eckey);
107 h->cert = tls_load_file(cert, &h->certlen, NULL);
108 if (h->cert == NULL)
109 fatal("can't load %s", cert);
111 h->key = tls_load_file(key, &h->keylen, NULL);
112 if (h->key == NULL)
113 fatal("can't load %s", key);
115 strlcpy(h->domain, hostname, sizeof(h->domain));
118 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
119 static void
120 pdirname(const char *path, char *dn)
122 char p[PATH_MAX+1];
123 char *t;
125 strlcpy(p, path, sizeof(p));
126 t = dirname(p);
127 memmove(dn, t, strlen(t)+1);
130 static void
131 mkdirs(const char *path, mode_t mode)
133 char dname[PATH_MAX+1];
135 pdirname(path, dname);
136 if (!strcmp(dname, "/"))
137 return;
138 mkdirs(dname, mode);
139 if (mkdir(path, mode) != 0 && errno != EEXIST)
140 fatal("can't mkdir %s", path);
143 /* $XDG_DATA_HOME/gemexp */
144 char *
145 data_dir(void)
147 const char *home, *xdg;
148 char *t;
150 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
151 if ((home = getenv("HOME")) == NULL)
152 fatalx("XDG_DATA_HOME and HOME both empty");
153 if (asprintf(&t, "%s/.local/share/gemexp", home) == -1)
154 fatalx("asprintf");
155 } else {
156 if (asprintf(&t, "%s/gemexp", xdg) == -1)
157 fatal("asprintf");
160 mkdirs(t, 0755);
161 return t;
164 static int
165 serve(struct conf *conf, const char *host, int port, const char *dir)
167 struct addrinfo hints, *res, *res0;
168 struct vhost *vh = TAILQ_FIRST(&conf->hosts);
169 struct address *addr, *acp;
170 int r, error, saved_errno, sock = -1;
171 const char *cause = NULL;
172 char service[32];
173 int any = 0;
175 event_init();
177 r = snprintf(service, sizeof(service), "%d", port);
178 if (r < 0 || (size_t)r >= sizeof(service))
179 fatal("snprintf");
181 memset(&hints, 0, sizeof(hints));
182 hints.ai_family = AF_UNSPEC;
183 hints.ai_socktype = SOCK_STREAM;
184 hints.ai_flags = AI_PASSIVE;
185 error = getaddrinfo(host, service, &hints, &res0);
186 if (error)
187 fatalx("%s", gai_strerror(error));
188 for (res = res0; res; res = res->ai_next) {
189 sock = socket(res->ai_family, res->ai_socktype,
190 res->ai_protocol);
191 if (sock == -1) {
192 cause = "socket";
193 continue;
196 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
197 cause = "bind";
198 saved_errno = errno;
199 close(sock);
200 errno = saved_errno;
201 continue;
204 if (listen(sock, 5) == -1)
205 fatal("listen");
207 any = 1;
209 addr = xcalloc(1, sizeof(*addr));
210 addr->ai_flags = res->ai_flags;
211 addr->ai_family = res->ai_family;
212 addr->ai_socktype = res->ai_socktype;
213 addr->ai_protocol = res->ai_protocol;
214 addr->slen = res->ai_addrlen;
215 memcpy(&addr->ss, res->ai_addr, res->ai_addrlen);
217 addr->conf = conf;
218 addr->sock = sock;
219 event_set(&addr->evsock, addr->sock, EV_READ|EV_PERSIST,
220 server_accept, addr);
222 if ((addr->ctx = tls_server()) == NULL)
223 fatal("tls_server failure");
225 TAILQ_INSERT_HEAD(&conf->addrs, addr, addrs);
227 acp = xcalloc(1, sizeof(*acp));
228 memcpy(acp, addr, sizeof(*acp));
229 acp->sock = -1;
230 memset(&acp->evsock, 0, sizeof(acp->evsock));
231 TAILQ_INSERT_HEAD(&vh->addrs, addr, addrs);
234 if (!any)
235 fatal("%s", cause);
236 freeaddrinfo(res0);
238 server_init(NULL, NULL, NULL);
239 if (server_configure_done(conf) == -1)
240 fatalx("server configuration failed");
242 log_info("serving %s on port %d", dir, port);
243 event_dispatch();
244 log_info("quitting");
245 return 0;
248 static __dead void
249 usage(void)
251 fprintf(stderr,
252 "Version: " GEMEXP_STRING "\n"
253 "Usage: %s [-hRV] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
254 getprogname());
255 exit(1);
258 int
259 main(int argc, char **argv)
261 struct conf *conf;
262 struct vhost *host;
263 struct location *loc;
264 const char *errstr, *certs_dir = NULL, *hostname = "localhost";
265 char path[PATH_MAX];
266 int ch, port = 1965;
268 setlocale(LC_CTYPE, "");
270 log_init(1, LOG_DAEMON);
271 log_setverbose(0);
272 conf = config_new();
274 /* ge doesn't do privsep so no privsep crypto engine. */
275 conf->use_privsep_crypto = 0;
277 while ((ch = getopt_long(argc, argv, "d:H:hp:RV", opts, NULL)) != -1) {
278 switch (ch) {
279 case 'd':
280 certs_dir = optarg;
281 break;
282 case 'H':
283 hostname = optarg;
284 break;
285 case 'h':
286 usage();
287 break;
288 case 'p':
289 port = strtonum(optarg, 0, UINT16_MAX, &errstr);
290 if (errstr)
291 fatalx("port number is %s: %s", errstr,
292 optarg);
293 break;
294 case 'R':
295 gen_eckey = 0;
296 break;
297 case 'V':
298 puts("Version: " GEMEXP_STRING);
299 return 0;
300 default:
301 usage();
302 break;
305 argc -= optind;
306 argv += optind;
308 if (argc > 1)
309 usage();
311 /* prepare the configuration */
312 init_mime(&conf->mime);
314 if (certs_dir == NULL)
315 certs_dir = data_dir();
317 /* set up the implicit vhost and location */
318 host = xcalloc(1, sizeof(*host));
319 TAILQ_INSERT_HEAD(&conf->hosts, host, vhosts);
321 loc = xcalloc(1, sizeof(*loc));
322 loc->fcgi = -1;
323 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
325 load_local_cert(host, hostname, certs_dir);
327 strlcpy(host->domain, "*", sizeof(host->domain));
328 loc->auto_index = 1;
329 strlcpy(loc->match, "*", sizeof(loc->match));
331 if (*argv == NULL) {
332 if (getcwd(path, sizeof(path)) == NULL)
333 fatal("getcwd");
334 strlcpy(loc->dir, path, sizeof(loc->dir));
335 } else {
336 char *tmp;
338 tmp = absolutify_path(*argv);
339 strlcpy(loc->dir, tmp, sizeof(loc->dir));
340 free(tmp);
343 /* start the server */
344 signal(SIGPIPE, SIG_IGN);
345 setproctitle("%s", loc->dir);
346 return serve(conf, hostname, port, loc->dir);