1 /*
2  * Copyright (c) 2021 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  */
16 
17 #include "gmid.h"
18 
19 #include <sys/types.h>
20 #include <sys/uio.h>
21 
22 #include <errno.h>
23 #include <event.h>
24 #include <imsg.h>
25 #include <netdb.h>
26 #include <poll.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <syslog.h>
31 #include <time.h>
32 
33 static struct event imsgev;
34 
35 static FILE *log;
36 
37 static void	handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
38 static void	handle_imsg_log(struct imsgbuf*, struct imsg*, size_t);
39 static void	handle_imsg_log_type(struct imsgbuf*, struct imsg*, size_t);
40 static void	handle_dispatch_imsg(int, short, void*);
41 
42 static imsg_handlerfn *handlers[] = {
43 	[IMSG_QUIT] = handle_imsg_quit,
44 	[IMSG_LOG] = handle_imsg_log,
45 	[IMSG_LOG_REQUEST] = handle_imsg_log,
46 	[IMSG_LOG_TYPE] = handle_imsg_log_type,
47 };
48 
49 static inline void
print_date(FILE * f)50 print_date(FILE *f)
51 {
52 	struct tm	tminfo;
53 	time_t		t;
54 	char		buf[20];
55 
56 	time(&t);
57 	strftime(buf, sizeof(buf), "%F %T",
58 	    localtime_r(&t, &tminfo));
59 	fprintf(f, "[%s] ", buf);
60 }
61 
62 static inline int
should_log(int priority)63 should_log(int priority)
64 {
65 	switch (priority) {
66 	case LOG_ERR:
67 		return 1;
68 	case LOG_WARNING:
69 		return 1;
70 	case LOG_NOTICE:
71 		return conf.verbose >= 1;
72 	case LOG_INFO:
73 		return conf.verbose >= 2;
74 	case LOG_DEBUG:
75 		return conf.verbose >= 3;
76 	default:
77 		return 0;
78 	}
79 }
80 
81 static inline void
send_log(int type,int priority,const char * msg,size_t len)82 send_log(int type, int priority, const char *msg, size_t len)
83 {
84 	imsg_compose(&logibuf, type, priority, 0, -1, msg, len);
85 	imsg_flush(&logibuf);
86 }
87 
88 void
fatal(const char * fmt,...)89 fatal(const char *fmt, ...)
90 {
91 	struct pollfd pfd;
92 	va_list	 ap;
93 	int	 r;
94 	char	*fmted;
95 
96 	va_start(ap, fmt);
97 	if ((r = vasprintf(&fmted, fmt, ap)) != -1) {
98 		send_log(IMSG_LOG, LOG_CRIT, fmted, r+1);
99 		free(fmted);
100 
101 		/* wait for the logger process to shut down */
102 		pfd.fd = logibuf.fd;
103 		pfd.events = POLLIN;
104 		poll(&pfd, 1, 1000);
105 	}
106 	va_end(ap);
107 	exit(1);
108 }
109 
110 static inline void
vlog(int priority,struct client * c,const char * fmt,va_list ap)111 vlog(int priority, struct client *c,
112     const char *fmt, va_list ap)
113 {
114 	char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
115 	char *fmted, *s;
116 	size_t len;
117 	int ec;
118 
119 	if (!should_log(priority))
120 		return;
121 
122 	if (c != NULL) {
123 		len = sizeof(c->addr);
124 		ec = getnameinfo((struct sockaddr*)&c->addr, len,
125 		    hbuf, sizeof(hbuf),
126 		    sbuf, sizeof(sbuf),
127 		    NI_NUMERICHOST | NI_NUMERICSERV);
128 		if (ec != 0)
129 			fatal("getnameinfo: %s", gai_strerror(ec));
130 	}
131 
132 	if (vasprintf(&fmted, fmt, ap) == -1)
133 		fatal("vasprintf: %s", strerror(errno));
134 
135 	if (c == NULL)
136 		ec = asprintf(&s, "internal: %s", fmted);
137 	else
138 		ec = asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted);
139 
140 	if (ec < 0)
141 		fatal("asprintf: %s", strerror(errno));
142 
143 	send_log(IMSG_LOG, priority, s, ec+1);
144 
145 	free(fmted);
146 	free(s);
147 }
148 
149 void
log_err(struct client * c,const char * fmt,...)150 log_err(struct client *c, const char *fmt, ...)
151 {
152 	va_list ap;
153 
154 	va_start(ap, fmt);
155 	vlog(LOG_ERR, c, fmt, ap);
156 	va_end(ap);
157 }
158 
159 void
log_warn(struct client * c,const char * fmt,...)160 log_warn(struct client *c, const char *fmt, ...)
161 {
162 	va_list ap;
163 
164 	va_start(ap, fmt);
165 	vlog(LOG_WARNING, c, fmt, ap);
166 	va_end(ap);
167 }
168 
169 void
log_notice(struct client * c,const char * fmt,...)170 log_notice(struct client *c, const char *fmt, ...)
171 {
172 	va_list ap;
173 
174 	va_start(ap, fmt);
175 	vlog(LOG_NOTICE, c, fmt, ap);
176 	va_end(ap);
177 }
178 
179 void
log_info(struct client * c,const char * fmt,...)180 log_info(struct client *c, const char *fmt, ...)
181 {
182 	va_list ap;
183 
184 	va_start(ap, fmt);
185 	vlog(LOG_INFO, c, fmt, ap);
186 	va_end(ap);
187 }
188 
189 void
log_debug(struct client * c,const char * fmt,...)190 log_debug(struct client *c, const char *fmt, ...)
191 {
192 	va_list ap;
193 
194 	va_start(ap, fmt);
195 	vlog(LOG_DEBUG, c, fmt, ap);
196 	va_end(ap);
197 }
198 
199 /* strchr, but with a bound */
200 static char *
gmid_strnchr(char * s,int c,size_t len)201 gmid_strnchr(char *s, int c, size_t len)
202 {
203 	size_t i;
204 
205 	for (i = 0; i < len; ++i)
206 		if (s[i] == c)
207 			return &s[i];
208 	return NULL;
209 }
210 
211 void
log_request(struct client * c,char * meta,size_t l)212 log_request(struct client *c, char *meta, size_t l)
213 {
214 	char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
215 	char *t, *fmted;
216 	size_t len;
217 	int ec;
218 
219 	len = sizeof(c->addr);
220 	ec = getnameinfo((struct sockaddr*)&c->addr, len,
221 	    hbuf, sizeof(hbuf),
222 	    sbuf, sizeof(sbuf),
223 	    NI_NUMERICHOST | NI_NUMERICSERV);
224 	if (ec != 0)
225 		fatal("getnameinfo: %s", gai_strerror(ec));
226 
227 	if (c->iri.schema != NULL) {
228 		/* serialize the IRI */
229 		strlcpy(b, c->iri.schema, sizeof(b));
230 		strlcat(b, "://", sizeof(b));
231 
232 		/* log the decoded host name, but if it was invalid
233 		 * use the raw one. */
234 		if (*c->domain != '\0')
235 			strlcat(b, c->domain, sizeof(b));
236 		else
237 			strlcat(b, c->iri.host, sizeof(b));
238 
239 		strlcat(b, "/", sizeof(b));
240 		strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
241 		if (*c->iri.query != '\0') {	    /* TODO: sanitize UTF8 */
242 			strlcat(b, "?", sizeof(b));
243 			strlcat(b, c->iri.query, sizeof(b));
244 		}
245 	} else {
246 		strlcpy(b, c->req, sizeof(b));
247 	}
248 
249 	if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
250 		t = meta + len;
251 
252 	ec = asprintf(&fmted, "%s:%s GET %s %.*s", hbuf, sbuf, b,
253 	    (int)(t-meta), meta);
254 	if (ec < 0)
255 		err(1, "asprintf");
256 	send_log(IMSG_LOG_REQUEST, LOG_NOTICE, fmted, ec+1);
257 	free(fmted);
258 }
259 
260 
261 
262 static void
do_log(int type,int priority,const char * msg)263 do_log(int type, int priority, const char *msg)
264 {
265 	int quit = 0;
266 
267 	if (priority == LOG_CRIT) {
268 		quit = 1;
269 		priority = LOG_ERR;
270 	}
271 
272 	if (log != NULL) {
273 		if (type != IMSG_LOG_REQUEST)
274 			print_date(log);
275 		fprintf(log, "%s\n", msg);
276 	} else
277 		syslog(LOG_DAEMON | priority, "%s", msg);
278 
279 	if (quit)
280 		exit(1);
281 }
282 
283 static void
handle_imsg_quit(struct imsgbuf * ibuf,struct imsg * imsg,size_t datalen)284 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
285 {
286 	event_loopbreak();
287 }
288 
289 static void
handle_imsg_log(struct imsgbuf * ibuf,struct imsg * imsg,size_t datalen)290 handle_imsg_log(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
291 {
292 	int	 priority;
293 	char	*msg;
294 
295 	msg = imsg->data;
296 	msg[datalen-1] = '\0';
297 	priority = imsg->hdr.peerid;
298 	do_log(imsg->hdr.type, priority, msg);
299 }
300 
301 static void
handle_imsg_log_type(struct imsgbuf * ibuf,struct imsg * imsg,size_t datalen)302 handle_imsg_log_type(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
303 {
304 	if (log != NULL && log != stderr) {
305 		fflush(log);
306 		fclose(log);
307 	}
308 	log = NULL;
309 
310 	if (imsg->fd != -1) {
311 		if ((log = fdopen(imsg->fd, "a")) == NULL) {
312 			syslog(LOG_DAEMON | LOG_ERR, "fdopen: %s",
313 			    strerror(errno));
314 			exit(1);
315 		}
316 	}
317 }
318 
319 static void
handle_dispatch_imsg(int fd,short ev,void * d)320 handle_dispatch_imsg(int fd, short ev, void *d)
321 {
322 	struct imsgbuf *ibuf = d;
323 	dispatch_imsg(ibuf, handlers, sizeof(handlers));
324 }
325 
326 int
logger_main(int fd,struct imsgbuf * ibuf)327 logger_main(int fd, struct imsgbuf *ibuf)
328 {
329 	log = stderr;
330 
331 	openlog(getprogname(), LOG_NDELAY, LOG_DAEMON);
332 
333 	event_init();
334 
335 	event_set(&imsgev, fd, EV_READ | EV_PERSIST, &handle_dispatch_imsg, ibuf);
336 	event_add(&imsgev, NULL);
337 
338 	sandbox_logger_process();
339 
340 	event_dispatch();
341 
342 	closelog();
343 
344 	return 0;
345 }
346