]> ruderich.org/simon Gitweb - wall-notify/wall-notify.git/blob - src/wall-notify.c
use double-fork for notification processes
[wall-notify/wall-notify.git] / src / wall-notify.c
1 /*
2  * Receive wall messages and pass them to a notification program via stdin.
3  *
4  * Copyright (C) 2014  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #include <config.h>
22
23 #include <assert.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <pwd.h>
27 #include <signal.h>
28 #include <stdint.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/select.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <unistd.h>
38
39 #ifdef USE_UTEMPTER
40 # include <utempter.h>
41 #endif
42 #ifdef USE_UTMPX
43 # include <utmpx.h>
44 #endif
45
46
47 static void sig_handler(int signal) {
48     (void)signal;
49 }
50 static void setup_signals(void) {
51     struct sigaction action;
52
53     memset(&action, 0, sizeof(action));
54     sigemptyset(&action.sa_mask);
55     action.sa_handler = sig_handler;
56
57     /* Handle all important signals which might be sent to us so we break out
58      * of the read()-loop below and can perform our cleanup. */
59     sigaction(SIGHUP,  &action, NULL);
60     sigaction(SIGINT,  &action, NULL);
61     sigaction(SIGQUIT, &action, NULL);
62     sigaction(SIGUSR1, &action, NULL);
63     sigaction(SIGUSR2, &action, NULL);
64 }
65
66 static int open_tty(void) {
67     int ptm;
68     const char *name;
69
70     ptm = posix_openpt(O_RDWR);
71     if (ptm < 0) {
72         return -1;
73     }
74     if (grantpt(ptm) != 0) {
75         return -1;
76     }
77
78     /* Prevent write access for other users so they can't use wall to send
79      * messages to this program. */
80     name = ptsname(ptm);
81     if (!name) {
82         return -1;
83     }
84     if (chmod(name, S_IRUSR | S_IWUSR) != 0) {
85         return -1;
86     }
87
88     if (unlockpt(ptm) != 0) {
89         return -1;
90     }
91
92     return ptm;
93 }
94
95 #ifdef USE_UTMPX
96 static const char *skip_prefix(const char *string, const char *prefix) {
97     size_t length = strlen(prefix);
98
99     if (!strncmp(string, prefix, length)) {
100         return string + length;
101     } else {
102         return string;
103     }
104 }
105 static int set_utmpx(short type, int ptm) {
106     struct utmpx entry;
107
108     const char *tty, *user, *id, *line;
109     struct timeval now;
110
111     user = getpwuid(getuid())->pw_name;
112     gettimeofday(&now, NULL);
113
114     tty = ptsname(ptm);
115     if (!tty) {
116         return 0;
117     }
118
119     id   = skip_prefix(tty, "/dev/pts/");
120     line = skip_prefix(tty, "/dev/");
121
122     /* Create utmp entry for the given terminal. */
123     memset(&entry, 0, sizeof(entry));
124
125     snprintf(entry.ut_user, sizeof(entry.ut_user), "%s", user);
126     snprintf(entry.ut_id,   sizeof(entry.ut_id),   "%s", id);
127     snprintf(entry.ut_line, sizeof(entry.ut_line), "%s", line);
128
129     entry.ut_pid  = getpid();
130     entry.ut_type = type;
131     entry.ut_tv.tv_sec  = now.tv_sec;
132     entry.ut_tv.tv_usec = now.tv_usec;
133
134     /* Write the entry to the utmp file. */
135     setutxent();
136     if (!pututxline(&entry)) {
137         return 0;
138     }
139     endutxent();
140
141     return 1;
142 }
143 #endif
144 static int login(int ptm) {
145 #if defined(USE_UTEMPTER)
146     return utempter_add_record(ptm, NULL);
147 #elif defined(USE_UTMPX)
148     return set_utmpx(USER_PROCESS, ptm);
149 #else
150 # error "neither USE_UTEMPTER nor USE_UTMPX defined"
151 #endif
152 }
153 static int logout(int ptm) {
154 #if defined(USE_UTEMPTER)
155     return utempter_remove_record(ptm);
156 #elif defined(USE_UTMPX)
157     return set_utmpx(DEAD_PROCESS, ptm);
158 #else
159 # error "neither USE_UTEMPTER nor USE_UTMPX defined"
160 #endif
161 }
162
163 static int wait_for_write(int fd, int timeout) {
164     fd_set rfds;
165     struct timeval tv;
166     int result;
167
168     FD_ZERO(&rfds);
169     FD_SET(fd, &rfds);
170
171     tv.tv_sec  = timeout;
172     tv.tv_usec = 0;
173
174     result = select(fd + 1, &rfds, NULL, NULL, &tv);
175     if (result < 0) {
176         perror("select");
177         return 0;
178     }
179     if (result == 0) {
180         /* Timeout. */
181         return 0;
182     }
183
184     /* Got more data to read. */
185     return 1;
186 }
187
188 static void pass_buffer_to_program(const char *buffer, size_t length, char **argv) {
189     int fds[2];
190     FILE *fh;
191
192     pid_t pid;
193
194     /* Skip argv[0]. */
195     argv++;
196
197     if (pipe(fds) != 0) {
198         perror("pipe");
199         return;
200     }
201
202     fh = fdopen(fds[1] /* write side */, "w");
203     if (!fh) {
204         perror("fdopen");
205         close(fds[0]);
206         close(fds[1]);
207         return;
208     }
209
210     pid = fork();
211     if (pid < 0) {
212         perror("fork");
213         goto out;
214     } else if (pid == 0) {
215         /* child */
216
217         close(fds[1]); /* write side */
218
219         /* Pass read side as stdin to the program. */
220         if (dup2(fds[0], STDIN_FILENO) < 0) {
221             perror("dup2");
222             exit(EXIT_FAILURE);
223         }
224         close(fds[0]);
225
226         /* Double fork so `wall-notify` doesn't have to wait for the
227          * notification process to terminate. We can't just use
228          * signal(SIGCHLD, SIG_IGN); because utempter on at least FreeBSD
229          * doesn't work if SIGCHLD is ignored. */
230         pid = fork();
231         if (pid < 0) {
232             perror("fork");
233             exit(EXIT_FAILURE);
234         } else if (pid == 0) {
235             execvp(argv[0], argv);
236             perror("execvp");
237             exit(EXIT_FAILURE);
238         }
239
240         exit(EXIT_SUCCESS);
241     }
242     /* father */
243
244     if (fwrite(buffer, 1, length, fh) != length) {
245         perror("fwrite");
246         /* continue to perform cleanup */
247     }
248
249 out:
250     close(fds[0]); /* read side */
251     fclose(fh);
252
253     if (waitpid(pid, NULL, 0) < 0) {
254         perror("waitpid");
255     }
256 }
257 static void handle_wall(int fd, char **argv) {
258     char buffer[4096];
259     ssize_t r;
260
261     assert(SSIZE_MAX <= SIZE_MAX);
262     while ((r = read(fd, buffer, sizeof(buffer))) > 0) {
263         size_t space;
264         ssize_t r2;
265
266         /* To prevent partial messages (sometimes it takes multiple reads to
267          * get the complete message) wait for a short time to get the rest of
268          * the message. */
269         space = sizeof(buffer) - (size_t)r;
270         while (space > 0 && wait_for_write(fd, 1 /* second */)) {
271             r2 = read(fd, buffer + r, space);
272             if (r2 <= 0) {
273                 break;
274             }
275             r += r2;
276             space -= (size_t)r2;
277         }
278
279         pass_buffer_to_program(buffer, (size_t)r, argv);
280     }
281 }
282
283
284 int main(int argc, char **argv) {
285     int ptm, pts;
286     char *name;
287
288     if (argc < 2) {
289         fprintf(stderr, "usage: %s <cmd args..>\n", argv[0]);
290         exit(EXIT_FAILURE);
291     }
292
293     ptm = open_tty();
294     if (ptm < 0) {
295         perror("open_tty");
296         exit(EXIT_FAILURE);
297     }
298     name = ptsname(ptm);
299     if (!name) {
300         perror("ptsname");
301         exit(EXIT_FAILURE);
302     }
303
304 #ifdef DEBUG
305     printf("%s\n", name);
306 #endif
307
308     /* We need to open the slave or reading from the master yields EOF after
309      * the first wall write to it. */
310     pts = open(name, O_RDWR);
311     if (pts < 0) {
312         perror(name);
313         exit(EXIT_FAILURE);
314     }
315
316     /* Cleanup on signals. Necessary before login(). */
317     setup_signals();
318
319     if (!login(ptm)) {
320         perror("login");
321         exit(EXIT_FAILURE);
322     }
323
324     /* Main loop. Handle all wall messages sent to our PTY. */
325     handle_wall(ptm, argv);
326
327     if (!logout(ptm)) {
328         perror("logout");
329         exit(EXIT_FAILURE);
330     }
331
332     close(ptm);
333     close(pts);
334
335     return EXIT_SUCCESS;
336 }