|
|
1.1 ! root 1: #include <sys/param.h> ! 2: #include <sys/user.h> ! 3: #include <sys/proc.h> ! 4: #include <sys/pioctl.h> ! 5: #include <sys/stat.h> ! 6: #include <utmp.h> ! 7: ! 8: #define UADDR (0x80000000-(UPAGES*NBPG)) ! 9: ! 10: /* ! 11: * figure out the name of the tty ! 12: * on which i originally logged in ! 13: * by guess and by hack ! 14: */ ! 15: ! 16: main() ! 17: { ! 18: char *tty; ! 19: char *mytty(); ! 20: ! 21: if ((tty = mytty()) == 0) { ! 22: printf("no login tty\n"); ! 23: exit(1); ! 24: } ! 25: printf("%s\n", tty); ! 26: exit(0); ! 27: } ! 28: ! 29: static char * ! 30: procname(pid) ! 31: int pid; ! 32: { ! 33: static char buf[20]; ! 34: ! 35: sprint(buf, "/proc/%d", pid); ! 36: return (buf); ! 37: } ! 38: ! 39: #define MAXME 20 ! 40: ! 41: struct ttyi { ! 42: ino_t ino; ! 43: char name[14]; /* 8 + "/dev/" + \0 */ ! 44: }; ! 45: ! 46: char * ! 47: mytty() ! 48: { ! 49: static struct ttyi mt[MAXME]; ! 50: register int i; ! 51: register int e; ! 52: int pid; ! 53: int fd; ! 54: struct proc p; ! 55: struct user u; ! 56: char *myname; ! 57: char *getlogin(); ! 58: ! 59: if ((myname = getlogin()) == NULL) ! 60: return (NULL); ! 61: if ((e = mtinit(myname, mt)) == 0) ! 62: return (NULL); ! 63: for (pid = getpid();; close(fd), pid = p.p_ppid) { ! 64: if ((fd = open(procname(pid), 0)) < 0) ! 65: break; ! 66: if (ioctl(fd, PIOCGETPR, &p) < 0) ! 67: break; ! 68: if (p.p_ppid == pid) ! 69: break; ! 70: lseek(fd, UADDR, 0); ! 71: if (read(fd, (char *)&u, sizeof(u)) != sizeof(u)) ! 72: break; ! 73: if (strncmp(u.u_logname, myname, sizeof(u.u_logname)) != 0) ! 74: break; ! 75: for (i = 0; i < e; i++) ! 76: if (mt[i].ino == u.u_ttyino) { ! 77: close(fd); ! 78: return (mt[i].name); ! 79: } ! 80: } ! 81: if (fd >= 0) ! 82: close(fd); ! 83: return (NULL); ! 84: } ! 85: ! 86: static ! 87: mtinit(myname, mt) ! 88: char *myname; ! 89: register struct ttyi *mt; ! 90: { ! 91: struct utmp ut[20]; ! 92: int fd; ! 93: register struct utmp *u, *e; ! 94: register int i; ! 95: register int n; ! 96: struct stat st; ! 97: ! 98: if ((myname = getlogin()) == NULL) ! 99: return (0); ! 100: if ((fd = open("/etc/utmp", 0)) < 0) ! 101: return (0); ! 102: i = 0; ! 103: while ((n = read(fd, (char *)ut, sizeof(ut))) > 0) { ! 104: e = (struct utmp *)((char *)ut + n); ! 105: for (u = ut; u < e; u++) { ! 106: if (u->ut_name[0] == 0) ! 107: continue; ! 108: if (strncmp(u->ut_name, myname, sizeof(u->ut_name)) != 0) ! 109: continue; ! 110: sprintf(mt[i].name, "/dev/%.8s", u->ut_line); ! 111: if (stat(mt[i].name, &st) < 0) ! 112: continue; ! 113: mt[i].ino = st.st_ino; ! 114: if (++i >= MAXME) { ! 115: close(fd); ! 116: return (i); ! 117: } ! 118: } ! 119: } ! 120: close(fd); ! 121: return (i); ! 122: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.