xref: /openbsd-src/sys/kern/subr_log.c (revision fcde59b201a29a2b4570b00b71e7aa25d61cb5c1)
1 /*	$OpenBSD: subr_log.c,v 1.70 2020/12/25 12:59:52 visa Exp $	*/
2 /*	$NetBSD: subr_log.c,v 1.11 1996/03/30 22:24:44 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)subr_log.c	8.1 (Berkeley) 6/10/93
33  */
34 
35 /*
36  * Error log buffer for kernel printf's.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/proc.h>
42 #include <sys/vnode.h>
43 #include <sys/ioctl.h>
44 #include <sys/msgbuf.h>
45 #include <sys/file.h>
46 #include <sys/tty.h>
47 #include <sys/signalvar.h>
48 #include <sys/syslog.h>
49 #include <sys/poll.h>
50 #include <sys/malloc.h>
51 #include <sys/filedesc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/fcntl.h>
55 #include <sys/mutex.h>
56 #include <sys/timeout.h>
57 
58 #ifdef KTRACE
59 #include <sys/ktrace.h>
60 #endif
61 
62 #include <sys/mount.h>
63 #include <sys/syscallargs.h>
64 
65 #include <dev/cons.h>
66 
67 #define LOG_RDPRI	(PZERO + 1)
68 #define LOG_TICK	50		/* log tick interval in msec */
69 
70 #define LOG_ASYNC	0x04
71 #define LOG_RDWAIT	0x08
72 
73 /*
74  * Locking:
75  *	L	log_mtx
76  */
77 struct logsoftc {
78 	int	sc_state;		/* [L] see above for possibilities */
79 	struct	selinfo sc_selp;	/* process waiting on select call */
80 	struct	sigio_ref sc_sigio;	/* async I/O registration */
81 	int	sc_need_wakeup;		/* if set, wake up waiters */
82 	struct timeout sc_tick;		/* wakeup poll timeout */
83 } logsoftc;
84 
85 int	log_open;			/* also used in log() */
86 int	msgbufmapped;			/* is the message buffer mapped */
87 struct	msgbuf *msgbufp;		/* the mapped buffer, itself. */
88 struct	msgbuf *consbufp;		/* console message buffer. */
89 struct	file *syslogf;
90 
91 /*
92  * Lock that serializes access to log message buffers.
93  * This should be kept as a leaf lock in order not to constrain where
94  * printf(9) can be used.
95  */
96 struct	mutex log_mtx =
97     MUTEX_INITIALIZER_FLAGS(IPL_HIGH, "logmtx", MTX_NOWITNESS);
98 
99 void filt_logrdetach(struct knote *kn);
100 int filt_logread(struct knote *kn, long hint);
101 
102 const struct filterops logread_filtops = {
103 	.f_flags	= FILTEROP_ISFD,
104 	.f_attach	= NULL,
105 	.f_detach	= filt_logrdetach,
106 	.f_event	= filt_logread,
107 };
108 
109 int dosendsyslog(struct proc *, const char *, size_t, int, enum uio_seg);
110 void logtick(void *);
111 size_t msgbuf_getlen(struct msgbuf *);
112 
113 void
114 initmsgbuf(caddr_t buf, size_t bufsize)
115 {
116 	struct msgbuf *mbp;
117 	long new_bufs;
118 
119 	/* Sanity-check the given size. */
120 	if (bufsize < sizeof(struct msgbuf))
121 		return;
122 
123 	mbp = msgbufp = (struct msgbuf *)buf;
124 
125 	new_bufs = bufsize - offsetof(struct msgbuf, msg_bufc);
126 	if ((mbp->msg_magic != MSG_MAGIC) || (mbp->msg_bufs != new_bufs) ||
127 	    (mbp->msg_bufr < 0) || (mbp->msg_bufr >= mbp->msg_bufs) ||
128 	    (mbp->msg_bufx < 0) || (mbp->msg_bufx >= mbp->msg_bufs)) {
129 		/*
130 		 * If the buffer magic number is wrong, has changed
131 		 * size (which shouldn't happen often), or is
132 		 * internally inconsistent, initialize it.
133 		 */
134 
135 		memset(buf, 0, bufsize);
136 		mbp->msg_magic = MSG_MAGIC;
137 		mbp->msg_bufs = new_bufs;
138 	}
139 
140 	/* Always start new buffer data on a new line. */
141 	if (mbp->msg_bufx > 0 && mbp->msg_bufc[mbp->msg_bufx - 1] != '\n')
142 		msgbuf_putchar(msgbufp, '\n');
143 
144 	/* mark it as ready for use. */
145 	msgbufmapped = 1;
146 }
147 
148 void
149 initconsbuf(void)
150 {
151 	/* Set up a buffer to collect /dev/console output */
152 	consbufp = malloc(CONSBUFSIZE, M_TTYS, M_WAITOK | M_ZERO);
153 	consbufp->msg_magic = MSG_MAGIC;
154 	consbufp->msg_bufs = CONSBUFSIZE - offsetof(struct msgbuf, msg_bufc);
155 }
156 
157 void
158 msgbuf_putchar(struct msgbuf *mbp, const char c)
159 {
160 	if (mbp->msg_magic != MSG_MAGIC)
161 		/* Nothing we can do */
162 		return;
163 
164 	mtx_enter(&log_mtx);
165 	mbp->msg_bufc[mbp->msg_bufx++] = c;
166 	if (mbp->msg_bufx < 0 || mbp->msg_bufx >= mbp->msg_bufs)
167 		mbp->msg_bufx = 0;
168 	/* If the buffer is full, keep the most recent data. */
169 	if (mbp->msg_bufr == mbp->msg_bufx) {
170 		if (++mbp->msg_bufr >= mbp->msg_bufs)
171 			mbp->msg_bufr = 0;
172 		mbp->msg_bufd++;
173 	}
174 	mtx_leave(&log_mtx);
175 }
176 
177 size_t
178 msgbuf_getlen(struct msgbuf *mbp)
179 {
180 	long len;
181 
182 	mtx_enter(&log_mtx);
183 	len = mbp->msg_bufx - mbp->msg_bufr;
184 	if (len < 0)
185 		len += mbp->msg_bufs;
186 	mtx_leave(&log_mtx);
187 	return (len);
188 }
189 
190 int
191 logopen(dev_t dev, int flags, int mode, struct proc *p)
192 {
193 	if (log_open)
194 		return (EBUSY);
195 	log_open = 1;
196 	sigio_init(&logsoftc.sc_sigio);
197 	timeout_set(&logsoftc.sc_tick, logtick, NULL);
198 	timeout_add_msec(&logsoftc.sc_tick, LOG_TICK);
199 	return (0);
200 }
201 
202 int
203 logclose(dev_t dev, int flag, int mode, struct proc *p)
204 {
205 	struct file *fp;
206 
207 	fp = syslogf;
208 	syslogf = NULL;
209 	if (fp)
210 		FRELE(fp, p);
211 	log_open = 0;
212 	timeout_del(&logsoftc.sc_tick);
213 	logsoftc.sc_state = 0;
214 	sigio_free(&logsoftc.sc_sigio);
215 	return (0);
216 }
217 
218 int
219 logread(dev_t dev, struct uio *uio, int flag)
220 {
221 	struct sleep_state sls;
222 	struct msgbuf *mbp = msgbufp;
223 	size_t l, rpos;
224 	int error = 0;
225 
226 	mtx_enter(&log_mtx);
227 	while (mbp->msg_bufr == mbp->msg_bufx) {
228 		if (flag & IO_NDELAY) {
229 			error = EWOULDBLOCK;
230 			goto out;
231 		}
232 		logsoftc.sc_state |= LOG_RDWAIT;
233 		mtx_leave(&log_mtx);
234 		/*
235 		 * Set up and enter sleep manually instead of using msleep()
236 		 * to keep log_mtx as a leaf lock.
237 		 */
238 		sleep_setup(&sls, mbp, LOG_RDPRI | PCATCH, "klog");
239 		sleep_setup_signal(&sls);
240 		sleep_finish(&sls, logsoftc.sc_state & LOG_RDWAIT);
241 		error = sleep_finish_signal(&sls);
242 		mtx_enter(&log_mtx);
243 		if (error)
244 			goto out;
245 	}
246 
247 	if (mbp->msg_bufd > 0) {
248 		char buf[64];
249 		long ndropped;
250 
251 		ndropped = mbp->msg_bufd;
252 		mtx_leave(&log_mtx);
253 		l = snprintf(buf, sizeof(buf),
254 		    "<%d>klog: dropped %ld byte%s, message buffer full\n",
255 		    LOG_KERN|LOG_WARNING, ndropped,
256 		    ndropped == 1 ? "" : "s");
257 		error = uiomove(buf, ulmin(l, sizeof(buf) - 1), uio);
258 		mtx_enter(&log_mtx);
259 		if (error)
260 			goto out;
261 		mbp->msg_bufd -= ndropped;
262 	}
263 
264 	while (uio->uio_resid > 0) {
265 		if (mbp->msg_bufx >= mbp->msg_bufr)
266 			l = mbp->msg_bufx - mbp->msg_bufr;
267 		else
268 			l = mbp->msg_bufs - mbp->msg_bufr;
269 		l = ulmin(l, uio->uio_resid);
270 		if (l == 0)
271 			break;
272 		rpos = mbp->msg_bufr;
273 		mtx_leave(&log_mtx);
274 		/* Ignore that concurrent readers may consume the same data. */
275 		error = uiomove(&mbp->msg_bufc[rpos], l, uio);
276 		mtx_enter(&log_mtx);
277 		if (error)
278 			break;
279 		mbp->msg_bufr += l;
280 		if (mbp->msg_bufr < 0 || mbp->msg_bufr >= mbp->msg_bufs)
281 			mbp->msg_bufr = 0;
282 	}
283  out:
284 	mtx_leave(&log_mtx);
285 	return (error);
286 }
287 
288 int
289 logpoll(dev_t dev, int events, struct proc *p)
290 {
291 	int revents = 0;
292 
293 	mtx_enter(&log_mtx);
294 	if (events & (POLLIN | POLLRDNORM)) {
295 		if (msgbufp->msg_bufr != msgbufp->msg_bufx)
296 			revents |= events & (POLLIN | POLLRDNORM);
297 		else
298 			selrecord(p, &logsoftc.sc_selp);
299 	}
300 	mtx_leave(&log_mtx);
301 	return (revents);
302 }
303 
304 int
305 logkqfilter(dev_t dev, struct knote *kn)
306 {
307 	struct klist *klist;
308 	int s;
309 
310 	switch (kn->kn_filter) {
311 	case EVFILT_READ:
312 		klist = &logsoftc.sc_selp.si_note;
313 		kn->kn_fop = &logread_filtops;
314 		break;
315 	default:
316 		return (EINVAL);
317 	}
318 
319 	kn->kn_hook = (void *)msgbufp;
320 
321 	s = splhigh();
322 	klist_insert_locked(klist, kn);
323 	splx(s);
324 
325 	return (0);
326 }
327 
328 void
329 filt_logrdetach(struct knote *kn)
330 {
331 	int s;
332 
333 	s = splhigh();
334 	klist_remove_locked(&logsoftc.sc_selp.si_note, kn);
335 	splx(s);
336 }
337 
338 int
339 filt_logread(struct knote *kn, long hint)
340 {
341 	struct msgbuf *mbp = kn->kn_hook;
342 
343 	kn->kn_data = msgbuf_getlen(mbp);
344 	return (kn->kn_data != 0);
345 }
346 
347 void
348 logwakeup(void)
349 {
350 	/*
351 	 * The actual wakeup has to be deferred because logwakeup() can be
352 	 * called in very varied contexts.
353 	 * Keep the print routines usable in as many situations as possible
354 	 * by not using locking here.
355 	 */
356 
357 	/*
358 	 * Ensure that preceding stores become visible to other CPUs
359 	 * before the flag.
360 	 */
361 	membar_producer();
362 
363 	logsoftc.sc_need_wakeup = 1;
364 }
365 
366 void
367 logtick(void *arg)
368 {
369 	int state;
370 
371 	if (!log_open)
372 		return;
373 
374 	if (!logsoftc.sc_need_wakeup)
375 		goto out;
376 	logsoftc.sc_need_wakeup = 0;
377 
378 	/*
379 	 * sc_need_wakeup has to be cleared before handling the wakeup.
380 	 * Visiting log_mtx ensures the proper order.
381 	 */
382 
383 	mtx_enter(&log_mtx);
384 	state = logsoftc.sc_state;
385 	if (logsoftc.sc_state & LOG_RDWAIT)
386 		logsoftc.sc_state &= ~LOG_RDWAIT;
387 	mtx_leave(&log_mtx);
388 
389 	selwakeup(&logsoftc.sc_selp);
390 	if (state & LOG_ASYNC)
391 		pgsigio(&logsoftc.sc_sigio, SIGIO, 0);
392 	if (state & LOG_RDWAIT)
393 		wakeup(msgbufp);
394 out:
395 	timeout_add_msec(&logsoftc.sc_tick, LOG_TICK);
396 }
397 
398 int
399 logioctl(dev_t dev, u_long com, caddr_t data, int flag, struct proc *p)
400 {
401 	struct file *fp;
402 	int error;
403 
404 	switch (com) {
405 
406 	/* return number of characters immediately available */
407 	case FIONREAD:
408 		*(int *)data = (int)msgbuf_getlen(msgbufp);
409 		break;
410 
411 	case FIONBIO:
412 		break;
413 
414 	case FIOASYNC:
415 		mtx_enter(&log_mtx);
416 		if (*(int *)data)
417 			logsoftc.sc_state |= LOG_ASYNC;
418 		else
419 			logsoftc.sc_state &= ~LOG_ASYNC;
420 		mtx_leave(&log_mtx);
421 		break;
422 
423 	case FIOSETOWN:
424 	case TIOCSPGRP:
425 		return (sigio_setown(&logsoftc.sc_sigio, com, data));
426 
427 	case FIOGETOWN:
428 	case TIOCGPGRP:
429 		sigio_getown(&logsoftc.sc_sigio, com, data);
430 		break;
431 
432 	case LIOCSFD:
433 		if ((error = suser(p)) != 0)
434 			return (error);
435 		fp = syslogf;
436 		if ((error = getsock(p, *(int *)data, &syslogf)) != 0)
437 			return (error);
438 		if (fp)
439 			FRELE(fp, p);
440 		break;
441 
442 	default:
443 		return (ENOTTY);
444 	}
445 	return (0);
446 }
447 
448 int
449 sys_sendsyslog(struct proc *p, void *v, register_t *retval)
450 {
451 	struct sys_sendsyslog_args /* {
452 		syscallarg(const char *) buf;
453 		syscallarg(size_t) nbyte;
454 		syscallarg(int) flags;
455 	} */ *uap = v;
456 	int error;
457 	static int dropped_count, orig_error, orig_pid;
458 
459 	if (dropped_count) {
460 		size_t l;
461 		char buf[80];
462 
463 		l = snprintf(buf, sizeof(buf),
464 		    "<%d>sendsyslog: dropped %d message%s, error %d, pid %d",
465 		    LOG_KERN|LOG_WARNING, dropped_count,
466 		    dropped_count == 1 ? "" : "s", orig_error, orig_pid);
467 		error = dosendsyslog(p, buf, ulmin(l, sizeof(buf) - 1),
468 		    0, UIO_SYSSPACE);
469 		if (error == 0) {
470 			dropped_count = 0;
471 			orig_error = 0;
472 			orig_pid = 0;
473 		}
474 	}
475 	error = dosendsyslog(p, SCARG(uap, buf), SCARG(uap, nbyte),
476 	    SCARG(uap, flags), UIO_USERSPACE);
477 	if (error) {
478 		dropped_count++;
479 		orig_error = error;
480 		orig_pid = p->p_p->ps_pid;
481 	}
482 	return (error);
483 }
484 
485 int
486 dosendsyslog(struct proc *p, const char *buf, size_t nbyte, int flags,
487     enum uio_seg sflg)
488 {
489 #ifdef KTRACE
490 	struct iovec ktriov;
491 #endif
492 	struct file *fp;
493 	char pri[6], *kbuf;
494 	struct iovec aiov;
495 	struct uio auio;
496 	size_t i, len;
497 	int error;
498 
499 	if (nbyte > LOG_MAXLINE)
500 		nbyte = LOG_MAXLINE;
501 
502 	/* Global variable syslogf may change during sleep, use local copy. */
503 	fp = syslogf;
504 	if (fp)
505 		FREF(fp);
506 	else if (!ISSET(flags, LOG_CONS))
507 		return (ENOTCONN);
508 	else {
509 		/*
510 		 * Strip off syslog priority when logging to console.
511 		 * LOG_PRIMASK | LOG_FACMASK is 0x03ff, so at most 4
512 		 * decimal digits may appear in priority as <1023>.
513 		 */
514 		len = MIN(nbyte, sizeof(pri));
515 		if (sflg == UIO_USERSPACE) {
516 			if ((error = copyin(buf, pri, len)))
517 				return (error);
518 		} else
519 			memcpy(pri, buf, len);
520 		if (0 < len && pri[0] == '<') {
521 			for (i = 1; i < len; i++) {
522 				if (pri[i] < '0' || pri[i] > '9')
523 					break;
524 			}
525 			if (i < len && pri[i] == '>') {
526 				i++;
527 				/* There must be at least one digit <0>. */
528 				if (i >= 3) {
529 					buf += i;
530 					nbyte -= i;
531 				}
532 			}
533 		}
534 	}
535 
536 	aiov.iov_base = (char *)buf;
537 	aiov.iov_len = nbyte;
538 	auio.uio_iov = &aiov;
539 	auio.uio_iovcnt = 1;
540 	auio.uio_segflg = sflg;
541 	auio.uio_rw = UIO_WRITE;
542 	auio.uio_procp = p;
543 	auio.uio_offset = 0;
544 	auio.uio_resid = aiov.iov_len;
545 #ifdef KTRACE
546 	if (sflg == UIO_USERSPACE && KTRPOINT(p, KTR_GENIO))
547 		ktriov = aiov;
548 	else
549 		ktriov.iov_len = 0;
550 #endif
551 
552 	len = auio.uio_resid;
553 	if (fp) {
554 		int flags = (fp->f_flag & FNONBLOCK) ? MSG_DONTWAIT : 0;
555 		error = sosend(fp->f_data, NULL, &auio, NULL, NULL, flags);
556 		if (error == 0)
557 			len -= auio.uio_resid;
558 	} else if (constty || cn_devvp) {
559 		error = cnwrite(0, &auio, 0);
560 		if (error == 0)
561 			len -= auio.uio_resid;
562 		aiov.iov_base = "\r\n";
563 		aiov.iov_len = 2;
564 		auio.uio_iov = &aiov;
565 		auio.uio_iovcnt = 1;
566 		auio.uio_segflg = UIO_SYSSPACE;
567 		auio.uio_rw = UIO_WRITE;
568 		auio.uio_procp = p;
569 		auio.uio_offset = 0;
570 		auio.uio_resid = aiov.iov_len;
571 		cnwrite(0, &auio, 0);
572 	} else {
573 		/* XXX console redirection breaks down... */
574 		if (sflg == UIO_USERSPACE) {
575 			kbuf = malloc(len, M_TEMP, M_WAITOK);
576 			error = copyin(aiov.iov_base, kbuf, len);
577 		} else {
578 			kbuf = aiov.iov_base;
579 			error = 0;
580 		}
581 		if (error == 0)
582 			for (i = 0; i < len; i++) {
583 				if (kbuf[i] == '\0')
584 					break;
585 				cnputc(kbuf[i]);
586 				auio.uio_resid--;
587 			}
588 		if (sflg == UIO_USERSPACE)
589 			free(kbuf, M_TEMP, len);
590 		if (error == 0)
591 			len -= auio.uio_resid;
592 		cnputc('\n');
593 	}
594 
595 #ifdef KTRACE
596 	if (error == 0 && ktriov.iov_len != 0)
597 		ktrgenio(p, -1, UIO_WRITE, &ktriov, len);
598 #endif
599 	if (fp)
600 		FRELE(fp, p);
601 	else
602 		error = ENOTCONN;
603 	return (error);
604 }
605