xref: /csrg-svn/usr.bin/who/who.c (revision 6201)
1*6201Sroot static char *sccsid = "@(#)who.c	4.4 (Berkeley) 03/15/82";
21165Sbill /*
31165Sbill  * who
41165Sbill  */
51165Sbill 
61165Sbill #include <stdio.h>
71165Sbill #include <utmp.h>
81165Sbill #include <pwd.h>
91729Sbill #include <ctype.h>
101165Sbill 
111165Sbill #define NMAX sizeof(utmp.ut_name)
121165Sbill #define LMAX sizeof(utmp.ut_line)
131165Sbill 
14*6201Sroot struct	utmp utmp;
15*6201Sroot struct	passwd *pw;
16*6201Sroot struct	passwd *getpwuid();
17*6201Sroot char	hostname[32];
181165Sbill 
19*6201Sroot char	*ttyname(), *rindex(), *ctime(), *strcpy();
20*6201Sroot 
211165Sbill main(argc, argv)
22*6201Sroot 	int argc;
23*6201Sroot 	char **argv;
241165Sbill {
251165Sbill 	register char *tp, *s;
261165Sbill 	register FILE *fi;
271165Sbill 	extern char _sobuf[];
281165Sbill 
291165Sbill 	setbuf(stdout, _sobuf);
301165Sbill 	s = "/etc/utmp";
311165Sbill 	if(argc == 2)
321165Sbill 		s = argv[1];
331165Sbill 	if (argc==3) {
341165Sbill 		tp = ttyname(0);
351165Sbill 		if (tp)
361165Sbill 			tp = rindex(tp, '/') + 1;
371165Sbill 		else {	/* no tty - use best guess from passwd file */
381165Sbill 			pw = getpwuid(getuid());
391165Sbill 			strcpy(utmp.ut_name, pw?pw->pw_name: "?");
401165Sbill 			strcpy(utmp.ut_line, "tty??");
411165Sbill 			time(&utmp.ut_time);
421165Sbill 			putline();
431165Sbill 			exit(0);
441165Sbill 		}
451165Sbill 	}
461165Sbill 	if ((fi = fopen(s, "r")) == NULL) {
471165Sbill 		puts("who: cannot open utmp");
481165Sbill 		exit(1);
491165Sbill 	}
501165Sbill 	while (fread((char *)&utmp, sizeof(utmp), 1, fi) == 1) {
511165Sbill 		if(argc==3) {
52*6201Sroot 			gethostname(hostname, sizeof (hostname));
531165Sbill 			if (strcmp(utmp.ut_line, tp))
541165Sbill 				continue;
55*6201Sroot 			printf("%s!", hostname);
561165Sbill 			putline();
571165Sbill 			exit(0);
581165Sbill 		}
591165Sbill 		if(utmp.ut_name[0] == '\0' && argc==1)
601165Sbill 			continue;
611165Sbill 		putline();
621165Sbill 	}
631165Sbill }
641165Sbill 
651165Sbill putline()
661165Sbill {
671165Sbill 	register char *cbuf;
681165Sbill 
691165Sbill 	printf("%-*.*s %-*.*s", NMAX, NMAX, utmp.ut_name, LMAX, LMAX, utmp.ut_line);
701165Sbill 	cbuf = ctime(&utmp.ut_time);
711165Sbill 	printf("%.12s\n", cbuf+4);
721165Sbill }
73