]> git.ipfire.org Git - people/amarx/ipfire-3.x.git/blob - initscripts/src/securetty.c
Change file layout of the makefiles.
[people/amarx/ipfire-3.x.git] / initscripts / src / securetty.c
1
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <syslog.h>
9 #include <unistd.h>
10
11 #include <sys/types.h>
12 #include <sys/stat.h>
13
14 void alarm_handler(int num) {
15 return;
16 }
17
18 int open_and_lock_securetty() {
19 int fd;
20 struct flock lock;
21 struct sigaction act, oldact;
22
23 lock.l_type = F_WRLCK;
24 lock.l_whence = SEEK_SET;
25 lock.l_start = 0;
26 lock.l_len = 0;
27
28 fd = open("/etc/securetty", O_RDWR);
29 if (fd == -1) {
30 syslog(LOG_ERR, "Couldn't open /etc/securetty: %s",strerror(errno));
31 return -1;
32 }
33 act.sa_handler = alarm_handler;
34 act.sa_flags = 0;
35 sigaction(SIGALRM, &act, &oldact);
36 alarm(2);
37 while (fcntl(fd, F_SETLKW, &lock) == -1) {
38 if (errno == EINTR) {
39 syslog(LOG_ERR, "Couldn't lock /etc/securetty: Timeout exceeded");
40 } else {
41 syslog(LOG_ERR, "Couldn't lock /etc/securetty: %s",strerror(errno));
42 }
43 return -1;
44 }
45 alarm(0);
46 sigaction(SIGALRM, &oldact, NULL);
47 return fd;
48 }
49
50 int rewrite_securetty(char *terminal) {
51 int fd;
52 char *buf, *pos;
53 struct stat sbuf;
54
55 fd = open_and_lock_securetty();
56 if (fd == -1)
57 return 1;
58 if (fstat(fd, &sbuf) == -1) {
59 close(fd);
60 syslog(LOG_ERR, "Couldn't stat /etc/securetty: %s",strerror(errno));
61 return 1;
62 }
63 buf = malloc(sbuf.st_size + 1);
64 if (read(fd, buf, sbuf.st_size) != sbuf.st_size) {
65 close(fd);
66 syslog(LOG_ERR, "Couldn't read /etc/securetty: %s",strerror(errno));
67 return 1;
68 }
69 if (!strncmp(buf,terminal,strlen(terminal)) && buf[strlen(terminal)] == '\n')
70 goto out_ok;
71 if ((pos = strstr(buf, terminal))) {
72 if (pos[strlen(terminal)] == '\n' && *(pos-1) == '\n')
73 goto out_ok;
74 }
75 if (lseek(fd, 0, SEEK_END) == -1) {
76 close(fd);
77 syslog(LOG_ERR, "Couldn't seek to end of /etc/securetty: %s",strerror(errno));
78 return 1;
79 }
80 write(fd, terminal, strlen(terminal));
81 write(fd, "\n", 1);
82 out_ok:
83 close(fd);
84 return 0;
85 }
86
87 int main(int argc, char **argv) {
88 if (argc < 2 ) {
89 fprintf(stderr, "Usage: securetty <device>\n");
90 exit(1);
91 }
92 openlog("securetty", LOG_CONS, LOG_DAEMON);
93 return rewrite_securetty(argv[1]);
94 }