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 int privsep_process;
37 static const struct option opts[] = {
38 {"help", no_argument, NULL, 'h'},
39 {"version", no_argument, NULL, 'V'},
40 {NULL, 0, NULL, 0},
41 };
43 void
44 log_request(struct client *c, int code, const char *meta)
45 {
46 char b[GEMINI_URL_LEN];
47 char cntmp[64], cn[64] = "-";
48 const char *t;
50 if (c->iri.schema != NULL) {
51 /* serialize the IRI */
52 strlcpy(b, c->iri.schema, sizeof(b));
53 strlcat(b, "://", sizeof(b));
55 /* log the decoded host name, but if it was invalid
56 * use the raw one. */
57 if (*c->domain != '\0')
58 strlcat(b, c->domain, sizeof(b));
59 else
60 strlcat(b, c->iri.host, sizeof(b));
62 if (*c->iri.path != '/')
63 strlcat(b, "/", sizeof(b));
64 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
65 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
66 strlcat(b, "?", sizeof(b));
67 strlcat(b, c->iri.query, sizeof(b));
68 }
69 } else {
70 if ((t = c->req) == NULL)
71 t = "";
72 strlcpy(b, t, sizeof(b));
73 }
75 if (tls_peer_cert_provided(c->ctx)) {
76 const char *subj;
77 char *n;
79 subj = tls_peer_cert_subject(c->ctx);
80 if ((n = strstr(subj, "/CN=")) != NULL) {
81 strlcpy(cntmp, subj + 4, sizeof(cntmp));
82 if ((n = strchr(cntmp, '/')) != NULL)
83 *n = '\0';
84 strnvis(cn, cntmp, sizeof(cn), VIS_WHITE|VIS_DQ);
85 }
86 }
88 fprintf(stderr, "%s %s %s %s %d %s\n", c->rhost, cn,
89 *c->domain == '\0' ? c->iri.host : c->domain, b, code, meta);
90 }
92 void
93 load_local_cert(struct vhost *h, const char *hostname, const char *dir)
94 {
95 char *cert, *key;
97 if (asprintf(&cert, "%s/%s.pem", dir, hostname) == -1)
98 fatal("asprintf");
99 if (asprintf(&key, "%s/%s.key", dir, hostname) == -1)
100 fatal("asprintf");
102 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
103 gen_certificate(hostname, cert, key);
105 h->cert = tls_load_file(cert, &h->certlen, NULL);
106 if (h->cert == NULL)
107 fatal("can't load %s", cert);
109 h->key = tls_load_file(key, &h->keylen, NULL);
110 if (h->key == NULL)
111 fatal("can't load %s", key);
113 strlcpy(h->domain, hostname, sizeof(h->domain));
116 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
117 static void
118 pdirname(const char *path, char *dn)
120 char p[PATH_MAX+1];
121 char *t;
123 strlcpy(p, path, sizeof(p));
124 t = dirname(p);
125 memmove(dn, t, strlen(t)+1);
128 static void
129 mkdirs(const char *path, mode_t mode)
131 char dname[PATH_MAX+1];
133 pdirname(path, dname);
134 if (!strcmp(dname, "/"))
135 return;
136 mkdirs(dname, mode);
137 if (mkdir(path, mode) != 0 && errno != EEXIST)
138 fatal("can't mkdir %s", path);
141 /* $XDG_DATA_HOME/gemexp */
142 char *
143 data_dir(void)
145 const char *home, *xdg;
146 char *t;
148 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
149 if ((home = getenv("HOME")) == NULL)
150 fatalx("XDG_DATA_HOME and HOME both empty");
151 if (asprintf(&t, "%s/.local/share/gemexp", home) == -1)
152 fatalx("asprintf");
153 } else {
154 if (asprintf(&t, "%s/gemexp", xdg) == -1)
155 fatal("asprintf");
158 mkdirs(t, 0755);
159 return t;
162 static int
163 serve(struct conf *conf, const char *host, int port, const char *dir)
165 struct addrinfo hints, *res, *res0;
166 struct vhost *vh = TAILQ_FIRST(&conf->hosts);
167 struct address *addr, *acp;
168 int r, error, saved_errno, sock = -1;
169 const char *cause = NULL;
170 char service[32];
171 int any = 0;
173 event_init();
175 r = snprintf(service, sizeof(service), "%d", port);
176 if (r < 0 || (size_t)r >= sizeof(service))
177 fatal("snprintf");
179 memset(&hints, 0, sizeof(hints));
180 hints.ai_family = AF_UNSPEC;
181 hints.ai_socktype = SOCK_STREAM;
182 hints.ai_flags = AI_PASSIVE;
183 error = getaddrinfo(host, service, &hints, &res0);
184 if (error)
185 fatalx("%s", gai_strerror(error));
186 for (res = res0; res; res = res->ai_next) {
187 sock = socket(res->ai_family, res->ai_socktype,
188 res->ai_protocol);
189 if (sock == -1) {
190 cause = "socket";
191 continue;
194 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
195 cause = "bind";
196 saved_errno = errno;
197 close(sock);
198 errno = saved_errno;
199 continue;
202 if (listen(sock, 5) == -1)
203 fatal("listen");
205 any = 1;
207 addr = xcalloc(1, sizeof(*addr));
208 addr->ai_flags = res->ai_flags;
209 addr->ai_family = res->ai_family;
210 addr->ai_socktype = res->ai_socktype;
211 addr->ai_protocol = res->ai_protocol;
212 addr->slen = res->ai_addrlen;
213 memcpy(&addr->ss, res->ai_addr, res->ai_addrlen);
215 addr->conf = conf;
216 addr->sock = sock;
217 event_set(&addr->evsock, addr->sock, EV_READ|EV_PERSIST,
218 server_accept, addr);
220 if ((addr->ctx = tls_server()) == NULL)
221 fatal("tls_server failure");
223 TAILQ_INSERT_HEAD(&conf->addrs, addr, addrs);
225 acp = xcalloc(1, sizeof(*acp));
226 memcpy(acp, addr, sizeof(*acp));
227 acp->sock = -1;
228 memset(&acp->evsock, 0, sizeof(acp->evsock));
229 TAILQ_INSERT_HEAD(&vh->addrs, addr, addrs);
232 if (!any)
233 fatal("%s", cause);
234 freeaddrinfo(res0);
236 server_init(NULL, NULL, NULL);
237 if (server_configure_done(conf) == -1)
238 fatalx("server configuration failed");
240 log_info("serving %s on port %d", dir, port);
241 event_dispatch();
242 log_info("quitting");
243 return 0;
246 static __dead void
247 usage(void)
249 fprintf(stderr,
250 "Version: " GE_STRING "\n"
251 "Usage: %s [-hV] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
252 getprogname());
253 exit(1);
256 int
257 main(int argc, char **argv)
259 struct conf *conf;
260 struct vhost *host;
261 struct location *loc;
262 const char *errstr, *certs_dir = NULL, *hostname = "localhost";
263 char path[PATH_MAX];
264 int ch, port = 1965;
266 setlocale(LC_CTYPE, "");
268 log_init(1, LOG_DAEMON);
269 log_setverbose(0);
270 conf = config_new();
272 /* ge doesn't do privsep so no privsep crypto engine. */
273 conf->use_privsep_crypto = 0;
275 while ((ch = getopt_long(argc, argv, "d:H:hp:V", opts, NULL)) != -1) {
276 switch (ch) {
277 case 'd':
278 certs_dir = optarg;
279 break;
280 case 'H':
281 hostname = optarg;
282 break;
283 case 'h':
284 usage();
285 break;
286 case 'p':
287 port = strtonum(optarg, 0, UINT16_MAX, &errstr);
288 if (errstr)
289 fatalx("port number is %s: %s", errstr,
290 optarg);
291 break;
292 case 'V':
293 puts("Version: " GE_STRING);
294 return 0;
295 default:
296 usage();
297 break;
300 argc -= optind;
301 argv += optind;
303 if (argc > 1)
304 usage();
306 /* prepare the configuration */
307 init_mime(&conf->mime);
309 if (certs_dir == NULL)
310 certs_dir = data_dir();
312 /* set up the implicit vhost and location */
313 host = xcalloc(1, sizeof(*host));
314 TAILQ_INSERT_HEAD(&conf->hosts, host, vhosts);
316 loc = xcalloc(1, sizeof(*loc));
317 loc->fcgi = -1;
318 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
320 load_local_cert(host, hostname, certs_dir);
322 strlcpy(host->domain, "*", sizeof(host->domain));
323 loc->auto_index = 1;
324 strlcpy(loc->match, "*", sizeof(loc->match));
326 if (*argv == NULL) {
327 if (getcwd(path, sizeof(path)) == NULL)
328 fatal("getcwd");
329 strlcpy(loc->dir, path, sizeof(loc->dir));
330 } else {
331 char *tmp;
333 tmp = absolutify_path(*argv);
334 strlcpy(loc->dir, tmp, sizeof(loc->dir));
335 free(tmp);
338 /* start the server */
339 signal(SIGPIPE, SIG_IGN);
340 setproctitle("%s", loc->dir);
341 return serve(conf, hostname, port, loc->dir);