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 size_t len;
48 int ec;
50 len = sizeof(c->addr);
51 ec = getnameinfo((struct sockaddr*)&c->addr, len,
52 hbuf, sizeof(hbuf),
53 sbuf, sizeof(sbuf),
54 NI_NUMERICHOST | NI_NUMERICSERV);
55 if (ec != 0)
56 fatalx("getnameinfo: %s", gai_strerror(ec));
58 if (c->iri.schema != NULL) {
59 /* serialize the IRI */
60 strlcpy(b, c->iri.schema, sizeof(b));
61 strlcat(b, "://", sizeof(b));
63 /* log the decoded host name, but if it was invalid
64 * use the raw one. */
65 if (*c->domain != '\0')
66 strlcat(b, c->domain, sizeof(b));
67 else
68 strlcat(b, c->iri.host, sizeof(b));
70 if (*c->iri.path != '/')
71 strlcat(b, "/", sizeof(b));
72 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
73 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
74 strlcat(b, "?", sizeof(b));
75 strlcat(b, c->iri.query, sizeof(b));
76 }
77 } else {
78 if ((t = c->req) == NULL)
79 t = "";
80 strlcpy(b, t, sizeof(b));
81 }
83 if ((t = memchr(meta, '\r', l)) == NULL)
84 t = meta + len;
86 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
87 (int)(t-meta), meta);
88 }
90 void
91 load_local_cert(struct vhost *h, const char *hostname, const char *dir)
92 {
93 char *cert, *key;
95 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
96 fatal("asprintf");
97 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
98 fatal("asprintf");
100 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
101 gen_certificate(hostname, cert, key);
103 h->cert = tls_load_file(cert, &h->certlen, NULL);
104 if (h->cert == NULL)
105 fatal("can't load %s", cert);
107 h->key = tls_load_file(key, &h->keylen, NULL);
108 if (h->key == NULL)
109 fatal("can't load %s", key);
111 strlcpy(h->domain, hostname, sizeof(h->domain));
114 /* wrapper around dirname(3). dn must be PATH_MAX+1 at least. */
115 static void
116 pdirname(const char *path, char *dn)
118 char p[PATH_MAX+1];
119 char *t;
121 strlcpy(p, path, sizeof(p));
122 t = dirname(p);
123 memmove(dn, t, strlen(t)+1);
126 static void
127 mkdirs(const char *path, mode_t mode)
129 char dname[PATH_MAX+1];
131 pdirname(path, dname);
132 if (!strcmp(dname, "/"))
133 return;
134 mkdirs(dname, mode);
135 if (mkdir(path, mode) != 0 && errno != EEXIST)
136 fatal("can't mkdir %s", path);
139 /* $XDG_DATA_HOME/gmid */
140 char *
141 data_dir(void)
143 const char *home, *xdg;
144 char *t;
146 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
147 if ((home = getenv("HOME")) == NULL)
148 fatalx("XDG_DATA_HOME and HOME both empty");
149 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
150 fatalx("asprintf");
151 } else {
152 if (asprintf(&t, "%s/gmid", xdg) == -1)
153 fatal("asprintf");
156 mkdirs(t, 0755);
157 return t;
160 static int
161 serve(struct conf *conf, const char *host, int port, const char *dir)
163 struct addrinfo hints, *res, *res0;
164 int r, error, saved_errno, sock = -1;
165 const char *cause = NULL;
166 char service[32];
168 r = snprintf(service, sizeof(service), "%d", port);
169 if (r < 0 || (size_t)r >= sizeof(service))
170 fatal("snprintf");
172 memset(&hints, 0, sizeof(hints));
173 hints.ai_family = AF_UNSPEC;
174 hints.ai_socktype = SOCK_STREAM;
175 hints.ai_flags = AI_PASSIVE;
176 error = getaddrinfo(host, service, &hints, &res0);
177 if (error)
178 fatalx("%s", gai_strerror(error));
179 for (res = res0; res; res = res->ai_next) {
180 sock = socket(res->ai_family, res->ai_socktype,
181 res->ai_protocol);
182 if (sock == -1) {
183 cause = "socket";
184 continue;
187 if (bind(sock, res->ai_addr, res->ai_addrlen) == -1) {
188 cause = "bind";
189 saved_errno = errno;
190 close(sock);
191 errno = saved_errno;
192 continue;
195 if (listen(sock, 5) == -1)
196 fatal("listen");
198 /*
199 * for the time being, we're happy as soon as
200 * something binds.
201 */
202 break;
205 if (sock == -1)
206 fatal("%s", cause);
207 freeaddrinfo(res0);
209 event_init();
211 /* cheating */
212 conf->sock4 = sock;
213 event_set(&conf->evsock4, conf->sock4, EV_READ|EV_PERSIST,
214 do_accept, conf);
216 server_init(NULL, NULL, NULL);
217 if (server_configure_done(conf) == -1)
218 fatalx("server configuration failed");
220 log_info("serving %s on port %d", dir, port);
221 event_dispatch();
222 log_info("quitting");
223 return 0;
226 static __dead void
227 usage(void)
229 fprintf(stderr,
230 "Version: " GE_STRING "\n"
231 "Usage: %s [-hVv] [-d certs-dir] [-H hostname] [-p port] [dir]\n",
232 getprogname());
233 exit(1);
236 int
237 main(int argc, char **argv)
239 struct conf *conf;
240 struct vhost *host;
241 struct location *loc;
242 const char *errstr, *certs_dir = NULL, *hostname = "localhost";
243 char path[PATH_MAX];
244 int ch;
246 setlocale(LC_CTYPE, "");
248 log_init(1, LOG_DAEMON);
249 log_setverbose(0);
250 conf = config_new();
252 /* ge doesn't do privsep so no privsep crypto engine. */
253 conf->use_privsep_crypto = 0;
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(&conf->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(conf, hostname, conf->port, loc->dir);