xref: /csrg-svn/usr.bin/who/who.c (revision 12686)
1*12686Ssam #ifndef lint
2*12686Ssam static char *sccsid = "@(#)who.c	4.5 (Berkeley) 05/23/83";
3*12686Ssam #endif
41165Sbill /*
51165Sbill  * who
61165Sbill  */
71165Sbill 
81165Sbill #include <stdio.h>
91165Sbill #include <utmp.h>
101165Sbill #include <pwd.h>
111729Sbill #include <ctype.h>
121165Sbill 
131165Sbill #define NMAX sizeof(utmp.ut_name)
141165Sbill #define LMAX sizeof(utmp.ut_line)
15*12686Ssam #define	HMAX sizeof(utmp.ut_host)
161165Sbill 
176201Sroot struct	utmp utmp;
186201Sroot struct	passwd *pw;
196201Sroot struct	passwd *getpwuid();
206201Sroot char	hostname[32];
211165Sbill 
226201Sroot char	*ttyname(), *rindex(), *ctime(), *strcpy();
236201Sroot 
241165Sbill main(argc, argv)
256201Sroot 	int argc;
266201Sroot 	char **argv;
271165Sbill {
281165Sbill 	register char *tp, *s;
291165Sbill 	register FILE *fi;
301165Sbill 	extern char _sobuf[];
311165Sbill 
321165Sbill 	setbuf(stdout, _sobuf);
331165Sbill 	s = "/etc/utmp";
341165Sbill 	if(argc == 2)
351165Sbill 		s = argv[1];
36*12686Ssam 	if (argc == 3) {
371165Sbill 		tp = ttyname(0);
381165Sbill 		if (tp)
391165Sbill 			tp = rindex(tp, '/') + 1;
401165Sbill 		else {	/* no tty - use best guess from passwd file */
411165Sbill 			pw = getpwuid(getuid());
421165Sbill 			strcpy(utmp.ut_name, pw?pw->pw_name: "?");
431165Sbill 			strcpy(utmp.ut_line, "tty??");
441165Sbill 			time(&utmp.ut_time);
451165Sbill 			putline();
461165Sbill 			exit(0);
471165Sbill 		}
481165Sbill 	}
491165Sbill 	if ((fi = fopen(s, "r")) == NULL) {
501165Sbill 		puts("who: cannot open utmp");
511165Sbill 		exit(1);
521165Sbill 	}
531165Sbill 	while (fread((char *)&utmp, sizeof(utmp), 1, fi) == 1) {
54*12686Ssam 		if (argc == 3) {
556201Sroot 			gethostname(hostname, sizeof (hostname));
561165Sbill 			if (strcmp(utmp.ut_line, tp))
571165Sbill 				continue;
586201Sroot 			printf("%s!", hostname);
591165Sbill 			putline();
601165Sbill 			exit(0);
611165Sbill 		}
62*12686Ssam 		if (utmp.ut_name[0] == '\0' && argc == 1)
631165Sbill 			continue;
641165Sbill 		putline();
651165Sbill 	}
661165Sbill }
671165Sbill 
681165Sbill putline()
691165Sbill {
701165Sbill 	register char *cbuf;
711165Sbill 
72*12686Ssam 	printf("%-*.*s %-*.*s",
73*12686Ssam 		NMAX, NMAX, utmp.ut_name,
74*12686Ssam 		LMAX, LMAX, utmp.ut_line);
751165Sbill 	cbuf = ctime(&utmp.ut_time);
76*12686Ssam 	printf("%.12s", cbuf+4);
77*12686Ssam 	if (utmp.ut_host[0])
78*12686Ssam 		printf("\t(%.*s)", HMAX, utmp.ut_host);
79*12686Ssam 	putchar('\n');
801165Sbill }
81