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 int privsep_process;
36 static const struct option opts[] = {
37 {"help", no_argument, NULL, 'h'},
38 {"version", no_argument, NULL, 'V'},
39 {NULL, 0, NULL, 0},
40 };
42 void
43 log_request(struct client *c, char *meta, size_t l)
44 {
45 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
46 const char *t;
47 int ec;
49 ec = getnameinfo((struct sockaddr*)&c->raddr, c->raddrlen,
50 hbuf, sizeof(hbuf),
51 sbuf, sizeof(sbuf),
52 NI_NUMERICHOST | NI_NUMERICSERV);
53 if (ec != 0)
54 fatalx("getnameinfo: %s", gai_strerror(ec));
56 if (c->iri.schema != NULL) {
57 /* serialize the IRI */
58 strlcpy(b, c->iri.schema, sizeof(b));
59 strlcat(b, "://", sizeof(b));
61 /* log the decoded host name, but if it was invalid
62 * use the raw one. */
63 if (*c->domain != '\0')
64 strlcat(b, c->domain, sizeof(b));
65 else
66 strlcat(b, c->iri.host, sizeof(b));
68 if (*c->iri.path != '/')
69 strlcat(b, "/", sizeof(b));
70 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
71 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
72 strlcat(b, "?", sizeof(b));
73 strlcat(b, c->iri.query, sizeof(b));
74 }
75 } else {
76 if ((t = c->req) == NULL)
77 t = "";
78 strlcpy(b, t, sizeof(b));
79 }
81 if ((t = memchr(meta, '\r', l)) == NULL)
82 t = meta + l;
84 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
85 (int)(t-meta), meta);
86 }
88 void
89 load_local_cert(struct vhost *h, const char *hostname, const char *dir)
90 {
91 char *cert, *key;
93 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
94 fatal("asprintf");
95 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
96 fatal("asprintf");
98 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
99 gen_certificate(hostname, cert, key);
101 h->cert = tls_load_file(cert, &h->certlen, NULL);
102 if (h->cert == NULL)
103 fatal("can't load %s", cert);
105 h->key = tls_load_file(key, &h->keylen, NULL);
106 if (h->key == NULL)
107 fatal("can't load %s", key);
109 strlcpy(h->domain, hostname, sizeof(h->domain));
112 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
113 static void
114 pdirname(const char *path, char *dn)
116 char p[PATH_MAX+1];
117 char *t;
119 strlcpy(p, path, sizeof(p));
120 t = dirname(p);
121 memmove(dn, t, strlen(t)+1);
124 static void
125 mkdirs(const char *path, mode_t mode)
127 char dname[PATH_MAX+1];
129 pdirname(path, dname);
130 if (!strcmp(dname, "/"))
131 return;
132 mkdirs(dname, mode);
133 if (mkdir(path, mode) != 0 && errno != EEXIST)
134 fatal("can't mkdir %s", path);
137 /* $XDG_DATA_HOME/gmid */
138 char *
139 data_dir(void)
141 const char *home, *xdg;
142 char *t;
144 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
145 if ((home = getenv("HOME")) == NULL)
146 fatalx("XDG_DATA_HOME and HOME both empty");
147 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
148 fatalx("asprintf");
149 } else {
150 if (asprintf(&t, "%s/gmid", xdg) == -1)
151 fatal("asprintf");
154 mkdirs(t, 0755);
155 return t;
158 static int
159 serve(struct conf *conf, const char *host, int port, const char *dir)
161 struct addrinfo hints, *res, *res0;
162 struct vhost *vh = TAILQ_FIRST(&conf->hosts);
163 struct address *addr, *acp;
164 int r, error, saved_errno, sock = -1;
165 const char *cause = NULL;
166 char service[32];
167 int any = 0;
169 event_init();
171 r = snprintf(service, sizeof(service), "%d", port);
172 if (r < 0 || (size_t)r >= sizeof(service))
173 fatal("snprintf");
175 memset(&hints, 0, sizeof(hints));
176 hints.ai_family = AF_UNSPEC;
177 hints.ai_socktype = SOCK_STREAM;
178 hints.ai_flags = AI_PASSIVE;
179 error = getaddrinfo(host, service, &hints, &res0);
180 if (error)
181 fatalx("%s", gai_strerror(error));
182 for (res = res0; res; res = res->ai_next) {
183 sock = socket(res->ai_family, res->ai_socktype,
184 res->ai_protocol);
185 if (sock == -1) {
186 cause = "socket";
187 continue;
190 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
191 cause = "bind";
192 saved_errno = errno;
193 close(sock);
194 errno = saved_errno;
195 continue;
198 if (listen(sock, 5) == -1)
199 fatal("listen");
201 any = 1;
203 addr = xcalloc(1, sizeof(*addr));
204 addr->ai_flags = res->ai_flags;
205 addr->ai_family = res->ai_family;
206 addr->ai_socktype = res->ai_socktype;
207 addr->ai_protocol = res->ai_protocol;
208 addr->slen = res->ai_addrlen;
209 memcpy(&addr->ss, res->ai_addr, res->ai_addrlen);
211 addr->conf = conf;
212 addr->sock = sock;
213 event_set(&addr->evsock, addr->sock, EV_READ|EV_PERSIST,
214 do_accept, addr);
216 TAILQ_INSERT_HEAD(&conf->addrs, addr, addrs);
218 acp = xcalloc(1, sizeof(*acp));
219 memcpy(acp, addr, sizeof(*acp));
220 acp->sock = -1;
221 memset(&acp->evsock, 0, sizeof(acp->evsock));
222 TAILQ_INSERT_HEAD(&vh->addrs, addr, addrs);
225 if (!any)
226 fatal("%s", cause);
227 freeaddrinfo(res0);
229 server_init(NULL, NULL, NULL);
230 if (server_configure_done(conf) == -1)
231 fatalx("server configuration failed");
233 log_info("serving %s on port %d", dir, port);
234 event_dispatch();
235 log_info("quitting");
236 return 0;
239 static __dead void
240 usage(void)
242 fprintf(stderr,
243 "Version: " GE_STRING "\n"
244 "Usage: %s [-hVv] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
245 getprogname());
246 exit(1);
249 int
250 main(int argc, char **argv)
252 struct conf *conf;
253 struct vhost *host;
254 struct location *loc;
255 const char *errstr, *certs_dir = NULL, *hostname = "localhost";
256 char path[PATH_MAX];
257 int ch, port = 1965;
259 setlocale(LC_CTYPE, "");
261 log_init(1, LOG_DAEMON);
262 log_setverbose(0);
263 conf = config_new();
265 /* ge doesn't do privsep so no privsep crypto engine. */
266 conf->use_privsep_crypto = 0;
268 while ((ch = getopt_long(argc, argv, "d:H:hp:Vv", opts, NULL)) != -1) {
269 switch (ch) {
270 case 'd':
271 certs_dir = optarg;
272 break;
273 case 'H':
274 hostname = optarg;
275 break;
276 case 'h':
277 usage();
278 break;
279 case 'p':
280 port = strtonum(optarg, 0, UINT16_MAX, &errstr);
281 if (errstr)
282 fatalx("port number is %s: %s", errstr,
283 optarg);
284 break;
285 case 'V':
286 puts("Version: " GE_STRING);
287 return 0;
288 default:
289 usage();
290 break;
293 argc -= optind;
294 argv += optind;
296 if (argc > 1)
297 usage();
299 /* prepare the configuration */
300 init_mime(&conf->mime);
302 if (certs_dir == NULL)
303 certs_dir = data_dir();
305 /* set up the implicit vhost and location */
306 host = xcalloc(1, sizeof(*host));
307 TAILQ_INSERT_HEAD(&conf->hosts, host, vhosts);
309 loc = xcalloc(1, sizeof(*loc));
310 loc->fcgi = -1;
311 TAILQ_INSERT_HEAD(&host->locations, loc, locations);
313 load_local_cert(host, hostname, certs_dir);
315 strlcpy(host->domain, "*", sizeof(host->domain));
316 loc->auto_index = 1;
317 strlcpy(loc->match, "*", sizeof(loc->match));
319 if (*argv == NULL) {
320 if (getcwd(path, sizeof(path)) == NULL)
321 fatal("getcwd");
322 strlcpy(loc->dir, path, sizeof(loc->dir));
323 } else {
324 char *tmp;
326 tmp = absolutify_path(*argv);
327 strlcpy(loc->dir, tmp, sizeof(loc->dir));
328 free(tmp);
331 /* start the server */
332 signal(SIGPIPE, SIG_IGN);
333 setproctitle("%s", loc->dir);
334 return serve(conf, hostname, port, loc->dir);