xref: /csrg-svn/old/sysline/sysline.c (revision 22534)
1 /*
2  * Copyright (c) 1980 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  */
6 
7 #ifndef lint
8 char copyright[] =
9 "@(#) Copyright (c) 1980 Regents of the University of California.\n\
10  All rights reserved.\n";
11 #endif not lint
12 
13 #ifndef lint
14 static char sccsid[] = "@(#)sysline.c	5.1 (Berkeley) 06/06/85";
15 #endif not lint
16 
17 /*
18  * sysline - system status display on 25th line of terminal
19  * j.k.foderaro
20  *
21  * Prints a variety of information on the special status line of terminals
22  * that have a status display capability.  Cursor motions, status commands,
23  * etc. are gleamed from /etc/termcap.
24  * By default, all information is printed, and flags are given on the command
25  * line to disable the printing of information.  The information and
26  * disabling flags are:
27  *
28  *  flag	what
29  *  -----	----
30  *		time of day
31  *		load average and change in load average in the last 5 mins
32  *		number of user logged on
33  *   -p		# of processes the users owns which are runnable and the
34  *		  number which are suspended.  Processes whose parent is 1
35  *		  are not counted.
36  *   -l		users who've logged on and off.
37  *   -m		summarize new mail which has arrived
38  *
39  *  <other flags>
40  *   -r		use non reverse video
41  *   -c		turn off 25th line for 5 seconds before redisplaying.
42  *   -b		beep once one the half hour, twice on the hour
43  *   +N		refresh display every N seconds.
44  *   -i		print pid first thing
45  *   -e		do simple print designed for an emacs buffer line
46  *   -w		do the right things for a window
47  *   -h		print hostname between time and load average
48  *   -D		print day/date before time of day
49  *   -d		debug mode - print status line data in human readable format
50  *   -q		quiet mode - don't output diagnostic messages
51  *   -s		print Short (left-justified) line if escapes not allowed
52  *   -j		Print left Justified line regardless
53  */
54 
55 #define BSD4_2			/* for 4.2 BSD */
56 #define WHO			/* turn this on always */
57 #define HOSTNAME		/* 4.1a or greater, with hostname() */
58 #define RWHO			/* 4.1a or greater, with rwho */
59 #define VMUNIX			/* turn this on if you are running on vmunix */
60 #define NEW_BOOTTIME		/* 4.1c or greater */
61 
62 #define NETPREFIX "ucb"
63 #define DEFDELAY 60		/* update status once per minute */
64 #define MAILDIR "/usr/spool/mail"
65 /*
66  * if MAXLOAD is defined, then if the load average exceeded MAXLOAD
67  * then the process table will not be scanned and the log in/out data
68  * will not be checked.   The purpose of this is to reduced the load
69  * on the system when it is loaded.
70  */
71 #define MAXLOAD 6.0
72 
73 #include <stdio.h>
74 #include <sys/param.h>
75 #include <sys/signal.h>
76 #include <utmp.h>
77 #include <ctype.h>
78 #ifndef BSD4_2
79 #include <unctrl.h>
80 #endif
81 #include <sys/time.h>
82 #include <sys/stat.h>
83 #ifdef VMUNIX
84 #include <nlist.h>
85 #include <sys/vtimes.h>
86 #include <sys/proc.h>
87 #endif
88 #ifdef pdp11
89 #include <a.out.h>
90 #include <sys/proc.h>
91 #endif
92 #include <curses.h>
93 #undef nl
94 #ifdef TERMINFO
95 #include <term.h>
96 #endif TERMINFO
97 
98 #ifdef RWHO
99 #define	DOWN_THRESHOLD	(11 * 60)
100 #define	RWHOLEADER	"/usr/spool/rwho/whod."
101 
102 struct whod {
103 	char	wd_vers;
104 	char	wd_type;
105 	char	wd_fill[2];
106 	int	wd_sendtime;
107 	int	wd_recvtime;
108 	char	wd_hostname[32];
109 	int	wd_loadav[3];
110 	int	wd_boottime;
111 };
112 
113 struct remotehost {
114 	char *rh_host;
115 	int rh_file;
116 } remotehost[10];
117 int nremotes = 0;
118 #endif RWHO
119 
120 struct nlist nl[] = {
121 #ifdef NEW_BOOTTIME
122 	{ "_boottime" },	/* After 4.1a the label changed to "boottime" */
123 #else
124 	{ "_bootime" },		/* Under 4.1a and earlier it is "bootime" */
125 #endif
126 #define	NL_BOOT 0
127 	{ "_proc" },
128 #define NL_PROC 1
129 	{ "_avenrun" },
130 #define NL_AVEN 2
131 #ifdef VMUNIX
132 	{ "_nproc" },
133 #define NL_NPROC 3
134 #endif
135 	0
136 };
137 
138 	/* stuff for the kernel */
139 int kmem;			/* file descriptor for /dev/kmem */
140 struct proc *proc, *procNPROC;
141 int nproc;
142 int procadr;
143 double avenrun[3];		/* used for storing load averages */
144 
145 /*
146  * In order to determine how many people are logged on and who has
147  * logged in or out, we read in the /etc/utmp file. We also keep track of
148  * the previous utmp file.
149  */
150 int ut;				/* the file descriptor */
151 struct utmp *new, *old;
152 char *status;			/* per tty status bits, see below */
153 int nentries;			/* number of utmp entries */
154 	/* string lengths for printing */
155 #define LINESIZE (sizeof old->ut_line)
156 #define NAMESIZE (sizeof old->ut_name)
157 /*
158  * Status codes to say what has happened to a particular entry in utmp.
159  * NOCH means no change, ON means new person logged on,
160  * OFF means person logged off.
161  */
162 #define NOCH	0
163 #define ON	0x1
164 #define OFF	0x2
165 
166 #ifdef WHO
167 char whofilename[100];
168 char whofilename2[100];
169 #endif
170 
171 #ifdef HOSTNAME
172 char hostname[33];		/* one more for null termination */
173 #endif
174 
175 char lockfilename[100];		/* if exists, will prevent us from running */
176 
177 	/* flags which determine which info is printed */
178 int mailcheck = 1;	/* m - do biff like checking of mail */
179 int proccheck = 1;	/* p - give information on processes */
180 int logcheck = 1; 	/* l - tell who logs in and out */
181 int hostprint = 0;	/* h - print out hostname */
182 int dateprint = 0;	/* h - print out day/date */
183 int quiet = 0;		/* q - hush diagnostic messages */
184 
185 	/* flags which determine how things are printed */
186 int clr_bet_ref = 0;	/* c - clear line between refeshes */
187 int reverse = 1;	/* r - use reverse video */
188 int shortline = 0;	/* s - short (left-justified) if escapes not allowed */
189 int leftline = 0;	/* j - left-justified even if escapes allowed */
190 
191 	/* flags which have terminal do random things	*/
192 int beep = 0;		/* b - beep every half hour and twice every hour */
193 int printid = 0;	/* i - print pid of this process at startup */
194 int synch = 1;		/* synchronize with clock */
195 
196 	/* select output device (status display or straight output) */
197 int emacs = 0;		/* e - assume status display */
198 int window = 0;		/* w - window mode */
199 int dbug = 0;		/* d - debug */
200 
201 /*
202  * used to turn off reverse video every REVOFF times
203  * in an attempt to not wear out the phospher.
204  */
205 #define REVOFF 5
206 int revtime = 1;
207 
208 	/* used by mail checker */
209 off_t mailsize = 0;
210 off_t linebeg = 0;		/* place where we last left off reading */
211 
212 	/* things used by the string routines */
213 int chars;			/* number of printable characters */
214 char *sp;
215 char strarr[512];		/* big enough now? */
216 	/* flags to stringdump() */
217 char sawmail;			/* remember mail was seen to print bells */
218 char mustclear;			/* status line messed up */
219 
220 	/* strings which control status line display */
221 #ifdef TERMINFO
222 char	*rev_out, *rev_end, *arrows;
223 char	*tparm();
224 #else
225 char	to_status_line[64];
226 char	from_status_line[64];
227 char	dis_status_line[64];
228 char	clr_eol[64];
229 char	rev_out[20], rev_end[20];
230 char	*arrows, *bell = "\007";
231 int	eslok;	/* escapes on status line okay (reverse, cursor addressing) */
232 int	columns;
233 #define tparm(cap, parm) tgoto((cap), 0, (parm))
234 char	*tgoto();
235 #endif
236 
237 	/* to deal with window size changes */
238 #ifdef SIGWINCH
239 int sigwinch();
240 char winchanged;	/* window size has changed since last update */
241 #endif
242 
243 	/* random globals */
244 char *username;
245 char *ourtty;			/* keep track of what tty we're on */
246 struct stat stbuf, mstbuf;	/* mstbuf for mail check only */
247 unsigned delay = DEFDELAY;
248 short uid;
249 double loadavg = 0.0;		/* current load average */
250 int users = 0;
251 
252 char *getenv();
253 char *ttyname();
254 char *strcpy1();
255 char *sysrup();
256 char *calloc();
257 char *malloc();
258 int outc();
259 int erroutc();
260 
261 main(argc,argv)
262 	register char **argv;
263 {
264 	int clearbotl();
265 	register char *cp;
266 	char *home;
267 	extern char _sobuf[];
268 
269 	setbuf(stdout, _sobuf);
270 
271 #ifdef HOSTNAME
272 	gethostname(hostname, sizeof hostname - 1);
273 #endif
274 
275 	for (argv++; *argv != 0; argv++)
276 		switch (**argv) {
277 		case '-':
278 			for (cp = *argv + 1; *cp; cp++) {
279 				switch(*cp) {
280 				case 'r' :	/* turn off reverse video */
281 					reverse = 0;
282 					break;
283 				case 'c':
284 					clr_bet_ref = 1;
285 					break;
286 				case 'h':
287 					hostprint = 1;
288 					break;
289 				case 'D':
290 					dateprint = 1;
291 					break;
292 #ifdef RWHO
293 				case 'H':
294 					if (argv[1] == 0)
295 						break;
296 					argv++;
297 					if (strcmp(hostname, *argv) &&
298 					    strcmp(&hostname[sizeof NETPREFIX - 1], *argv))
299 						remotehost[nremotes++].rh_host = *argv;
300 					break;
301 #endif RWHO
302 				case 'm':
303 					mailcheck = 0;
304 					break;
305 				case 'p':
306 					proccheck = 0;
307 					break;
308 				case 'l':
309 					logcheck = 0;
310 					break;
311 				case 'b':
312 					beep = 1;
313 					break;
314 				case 'i':
315 					printid = 1;
316 					break;
317 				case 'w':
318 					window = 1;
319 					break;
320 				case 'e':
321 					emacs = 1;
322 					break;
323 				case 'd':
324 					dbug = 1;
325 					break;
326 				case 'q':
327 					quiet = 1;
328 					break;
329 				case 's':
330 					shortline = 1;
331 					break;
332 				case 'j':
333 					leftline = 1;
334 					break;
335 				default:
336 					fprintf(stderr,
337 						"sysline: bad flag: %c\n", *cp);
338 				}
339 			}
340 			break;
341 		case '+':
342 			delay = atoi(*argv + 1);
343 			if (delay < 10)
344 				delay = 10;
345 			else if (delay > 500)
346 				delay = 500;
347 			synch = 0;	/* no more sync */
348 			break;
349 		default:
350 			fprintf(stderr, "sysline: illegal argument %s\n",
351 				argv[0]);
352 		}
353 	if (emacs) {
354 		reverse = 0;
355 		columns = 79;
356 	} else	/* if not to emacs window, initialize terminal dependent info */
357 		initterm();
358 #ifdef SIGWINCH
359 	/*
360 	 * When the window size changes and we are the foreground
361 	 * process (true if -w), we get this signal.
362 	 */
363 	signal(SIGWINCH, sigwinch);
364 #endif
365 	getwinsize();		/* get window size from ioctl */
366 
367 	/* immediately fork and let the parent die if not emacs mode */
368 	if (!emacs && !window && !dbug) {
369 		if (fork())
370 			exit(0);
371 		/* pgrp should take care of things, but ignore them anyway */
372 		signal(SIGINT, SIG_IGN);
373 		signal(SIGQUIT, SIG_IGN);
374 #ifdef VMUNIX
375 		signal(SIGTTOU, SIG_IGN);
376 #endif
377 	}
378 	/*
379 	 * When we logoff, init will do a "vhangup()" on this
380 	 * tty which turns off I/O access and sends a SIGHUP
381 	 * signal.  We catch this and thereby clear the status
382 	 * display.  Note that a bug in 4.1bsd caused the SIGHUP
383 	 * signal to be sent to the wrong process, so you had to
384 	 * `kill -HUP' yourself in your .logout file.
385 	 * Do the same thing for SIGTERM, which is the default kill
386 	 * signal.
387 	 */
388 	signal(SIGHUP, clearbotl);
389 	signal(SIGTERM, clearbotl);
390 	/*
391 	 * This is so kill -ALRM to force update won't screw us up..
392 	 */
393 	signal(SIGALRM, SIG_IGN);
394 
395 	uid = getuid();
396 	ourtty = ttyname(2);	/* remember what tty we are on */
397 	if (printid) {
398 		printf("%d\n", getpid());
399 		fflush(stdout);
400 	}
401 	dup2(2, 1);
402 
403 	if ((home = getenv("HOME")) == 0)
404 		home = "";
405 	strcpy1(strcpy1(whofilename, home), "/.who");
406 	strcpy1(strcpy1(whofilename2, home), "/.sysline");
407 	strcpy1(strcpy1(lockfilename, home), "/.syslinelock");
408 
409 	if ((kmem = open("/dev/kmem",0)) < 0) {
410 		fprintf(stderr, "Can't open kmem.\n");
411 		exit(1);
412 	}
413 	readnamelist();
414 	if (proccheck)
415 		initprocread();
416 	initutmp();
417 	if (mailcheck)
418 		if ((username = getenv("USER")) == 0)
419 			mailcheck = 0;
420 		else {
421 			chdir(MAILDIR);
422 			if (stat(username, &mstbuf) >= 0)
423 				mailsize = mstbuf.st_size;
424 			else
425 				mailsize = 0;
426 		}
427 
428 	while (emacs || window || isloggedin())
429 		if (access(lockfilename, 0) >= 0)
430 			sleep(60);
431 		else {
432 			prtinfo();
433 			sleep(delay);
434 			if (clr_bet_ref) {
435 				tputs(dis_status_line, 1, outc);
436 				fflush(stdout);
437 				sleep(5);
438 			}
439 			revtime = (1 + revtime) % REVOFF;
440 		}
441 	clearbotl();
442 	/*NOTREACHED*/
443 }
444 
445 isloggedin()
446 {
447 	/*
448 	 * you can tell if a person has logged out if the owner of
449 	 * the tty has changed
450 	 */
451 	struct stat statbuf;
452 
453 	return fstat(2, &statbuf) == 0 && statbuf.st_uid == uid;
454 }
455 
456 readnamelist()
457 {
458 	time_t bootime, clock, nintv, time();
459 
460 #ifdef pdp11
461 	nlist("/unix", nl);
462 #else
463 	nlist("/vmunix", nl);
464 #endif
465 	if (nl[0].n_value == 0) {
466 		if (!quiet)
467 			fprintf(stderr, "No namelist\n");
468 		return;
469 	}
470 	lseek(kmem, (long)nl[NL_BOOT].n_value, 0);
471 	read(kmem, &bootime, sizeof(bootime));
472 	(void) time(&clock);
473 	nintv = clock - bootime;
474 	if (nintv <= 0L || nintv > 60L*60L*24L*365L) {
475 		if (!quiet)
476 			fprintf(stderr,
477 			"Time makes no sense... namelist must be wrong\n");
478 		nl[NL_PROC].n_value = nl[NL_AVEN].n_value = 0;
479 	}
480 }
481 
482 initutmp()
483 {
484 	struct stat st;
485 
486 	if ((ut = open("/etc/utmp", 0)) < 0) {
487 		fprintf(stderr, "Can't open utmp.\n");
488 		exit(1);
489 	}
490 	if (fstat(ut, &st) < 0) {
491 		perror("fstat: utmp");
492 		exit(1);
493 	}
494 	/*
495 	 * Calculate the size once and allocate buffer space.
496 	 * Utmp is not expected to grow or shrink.
497 	 */
498 	nentries = st.st_size / sizeof (struct utmp);
499 	if ((old = (struct utmp *)calloc(nentries, sizeof *old)) == 0 ||
500 	    (new = (struct utmp *)calloc(nentries, sizeof *new)) == 0 ||
501 	    (status = calloc(nentries, sizeof *status)) == 0) {
502 		fprintf(stderr, "Out of memory.\n");
503 		exit(1);
504 	}
505 }
506 
507 readutmp(u)
508 	struct utmp *u;
509 {
510 	static time_t lastmod;		/* initially zero */
511 	struct stat st;
512 
513 	if (fstat(ut, &st) >= 0 && st.st_mtime == lastmod)
514 		return 0;
515 	lastmod = st.st_mtime;
516 	lseek(ut, 0L, 0);
517 	(void) read(ut, (char *)u, nentries * sizeof *u);
518 	return 1;
519 }
520 
521 /*
522  * read in the process table locations and sizes, and allocate space
523  * for storing the process table.  This is done only once.
524  */
525 initprocread()
526 {
527 
528 	if (nl[NL_PROC].n_value == 0)
529 		return;
530 #ifdef VMUNIX
531 	lseek(kmem, (long)nl[NL_PROC].n_value, 0);
532 	read(kmem, &procadr, sizeof procadr);
533 	lseek(kmem, (long)nl[NL_NPROC].n_value, 0);
534 	read(kmem, &nproc, sizeof nproc);
535 #endif
536 #ifdef pdp11
537 	procadr = nl[NL_PROC].n_value;
538 	nproc = NPROC;			/* from param.h */
539 #endif
540 	if ((proc = (struct proc *) calloc(nproc, sizeof (struct proc))) == 0) {
541 		fprintf(stderr, "Out of memory.\n");
542 		exit(1);
543 	}
544 	procNPROC = proc + nproc;
545 }
546 
547 /*
548  * read in the process table.  This assumes that initprocread has alread been
549  * called to set up storage.
550  */
551 readproctab()
552 {
553 
554 	if (nl[NL_PROC].n_value == 0)
555 		return (0);
556 	lseek(kmem, (long)procadr, 0);
557 	read(kmem, (char *)proc, nproc * sizeof (struct proc));
558 	return (1);
559 }
560 
561 prtinfo()
562 {
563 	int on, off;
564 	register i;
565 	char fullprocess;
566 
567 	stringinit();
568 #ifdef SIGWINCH
569 	if (winchanged) {
570 		winchanged = 0;
571 		getwinsize();
572 		mustclear = 1;
573 	}
574 #endif
575 #ifdef WHO
576 	/* check for file named .who in the home directory */
577 	whocheck();
578 #endif
579 	timeprint();
580 	/*
581 	 * if mail is seen, don't print rest of info, just the mail
582 	 * reverse new and old so that next time we run, we won't lose log
583 	 * in and out information
584 	 */
585 	if (mailcheck && (sawmail = mailseen()))
586 		goto bottom;
587 #ifdef HOSTNAME
588 #ifdef RWHO
589 	for (i = 0; i < nremotes; i++) {
590 		char *tmp;
591 
592 		stringspace();
593 		tmp = sysrup(remotehost + i);
594 		stringcat(tmp, strlen(tmp));
595 	}
596 #endif
597 	/*
598 	 * print hostname info if requested
599 	 */
600 	if (hostprint) {
601 		stringspace();
602 		stringcat(hostname, -1);
603 	}
604 #endif
605 	/*
606 	 * print load average and difference between current load average
607 	 * and the load average 5 minutes ago
608 	 */
609 	if (nl[NL_AVEN].n_value != 0) {
610 		double diff;
611 
612 		stringspace();
613 #ifdef VMUNIX
614 		lseek(kmem, (long)nl[NL_AVEN].n_value, 0);
615 		read(kmem, avenrun, sizeof avenrun);
616 #endif
617 #ifdef pdp11
618 		loadav(avenrun);
619 #endif
620 		if ((diff = avenrun[0] - avenrun[1]) < 0.0)
621 			stringprt("%.1f %.1f", avenrun[0],  diff);
622 		else
623 			stringprt("%.1f +%.1f", avenrun[0], diff);
624 		loadavg = avenrun[0];		/* remember load average */
625 	}
626 	/*
627 	 * print log on and off information
628 	 */
629 	stringspace();
630 	fullprocess = 1;
631 #ifdef MAXLOAD
632 	if (loadavg > MAXLOAD)
633 		fullprocess = 0;	/* too loaded to run */
634 #endif
635 	/*
636 	 * Read utmp file (logged in data) only if we are doing a full
637 	 * process, or if this is the first time and we are calculating
638 	 * the number of users.
639 	 */
640 	on = off = 0;
641 	if (users == 0) {		/* first time */
642 		if (readutmp(old))
643 			for (i = 0; i < nentries; i++)
644 				if (old[i].ut_name[0])
645 					users++;
646 	} else if (fullprocess && readutmp(new)) {
647 		struct utmp *tmp;
648 
649 		users = 0;
650 		for (i = 0; i < nentries; i++) {
651 			if (strncmp(old[i].ut_name,
652 			    new[i].ut_name, NAMESIZE) == 0)
653 				status[i] = NOCH;
654 			else if (old[i].ut_name[0] == '\0') {
655 				status[i] = ON;
656 				on++;
657 			} else if (new[i].ut_name[0] == '\0') {
658 				status[i] = OFF;
659 				off++;
660 			} else {
661 				status[i] = ON | OFF;
662 				on++;
663 				off++;
664 			}
665 			if (new[i].ut_name[0])
666 				users++;
667 		}
668 		tmp = new;
669 		new = old;
670 		old = tmp;
671 	}
672 	/*
673 	 * Print:
674 	 * 	1.  number of users
675 	 *	2.  a * for unread mail
676 	 *	3.  a - if load is too high
677 	 *	4.  number of processes running and stopped
678 	 */
679 	stringprt("%du", users);
680 	if (mailsize > 0 && mstbuf.st_mtime >= mstbuf.st_atime)
681 		stringcat("*", -1);
682 	if (!fullprocess && (proccheck || logcheck))
683 		stringcat("-", -1);
684 	if (fullprocess && proccheck && readproctab()) {
685 		register struct proc *p;
686 		int procrun, procstop;
687 
688 		/*
689 		 * We are only interested in processes which have the same
690 		 * uid as us, and whose parent process id is not 1.
691 		 */
692 		procrun = procstop = 0;
693 		for (p = proc; p < procNPROC; p++) {
694 			if (p->p_stat == 0 || p->p_pgrp == 0 ||
695 			    p->p_uid != uid || p->p_ppid == 1)
696 				continue;
697 			switch (p->p_stat) {
698 			case SSTOP:
699 				procstop++;
700 				break;
701 			case SSLEEP:
702 				/*
703 				 * Sleep can mean waiting for a signal or just
704 				 * in a disk or page wait queue ready to run.
705 				 * We can tell if it is the later by the pri
706 				 * being negative.
707 				 */
708 				if (p->p_pri < PZERO)
709 					procrun++;
710 				break;
711 			case SWAIT:
712 			case SRUN:
713 			case SIDL:
714 				procrun++;
715 			}
716 		}
717 		if (procrun > 0 || procstop > 0) {
718 			stringspace();
719 			if (procrun > 0 && procstop > 0)
720 				stringprt("%dr %ds", procrun, procstop);
721 			else if (procrun > 0)
722 				stringprt("%dr", procrun);
723 			else
724 				stringprt("%ds", procstop);
725 		}
726 	}
727 	/*
728 	 * If anyone has logged on or off, and we are interested in it,
729 	 * print it out.
730 	 */
731 	if (logcheck) {
732 		/* old and new have already been swapped */
733 		if (on) {
734 			stringspace();
735 			stringcat("on:", -1);
736 			for (i = 0; i < nentries; i++)
737 				if (status[i] & ON) {
738 					stringprt(" %.8s", old[i].ut_name);
739 					ttyprint(old[i].ut_line);
740 				}
741 		}
742 		if (off) {
743 			stringspace();
744 			stringcat("off:", -1);
745 			for (i = 0; i < nentries; i++)
746 				if (status[i] & OFF) {
747 					stringprt(" %.8s", new[i].ut_name);
748 					ttyprint(new[i].ut_line);
749 				}
750 		}
751 	}
752 bottom:
753 		/* dump out what we know */
754 	stringdump();
755 }
756 
757 timeprint()
758 {
759 	long curtime;
760 	struct tm *tp, *localtime();
761 	static int beepable = 1;
762 
763 		/* always print time */
764 	time(&curtime);
765 	tp = localtime(&curtime);
766 	if (dateprint)
767 		stringprt("%.11s", ctime(&curtime));
768 	stringprt("%d:%02d", tp->tm_hour > 12 ? tp->tm_hour - 12 :
769 		(tp->tm_hour == 0 ? 12 : tp->tm_hour), tp->tm_min);
770 	if (synch)			/* sync with clock */
771 		delay = 60 - tp->tm_sec;
772 	/*
773 	 * Beepable is used to insure that we get at most one set of beeps
774 	 * every half hour.
775 	 */
776 	if (beep)
777 		if (beepable) {
778 			if (tp->tm_min == 30) {
779 				tputs(bell, 1, outc);
780 				fflush(stdout);
781 				beepable = 0;
782 			} else if (tp->tm_min == 0) {
783 				tputs(bell, 1, outc);
784 				fflush(stdout);
785 				sleep(2);
786 				tputs(bell, 1, outc);
787 				fflush(stdout);
788 				beepable = 0;
789 			}
790 		} else
791 			if (tp->tm_min != 0 && tp->tm_min != 30)
792 				beepable = 1;
793 }
794 
795 /*
796  * whocheck -- check for file named .who and print it on the who line first
797  */
798 whocheck()
799 {
800 	int chss;
801 	register char *p;
802 	char buff[81];
803 	int whofile;
804 
805 	if ((whofile = open(whofilename, 0)) < 0 &&
806 	    (whofile = open(whofilename2, 0)) < 0)
807 		return;
808 	chss = read(whofile, buff, sizeof buff - 1);
809 	close(whofile);
810 	if (chss <= 0)
811 		return;
812 	buff[chss] = '\0';
813 	/*
814 	 * Remove all line feeds, and replace by spaces if they are within
815 	 * the message, else replace them by nulls.
816 	 */
817 	for (p = buff; *p;)
818 		if (*p == '\n')
819 			if (p[1])
820 				*p++ = ' ';
821 			else
822 				*p = '\0';
823 		else
824 			p++;
825 	stringcat(buff, p - buff);
826 	stringspace();
827 }
828 
829 /*
830  * ttyprint -- given the name of a tty, print in the string buffer its
831  * short name surrounded by parenthesis.
832  * ttyxx is printed as (xx)
833  * console is printed as (cty)
834  */
835 ttyprint(name)
836 	char *name;
837 {
838 	char buff[11];
839 
840 	if (strncmp(name, "tty", 3) == 0)
841 		stringprt("(%.*s)", LINESIZE - 3, name + 3);
842 	else if (strcmp(name, "console") == 0)
843 		stringcat("(cty)", -1);
844 	else
845 		stringprt("(%.*s)", LINESIZE, name);
846 }
847 
848 /*
849  * mail checking function
850  * returns 0 if no mail seen
851  */
852 mailseen()
853 {
854 	FILE *mfd;
855 	register n;
856 	register char *cp;
857 	char lbuf[100], sendbuf[100], *bufend;
858 	char seenspace;
859 	int retval = 0;
860 
861 	if (stat(username, &mstbuf) < 0) {
862 		mailsize = 0;
863 		return 0;
864 	}
865 	if (mstbuf.st_size <= mailsize || (mfd = fopen(username,"r")) == NULL) {
866 		mailsize = mstbuf.st_size;
867 		return 0;
868 	}
869 	fseek(mfd, mailsize, 0);
870 	while ((n = readline(mfd, lbuf, sizeof lbuf)) >= 0 &&
871 	       strncmp(lbuf, "From ", 5) != 0)
872 		;
873 	if (n < 0) {
874 		stringcat("Mail has just arrived", 0);
875 		goto out;
876 	}
877 	retval = 1;
878 	/*
879 	 * Found a From line, get second word, which is the sender,
880 	 * and print it.
881 	 */
882 	for (cp = lbuf + 5; *cp && *cp != ' '; cp++)	/* skip to blank */
883 		;
884 	*cp = '\0';					/* terminate name */
885 	stringspace();
886 	stringprt("Mail from %s ", lbuf + 5);
887 	/*
888 	 * Print subject, and skip over header.
889 	 */
890 	while ((n = readline(mfd, lbuf, sizeof lbuf)) > 0)
891 		if (strncmp(lbuf, "Subject:", 8) == 0)
892 			stringprt("on %s ", lbuf + 9);
893 	if (!emacs)
894 		stringcat(arrows, 2);
895 	else
896 		stringcat(": ", 2);
897 	if (n < 0)			/* already at eof */
898 		goto out;
899 	/*
900 	 * Print as much of the letter as we can.
901 	 */
902 	cp = sendbuf;
903 	if ((n = columns - chars) > sizeof sendbuf - 1)
904 		n = sizeof sendbuf - 1;
905 	bufend = cp + n;
906 	seenspace = 0;
907 	while ((n = readline(mfd, lbuf, sizeof lbuf)) >= 0) {
908 		register char *rp;
909 
910 		if (strncmp(lbuf, "From ", 5) == 0)
911 			break;
912 		if (cp >= bufend)
913 			continue;
914 		if (!seenspace) {
915 			*cp++ = ' ';		/* space before lines */
916 			seenspace = 1;
917 		}
918 		rp = lbuf;
919 		while (*rp && cp < bufend)
920 			if (isspace(*rp)) {
921 				if (!seenspace) {
922 					*cp++ = ' ';
923 					seenspace = 1;
924 				}
925 				rp++;
926 			} else {
927 				*cp++ = *rp++;
928 				seenspace = 0;
929 			}
930 	}
931 	*cp = 0;
932 	stringcat(sendbuf, -1);
933 	/*
934 	 * Want to update write time so a star will
935 	 * appear after the number of users until the
936 	 * user reads his mail.
937 	 */
938 out:
939 	mailsize = linebeg;
940 	fclose(mfd);
941 	touch(username);
942 	return retval;
943 }
944 
945 /*
946  * readline -- read a line from fp and store it in buf.
947  * return the number of characters read.
948  */
949 readline(fp, buf, n)
950 	register FILE *fp;
951 	char *buf;
952 	register n;
953 {
954 	register c;
955 	register char *cp = buf;
956 
957 	linebeg = ftell(fp);		/* remember loc where line begins */
958 	cp = buf;
959 	while (--n > 0 && (c = getc(fp)) != EOF && c != '\n')
960 		*cp++ = c;
961 	*cp = 0;
962 	if (c == EOF && cp - buf == 0)
963 		return -1;
964 	return cp - buf;
965 }
966 
967 
968 /*
969  * string hacking functions
970  */
971 
972 stringinit()
973 {
974 	sp = strarr;
975 	chars = 0;
976 }
977 
978 /*VARARGS1*/
979 stringprt(format, a, b, c)
980 	char *format;
981 {
982 	char tempbuf[150];
983 
984 	stringcat(sprintf(tempbuf, format, a, b, c), -1);
985 }
986 
987 stringdump()
988 {
989 	char bigbuf[sizeof strarr + 200];
990 	register char *bp = bigbuf;
991 	register int i;
992 
993 	if (!emacs) {
994 		if (sawmail)
995 			bp = strcpy1(bp, bell);
996 		if (eslok)
997 			bp = strcpy1(bp, tparm(to_status_line,
998 				leftline ? 0 : columns - chars));
999 		else {
1000 			bp = strcpy1(bp, to_status_line);
1001 			if (!shortline && !leftline)
1002 				for (i = columns - chars; --i >= 0;)
1003 					*bp++ = ' ';
1004 		}
1005 		if (reverse && revtime != 0)
1006 			bp = strcpy1(bp, rev_out);
1007 	}
1008 	*sp = 0;
1009 	bp = strcpy1(bp, strarr);
1010 	if (!emacs) {
1011 		if (reverse)
1012 			bp = strcpy1(bp, rev_end);
1013 		bp = strcpy1(bp, from_status_line);
1014 		if (sawmail)
1015 			bp = strcpy1(strcpy1(bp, bell), bell);
1016 		*bp = 0;
1017 		tputs(bigbuf, 1, outc);
1018 		if (mustclear) {
1019 			mustclear = 0;
1020 			tputs(clr_eol, 1, outc);
1021 		}
1022 		if (dbug)
1023 			putchar('\n');
1024 		fflush(stdout);
1025 	} else
1026 		write(2, bigbuf, bp - bigbuf);
1027 }
1028 
1029 stringspace()
1030 {
1031 	if (reverse && revtime != 0) {
1032 #ifdef TERMINFO
1033 		stringcat(rev_end,
1034 			magic_cookie_glitch <= 0 ? 0 : magic_cookie_glitch);
1035 		stringcat(" ", 1);
1036 		stringcat(rev_out,
1037 			magic_cookie_glitch <= 0 ? 0 : magic_cookie_glitch);
1038 #else
1039 		stringcat(rev_end, 0);
1040 		stringcat(" ", 1);
1041 		stringcat(rev_out, 0);
1042 #endif TERMINFO
1043 	} else
1044 		stringcat(" ", 1);
1045 }
1046 
1047 /*
1048  * stringcat :: concatenate the characters in string str to the list we are
1049  * 	        building to send out.
1050  * str - the string to print. may contain funny (terminal control) chars.
1051  * n  - the number of printable characters in the string
1052  *	or if -1 then str is all printable so we can truncate it,
1053  *	otherwise don't print only half a string.
1054  */
1055 stringcat(str, n)
1056 	register char *str;
1057 	register n;
1058 {
1059 	register char *p = sp;
1060 
1061 	if (n < 0) {				/* truncate */
1062 		n = columns - chars;
1063 		while ((*p++ = *str++) && --n >= 0)
1064 			;
1065 		p--;
1066 		chars += p - sp;
1067 		sp = p;
1068 	} else if (chars + n <= columns) {	/* don't truncate */
1069 		while (*p++ = *str++)
1070 			;
1071 		chars += n;
1072 		sp = p - 1;
1073 	}
1074 }
1075 
1076 /*
1077  * touch :: update the modify time of a file.
1078  */
1079 touch(name)
1080 	char *name;		/* name of file */
1081 {
1082 	register fd;
1083 	char buf;
1084 
1085 	if ((fd = open(name, 2)) >= 0) {
1086 		read(fd, &buf, 1);		/* get first byte */
1087 		lseek(fd, 0L, 0);		/* go to beginning */
1088 		write(fd, &buf, 1);		/* and rewrite first byte */
1089 		close(fd);
1090 	}
1091 }
1092 
1093 
1094 /*
1095  * clearbotl :: clear bottom line.
1096  * called when process quits or is killed.
1097  * it clears the bottom line of the terminal.
1098  */
1099 clearbotl()
1100 {
1101 	register int fd;
1102 	int exit();
1103 
1104 	signal(SIGALRM, exit);
1105 	alarm(30);	/* if can't open in 30 secs, just die */
1106 	if (!emacs && (fd = open(ourtty, 1)) >= 0) {
1107 		write(fd, dis_status_line, strlen(dis_status_line));
1108 		close(fd);
1109 	}
1110 #ifdef PROF
1111 	if (chdir("/usr/src/ucb/sysline") < 0)
1112 		(void) chdir("/tmp");
1113 #endif
1114 	exit(0);
1115 }
1116 
1117 #ifdef TERMINFO
1118 initterm()
1119 {
1120 	static char standbuf[40];
1121 
1122 	setupterm(0, 1, 0);
1123 	if (!window && !has_status_line) {
1124 		/* not an appropriate terminal */
1125 		if (!quiet)
1126 		   fprintf(stderr, "sysline: no status capability for %s\n",
1127 			getenv("TERM"));
1128 		exit(1);
1129 	}
1130 	if (window || status_line_esc_ok) {
1131 		if (set_attributes) {
1132 			/* reverse video mode */
1133 			strcpy(standbuf,
1134 				tparm(set_attributes,0,0,1,0,0,0,0,0,0));
1135 			rev_out = standbuf;
1136 			rev_end = exit_attribute_mode;
1137 		} else if (enter_standout_mode && exit_standout_mode) {
1138 			rev_out = enter_standout_mode;
1139 			rev_end = exit_standout_mode;
1140 		} else
1141 			rev_out = rev_end = "";
1142 	} else
1143 		rev_out = rev_end = "";
1144 	columns--;	/* avoid cursor wraparound */
1145 }
1146 
1147 #else	/* TERMCAP */
1148 
1149 initterm()
1150 {
1151 	char *term, *cp;
1152 	static char tbuf[1024];
1153 	char is2[40];
1154 	extern char *UP;
1155 
1156 	if ((term = getenv("TERM")) == NULL) {
1157 		if (!quiet)
1158 			fprintf(stderr,
1159 				"sysline: No TERM variable in enviroment\n");
1160 		exit(1);
1161 	}
1162 	if (tgetent(tbuf, term) <= 0) {
1163 		if (!quiet)
1164 			fprintf(stderr,
1165 				"sysline: Unknown terminal type: %s\n", term);
1166 		exit(1);
1167 	}
1168 	if (!window && tgetflag("hs") <= 0) {
1169 		if (!strncmp(term, "h19", 3)) {
1170 			/* for upward compatability with h19sys */
1171 			strcpy(to_status_line,
1172 				"\033j\033x5\033x1\033Y8%+ \033o");
1173 			strcpy(from_status_line, "\033k\033y5");
1174 			strcpy(dis_status_line, "\033y1");
1175 			strcpy(rev_out, "\033p");
1176 			strcpy(rev_end, "\033q");
1177 			arrows = "\033Fhh\033G";
1178 			columns = 80;
1179 			UP = "\b";
1180 			return;
1181 		}
1182 		if (!quiet)
1183 			fprintf(stderr,
1184 				"sysline: No status capability for %s\n", term);
1185 		exit(1);
1186 	}
1187 	cp = is2;
1188 	if (tgetstr("i2", &cp) != NULL) {
1189 		/* someday tset will do this */
1190 		tputs(is2, 1, erroutc);
1191 		fflush(stdout);
1192 	}
1193 
1194 	/* the "-1" below is to avoid cursor wraparound problems */
1195 	columns = tgetnum("co") - 1;
1196 	if (window) {
1197 		strcpy(to_status_line, "\r");
1198 		strcpy(from_status_line, "");
1199 		cp = dis_status_line;	/* use the clear line sequence */
1200 		*cp++ = '\r';
1201 		tgetstr("ce", &cp);
1202 	} else {
1203 		cp = to_status_line;
1204 		tgetstr("ts", &cp);
1205 		cp = from_status_line;
1206 		tgetstr("fs", &cp);
1207 		cp = dis_status_line;
1208 		tgetstr("ds", &cp);
1209 		eslok = tgetflag("es");
1210 	}
1211 	if (eslok || window) {
1212 		cp = rev_out;
1213 		tgetstr("so", &cp);
1214 		cp = rev_end;
1215 		tgetstr("se", &cp);
1216 		cp = clr_eol;
1217 		tgetstr("ce", &cp);
1218 	} else
1219 		reverse = 0;	/* turn off reverse video */
1220 	UP = "\b";
1221 	if (!strncmp(term, "h19", 3))
1222 		arrows = "\033Fhh\033G";	/* "two tiny graphic arrows" */
1223 	else
1224 		arrows = "->";
1225 }
1226 #endif TERMINFO
1227 
1228 #ifdef pdp11
1229 loadav(ap)
1230 double ap[];
1231 {
1232 	register int i;
1233 	short s_avenrun[3];
1234 
1235 	lseek(kmem, (long)nl[NL_AVEN].n_value, 0);
1236 	read(kmem, s_avenrun, sizeof(s_avenrun));
1237 	for (i=0; i < (sizeof(s_avenrun)/sizeof(s_avenrun[0])); i++)
1238 		ap[i] = s_avenrun[i] / 256.0;
1239 }
1240 #endif
1241 
1242 #ifdef RWHO
1243 char *
1244 sysrup(hp)
1245 	register struct remotehost *hp;
1246 {
1247 	char filename[100];
1248 	struct whod wd;
1249 	static char buffer[50];
1250 	time_t now;
1251 
1252 	/*
1253 	 * rh_file is initially 0.
1254 	 * This is ok since standard input is assumed to exist.
1255 	 */
1256 	if (hp->rh_file == 0) {
1257 		/*
1258 		 * Try rwho hostname file, and if that fails try ucbhostname.
1259 		 */
1260 		(void) strcpy1(strcpy1(filename, RWHOLEADER), hp->rh_host);
1261 		if ((hp->rh_file = open(filename, 0)) < 0) {
1262 			(void) strcpy1(strcpy1(strcpy1(filename, RWHOLEADER),
1263 				NETPREFIX), hp->rh_host);
1264 			hp->rh_file = open(filename, 0);
1265 		}
1266 	}
1267 	if (hp->rh_file < 0)
1268 		return sprintf(buffer, "%s?", hp->rh_host);
1269 	(void) lseek(hp->rh_file, (off_t)0, 0);
1270 	if (read(hp->rh_file, (char *)&wd, sizeof wd) != sizeof wd)
1271 		return sprintf(buffer, "%s ?", hp->rh_host);
1272 	(void) time(&now);
1273 	if (now - wd.wd_recvtime > DOWN_THRESHOLD) {
1274 		long interval;
1275 		long days, hours, minutes;
1276 
1277 		interval = now - wd.wd_recvtime;
1278 		minutes = (interval + 59) / 60;	/* round to minutes */
1279 		hours = minutes / 60;		/* extract hours from minutes */
1280 		minutes %= 60;			/* remove hours from minutes */
1281 		days = hours / 24;		/* extract days from hours */
1282 		hours %= 24;			/* remove days from hours */
1283 		if (days > 7 || days < 0)
1284 			(void) sprintf(buffer, "%s down", hp->rh_host);
1285 		else if (days > 0)
1286 			(void) sprintf(buffer, "%s %d+%d:%02d",
1287 				hp->rh_host, days, hours, minutes);
1288 		else
1289 			(void) sprintf(buffer, "%s %d:%02d",
1290 				hp->rh_host, hours, minutes);
1291 	} else
1292 		(void) sprintf(buffer, "%s %.1f",
1293 			hp->rh_host, wd.wd_loadav[0]/100.0);
1294 	return buffer;
1295 }
1296 #endif RWHO
1297 
1298 getwinsize()
1299 {
1300 #ifdef TIOCGWINSZ
1301 	struct winsize winsize;
1302 
1303 	/* the "-1" below is to avoid cursor wraparound problems */
1304 	if (ioctl(2, TIOCGWINSZ, (char *)&winsize) >= 0 && winsize.ws_col != 0)
1305 		columns = winsize.ws_col - 1;
1306 #endif
1307 }
1308 
1309 #ifdef SIGWINCH
1310 sigwinch()
1311 {
1312 	winchanged++;
1313 }
1314 #endif
1315 
1316 char *
1317 strcpy1(p, q)
1318 	register char *p, *q;
1319 {
1320 
1321 	while (*p++ = *q++)
1322 		;
1323 	return p - 1;
1324 }
1325 
1326 outc(c)
1327 	char c;
1328 {
1329 	if (dbug)
1330 		printf("%s", unctrl(c));
1331 	else
1332 		putchar(c);
1333 }
1334 
1335 erroutc(c)
1336 	char c;
1337 {
1338 	if (dbug)
1339 		fprintf(stderr, "%s", unctrl(c));
1340 	else
1341 		putc(c, stderr);
1342 }
1343