Blob


1 /*
2 * Copyright (c) 2022 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>
32 #include "log.h"
34 struct conf conf;
35 int privsep_process;
37 struct fcgi fcgi[FCGI_MAX]; /* just because it's referenced */
38 struct vhosthead hosts = TAILQ_HEAD_INITIALIZER(hosts);
40 static const struct option opts[] = {
41 {"help", no_argument, NULL, 'h'},
42 {"version", no_argument, NULL, 'V'},
43 {NULL, 0, NULL, 0},
44 };
46 void
47 log_request(struct client *c, char *meta, size_t l)
48 {
49 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
50 const char *t;
51 size_t len;
52 int ec;
54 len = sizeof(c->addr);
55 ec = getnameinfo((struct sockaddr*)&c->addr, len,
56 hbuf, sizeof(hbuf),
57 sbuf, sizeof(sbuf),
58 NI_NUMERICHOST | NI_NUMERICSERV);
59 if (ec != 0)
60 fatalx("getnameinfo: %s", gai_strerror(ec));
62 if (c->iri.schema != NULL) {
63 /* serialize the IRI */
64 strlcpy(b, c->iri.schema, sizeof(b));
65 strlcat(b, "://", sizeof(b));
67 /* log the decoded host name, but if it was invalid
68 * use the raw one. */
69 if (*c->domain != '\0')
70 strlcat(b, c->domain, sizeof(b));
71 else
72 strlcat(b, c->iri.host, sizeof(b));
74 if (*c->iri.path != '/')
75 strlcat(b, "/", sizeof(b));
76 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
77 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
78 strlcat(b, "?", sizeof(b));
79 strlcat(b, c->iri.query, sizeof(b));
80 }
81 } else {
82 if ((t = c->req) == NULL)
83 t = "";
84 strlcpy(b, t, sizeof(b));
85 }
87 if ((t = memchr(meta, '\r', l)) == NULL)
88 t = meta + len;
90 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
91 (int)(t-meta), 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.cert.pem", dir, hostname) == -1)
100 fatal("asprintf");
101 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
102 fatal("asprintf");
104 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
105 gen_certificate(hostname, cert, key);
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/gmid */
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/gmid", home) == -1)
154 fatalx("asprintf");
155 } else {
156 if (asprintf(&t, "%s/gmid", xdg) == -1)
157 fatal("asprintf");
160 mkdirs(t, 0755);
161 return t;
164 static int
165 serve(const char *host, int port, const char *dir)
167 struct addrinfo hints, *res, *res0;
168 int r, error, saved_errno, sock = -1;
169 const char *cause = NULL;
170 char service[32];
172 r = snprintf(service, sizeof(service), "%d", port);
173 if (r < 0 || (size_t)r >= sizeof(service))
174 fatal("snprintf");
176 memset(&hints, 0, sizeof(hints));
177 hints.ai_family = AF_UNSPEC;
178 hints.ai_socktype = SOCK_STREAM;
179 hints.ai_flags = AI_PASSIVE;
180 error = getaddrinfo(host, service, &hints, &res0);
181 if (error)
182 fatalx("%s", gai_strerror(error));
183 for (res = res0; res; res = res->ai_next) {
184 sock = socket(res->ai_family, res->ai_socktype,
185 res->ai_protocol);
186 if (sock == -1) {
187 cause = "socket";
188 continue;
191 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
192 cause = "bind";
193 saved_errno = errno;
194 close(sock);
195 errno = saved_errno;
196 continue;
199 if (listen(sock, 5) == -1)
200 fatal("listen");
202 /*
203 * for the time being, we're happy as soon as
204 * something binds.
205 */
206 break;
209 if (sock == -1)
210 fatal("%s", cause);
211 freeaddrinfo(res0);
213 event_init();
215 /* cheating */
216 conf.sock4 = sock;
217 event_set(&conf.evsock4, conf.sock4, EV_READ|EV_PERSIST,
218 do_accept, NULL);
220 server_init(NULL, NULL, NULL);
221 if (server_configure_done(&conf) == -1)
222 fatalx("server configuration failed");
224 log_info("serving %s on port %d", dir, port);
225 event_dispatch();
226 log_info("quitting");
227 return 0;
230 static __dead void
231 usage(void)
233 fprintf(stderr,
234 "Version: " GE_STRING "\n"
235 "Usage: %s [-hVv] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
236 getprogname());
237 exit(1);
240 int
241 main(int argc, char **argv)
243 struct vhost *host;
244 struct location *loc;
245 const char *errstr, *certs_dir = NULL, *hostname = "localhost";
246 char path[PATH_MAX];
247 int ch;
249 setlocale(LC_CTYPE, "");
251 log_init(1, LOG_DAEMON);
252 log_setverbose(0);
253 config_init();
255 while ((ch = getopt_long(argc, argv, "d:H:hp:Vv", opts, NULL)) != -1) {
256 switch (ch) {
257 case 'd':
258 certs_dir = optarg;
259 break;
260 case 'H':
261 hostname = optarg;
262 break;
263 case 'h':
264 usage();
265 break;
266 case 'p':
267 conf.port = strtonum(optarg, 0, UINT16_MAX, &errstr);
268 if (errstr)
269 fatalx("port number is %s: %s", errstr,
270 optarg);
271 break;
272 case 'V':
273 puts("Version: " GE_STRING);
274 return 0;
275 default:
276 usage();
277 break;
280 argc -= optind;
281 argv += optind;
283 if (argc > 1)
284 usage();
286 /* prepare the configuration */
287 init_mime(&conf.mime);
289 if (certs_dir == NULL)
290 certs_dir = data_dir();
292 /* set up the implicit vhost and location */
293 host = xcalloc(1, sizeof(*host));
294 TAILQ_INSERT_HEAD(&hosts, host, vhosts);
296 loc = xcalloc(1, sizeof(*loc));
297 loc->fcgi = -1;
298 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
300 load_local_cert(host, hostname, certs_dir);
302 strlcpy(host->domain, "*", sizeof(host->domain));
303 loc->auto_index = 1;
304 strlcpy(loc->match, "*", sizeof(loc->match));
306 if (*argv == NULL) {
307 if (getcwd(path, sizeof(path)) == NULL)
308 fatal("getcwd");
309 strlcpy(loc->dir, path, sizeof(loc->dir));
310 } else {
311 char *tmp;
313 tmp = absolutify_path(*argv);
314 strlcpy(loc->dir, tmp, sizeof(loc->dir));
315 free(tmp);
318 /* start the server */
319 signal(SIGPIPE, SIG_IGN);
320 setproctitle("%s", loc->dir);
321 return serve(hostname, conf.port, loc->dir);