getty.c (2764B)
1 /* see LICENSE file for copyright and license details */ 2 3 #include <sys/ioctl.h> 4 #include <sys/stat.h> 5 #include <sys/types.h> 6 7 #include <fcntl.h> 8 #include <limits.h> 9 #include <signal.h> 10 #include <stdio.h> 11 #include <stdlib.h> 12 #include <string.h> 13 #include <unistd.h> 14 15 #include "config.h" 16 #include "session.h" 17 #include "util.h" 18 #include "wexec.h" 19 20 static const char *tty; 21 22 static void 23 usage(void) 24 { 25 eprintf("usage: %s [tty] [term] [cmd] [args...]\n", argv0); 26 } 27 28 // ?man getty: set terminal mode 29 // ?man arguments: tty [term] [cmd] [args ...] 30 // ?man set terminal line discipline, speed, and mode 31 int 32 main(int argc, char *argv[]) 33 { 34 char term[128], logname[LOGIN_NAME_MAX], c; 35 char hostname[HOST_NAME_MAX + 1]; 36 struct sigaction sa; 37 int fd; 38 unsigned int i = 0; 39 ssize_t n; 40 41 ARGBEGIN 42 { 43 default: 44 usage(); 45 } 46 ARGEND; 47 48 tty = ttyconsole(); 49 strlcpy(term, ttyconsterm(), sizeof(term)); 50 if (argc > 0) { 51 tty = argv[0]; 52 if (argc > 1) 53 strlcpy(term, argv[1], sizeof(term)); 54 } 55 56 sa.sa_handler = SIG_IGN; 57 sa.sa_flags = 0; 58 sigemptyset(&sa.sa_mask); 59 sigaction(SIGHUP, &sa, NULL); 60 61 setenv("TERM", term, 1); 62 63 setsid(); 64 65 fd = open(tty, O_RDWR); 66 if (fd < 0) 67 eprintf("open %s:", tty); 68 if (isatty(fd) == 0) 69 eprintf("%s is not a tty\n", tty); 70 71 /* steal the controlling terminal if necessary */ 72 if (ioctl(fd, TIOCSCTTY, (void *)1) != 0) 73 weprintf("TIOCSCTTY: could not set controlling tty\n"); 74 #if FEATURE_GTTY_VHANGUP 75 ttyhangup(); 76 #else 77 eprintf("getty: vhangup support not built\n"); 78 #endif 79 close(fd); 80 81 fd = open(tty, O_RDWR); 82 if (fd < 0) 83 eprintf("open %s:", tty); 84 dup2(fd, 0); 85 dup2(fd, 1); 86 dup2(fd, 2); 87 if (fchown(fd, 0, 0) < 0) 88 weprintf("fchown %s:", tty); 89 if (fchmod(fd, 0600) < 0) 90 weprintf("fchmod %s:", tty); 91 if (fd > 2) 92 close(fd); 93 94 sa.sa_handler = SIG_DFL; 95 sa.sa_flags = 0; 96 sigemptyset(&sa.sa_mask); 97 sigaction(SIGHUP, &sa, NULL); 98 99 session_clear(tty); 100 101 if (argc > 2) { 102 wexecvp_self(argv[2], argv + 2); 103 return 0; 104 } 105 106 if (gethostname(hostname, sizeof(hostname)) == 0) 107 printf("%s ", hostname); 108 printf("login: "); 109 fflush(stdout); 110 111 /* flush pending input */ 112 ioctl(0, TCFLSH, (void *)0); 113 memset(logname, 0, sizeof(logname)); 114 while (1) { 115 n = read(0, &c, 1); 116 if (n < 0) 117 eprintf("read:"); 118 if (n == 0) 119 return 1; 120 if (i >= sizeof(logname) - 1) 121 eprintf("login name too long\n"); 122 if (c == '\n' || c == '\r') 123 break; 124 logname[i++] = c; 125 } 126 if (logname[0] == '-') 127 eprintf("login name cannot start with '-'\n"); 128 if (logname[0] == '\0') 129 return 1; 130 wexecvp_self("login", (char *const[]){"login", "-p", logname, NULL}); 131 return 0; 132 }