1 /* 2 * Copyright (c) 1989, 1993 3 * The Regents of the University of California. All rights reserved. 4 * 5 * This code is derived from software contributed to Berkeley by 6 * Michael Fischbein. 7 * 8 * %sccs.include.redist.c% 9 */ 10 11 #ifndef lint 12 static char copyright[] = 13 "@(#) Copyright (c) 1989, 1993\n\ 14 The Regents of the University of California. All rights reserved.\n"; 15 #endif /* not lint */ 16 17 #ifndef lint 18 static char sccsid[] = "@(#)who.c 8.1 (Berkeley) 06/06/93"; 19 #endif /* not lint */ 20 21 #include <sys/types.h> 22 #include <sys/file.h> 23 #include <sys/time.h> 24 #include <pwd.h> 25 #include <utmp.h> 26 #include <stdio.h> 27 28 main(argc, argv) 29 int argc; 30 char **argv; 31 { 32 register char *p; 33 struct utmp usr; 34 struct passwd *pw; 35 FILE *ufp, *file(); 36 char *t, *rindex(), *strcpy(), *strncpy(), *ttyname(); 37 time_t time(); 38 39 switch (argc) { 40 case 1: /* who */ 41 ufp = file(_PATH_UTMP); 42 /* only entries with both name and line fields */ 43 while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1) 44 if (*usr.ut_name && *usr.ut_line) 45 output(&usr); 46 break; 47 case 2: /* who utmp_file */ 48 ufp = file(argv[1]); 49 /* all entries */ 50 while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1) 51 output(&usr); 52 break; 53 case 3: /* who am i */ 54 ufp = file(_PATH_UTMP); 55 56 /* search through the utmp and find an entry for this tty */ 57 if (p = ttyname(0)) { 58 /* strip any directory component */ 59 if (t = rindex(p, '/')) 60 p = t + 1; 61 while (fread((char *)&usr, sizeof(usr), 1, ufp) == 1) 62 if (usr.ut_name && !strcmp(usr.ut_line, p)) { 63 output(&usr); 64 exit(0); 65 } 66 /* well, at least we know what the tty is */ 67 (void)strncpy(usr.ut_line, p, UT_LINESIZE); 68 } else 69 (void)strcpy(usr.ut_line, "tty??"); 70 pw = getpwuid(getuid()); 71 (void)strncpy(usr.ut_name, pw ? pw->pw_name : "?", UT_NAMESIZE); 72 (void)time(&usr.ut_time); 73 *usr.ut_host = '\0'; 74 output(&usr); 75 break; 76 default: 77 (void)fprintf(stderr, "usage: who [ file ]\n who am i\n"); 78 exit(1); 79 } 80 exit(0); 81 } 82 83 output(up) 84 struct utmp *up; 85 { 86 char *ctime(); 87 88 (void)printf("%-*.*s %-*.*s", UT_NAMESIZE, UT_NAMESIZE, up->ut_name, 89 UT_LINESIZE, UT_LINESIZE, up->ut_line); 90 (void)printf("%.12s", ctime(&up->ut_time) + 4); 91 if (*up->ut_host) 92 printf("\t(%.*s)", UT_HOSTSIZE, up->ut_host); 93 (void)putchar('\n'); 94 } 95 96 FILE * 97 file(name) 98 char *name; 99 { 100 extern int errno; 101 FILE *ufp; 102 char *strerror(); 103 104 if (!(ufp = fopen(name, "r"))) { 105 (void)fprintf(stderr, "who: %s: %s.\n", name, strerror(errno)); 106 exit(1); 107 } 108 return(ufp); 109 } 110