12 #include <sys/types.h>
14 #include <sys/ioctl.h>
16 #include <sys/epoll.h>
17 #include <sys/signalfd.h>
20 typedef struct tty_t {
33 /* Helper functions */
34 void error(const char *fmt, ...)
38 fprintf(stderr, "Error ");
39 vfprintf(stderr, fmt, ap);
40 fprintf(stderr, ": %s\n", strerror(errno));
46 int add_poll(int fd, void *ptr)
48 struct epoll_event ctl = {
52 return epoll_ctl(epoll, EPOLL_CTL_ADD, fd, &ctl);
57 return epoll_ctl(epoll, EPOLL_CTL_DEL, fd, NULL);
60 static int start_tty(tty_t *tty)
62 const char *prompt = "[Press enter to login]";
65 tty->fd = open(tty->path, O_RDWR|O_NOCTTY|O_NONBLOCK|O_CLOEXEC, 0);
68 tcgetattr(tty->fd, &attr);
69 attr.c_lflag &= ~ECHO;
70 tcsetattr(tty->fd, TCSANOW, &attr);
71 write(tty->fd, "\033c", 2);
72 write(tty->fd, "\033[?1c", 5);
73 write(tty->fd, prompt, strlen(prompt));
74 return add_poll(tty->fd, tty);
77 static void read_tty(tty_t *tty)
81 while (read(tty->fd, &ch, 1) == 1)
82 if (ch == '\n' || ch == '\r')
86 if ((tty->pid = fork()) < 0)
89 if (putenv("TERM=linux"))
90 error("setting environment");
93 if (write(tty->fd, "\033c", 2) < 0)
94 error("resetting tty");
95 if ((flags = fcntl(tty->fd, F_GETFL)) < 0)
96 error("getting fd flags");
97 if (fcntl(tty->fd, F_SETFL, flags&~O_NONBLOCK) < 0)
98 error("setting blocking flags");
99 if (ioctl(tty->fd, TIOCSCTTY, 0) < 0)
100 error("setting ctty");
101 if (dup2(tty->fd, 0) != 0)
102 error("setting stdin");
103 if (dup2(tty->fd, 1) != 1)
104 error("setting stdout");
105 if (dup2(tty->fd, 2) != 2)
106 error("setting stderr");
107 if (execl("/bin/login", "login", NULL) < 0)
108 error("execing login program");
116 struct signalfd_siginfo info;
117 if (read(sigs, &info, sizeof(info)) != sizeof(info))
119 if (info.ssi_signo != SIGCHLD)
125 while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
126 for (tty = ttys; tty; tty = tty->next) {
127 if (pid == tty->pid) {
136 int main(int argc, char **argv)
142 /* Check arguments */
144 printf("usage: gettyd <tty> ...\n");
150 sigaddset(&mask, SIGCHLD);
151 sigaddset(&mask, SIGHUP);
152 if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0)
153 error("blocking signals");
154 if ((sigs = signalfd(-1, &mask, SFD_CLOEXEC)) < 0)
155 error("creating signal fd");
156 if ((epoll = epoll_create1(EPOLL_CLOEXEC)) < 0)
157 error("creating epoll");
158 if (add_poll(sigs, &sigs) < 0)
159 error("adding signal epoll");
162 for (i = 1; i < argc; i++) {
163 if (!(tty = malloc(sizeof(tty_t))))
164 error("allocating memory");
165 if (asprintf(&tty->path, "/dev/%s", argv[i]) < 0)
166 error("allocating path name");
167 if (start_tty(tty) < 0)
168 error("starting tty '%s'", tty->path);
176 struct epoll_event event;
178 count = epoll_wait(epoll, &event, 1, -1);
183 if (event.data.ptr == &sigs)
186 read_tty(event.data.ptr);