]> ruderich.org/simon Gitweb - wall-notify/wall-notify.git/blob - src/wall-notify.c
exit if the current X11 session terminates
[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 #ifndef DONT_USE_X11
46 # include <pthread.h>
47 # include <X11/Xlib.h>
48 #endif
49
50
51 static void sig_handler(int signal) {
52     (void)signal;
53 }
54 static void setup_signals(void) {
55     struct sigaction action;
56
57     memset(&action, 0, sizeof(action));
58     sigemptyset(&action.sa_mask);
59     action.sa_handler = sig_handler;
60
61     /* Handle all important signals which might be sent to us so we break out
62      * of the read()-loop below and can perform our cleanup. */
63     sigaction(SIGHUP,  &action, NULL);
64     sigaction(SIGINT,  &action, NULL);
65     sigaction(SIGQUIT, &action, NULL);
66     sigaction(SIGUSR1, &action, NULL);
67     sigaction(SIGUSR2, &action, NULL);
68 }
69
70 static int open_tty(void) {
71     int ptm;
72     const char *name;
73
74     ptm = posix_openpt(O_RDWR);
75     if (ptm < 0) {
76         return -1;
77     }
78     if (grantpt(ptm) != 0) {
79         return -1;
80     }
81
82     /* Prevent write access for other users so they can't use wall to send
83      * messages to this program. */
84     name = ptsname(ptm);
85     if (!name) {
86         return -1;
87     }
88     if (chmod(name, S_IRUSR | S_IWUSR) != 0) {
89         return -1;
90     }
91
92     if (unlockpt(ptm) != 0) {
93         return -1;
94     }
95
96     return ptm;
97 }
98
99 #ifdef USE_UTMPX
100 static const char *skip_prefix(const char *string, const char *prefix) {
101     size_t length = strlen(prefix);
102
103     if (!strncmp(string, prefix, length)) {
104         return string + length;
105     } else {
106         return string;
107     }
108 }
109 static int set_utmpx(short type, int ptm) {
110     struct utmpx entry;
111
112     const char *tty, *user, *id, *line;
113     struct timeval now;
114
115     user = getpwuid(getuid())->pw_name;
116     gettimeofday(&now, NULL);
117
118     tty = ptsname(ptm);
119     if (!tty) {
120         return 0;
121     }
122
123     id   = skip_prefix(tty, "/dev/pts/");
124     line = skip_prefix(tty, "/dev/");
125
126     /* Create utmp entry for the given terminal. */
127     memset(&entry, 0, sizeof(entry));
128
129     snprintf(entry.ut_user, sizeof(entry.ut_user), "%s", user);
130     snprintf(entry.ut_id,   sizeof(entry.ut_id),   "%s", id);
131     snprintf(entry.ut_line, sizeof(entry.ut_line), "%s", line);
132
133     entry.ut_pid  = getpid();
134     entry.ut_type = type;
135     entry.ut_tv.tv_sec  = now.tv_sec;
136     entry.ut_tv.tv_usec = now.tv_usec;
137
138     /* Write the entry to the utmp file. */
139     setutxent();
140     if (!pututxline(&entry)) {
141         return 0;
142     }
143     endutxent();
144
145     return 1;
146 }
147 #endif
148 static int login(int ptm) {
149 #if defined(USE_UTEMPTER)
150     int result = utempter_add_record(ptm, NULL);
151     /* Exit value of utempter_*() is not correct on all systems, e.g.
152      * FreeBSD() always returns 0. Checking the utmpx database manually is
153      * difficult because we don't know the exact values for ut_id and ut_line,
154      * therefore we only check the return value on systems known to return a
155      * useful value. */
156 # ifndef __linux
157     result = 1;
158 # endif
159     return result;
160 #elif defined(USE_UTMPX)
161     return set_utmpx(USER_PROCESS, ptm);
162 #else
163 # error "neither USE_UTEMPTER nor USE_UTMPX defined"
164 #endif
165 }
166 static int logout(int ptm) {
167 #if defined(USE_UTEMPTER)
168     int result = utempter_remove_record(ptm);
169     /* See above. */
170 # ifndef __linux
171     result = 1;
172 # endif
173     return result;
174 #elif defined(USE_UTMPX)
175     return set_utmpx(DEAD_PROCESS, ptm);
176 #else
177 # error "neither USE_UTEMPTER nor USE_UTMPX defined"
178 #endif
179 }
180
181 static int wait_for_write(int fd, int timeout) {
182     fd_set rfds;
183     struct timeval tv;
184     int result;
185
186     FD_ZERO(&rfds);
187     FD_SET(fd, &rfds);
188
189     tv.tv_sec  = timeout;
190     tv.tv_usec = 0;
191
192     result = select(fd + 1, &rfds, NULL, NULL, &tv);
193     if (result < 0) {
194         perror("select");
195         return 0;
196     }
197     if (result == 0) {
198         /* Timeout. */
199         return 0;
200     }
201
202     /* Got more data to read. */
203     return 1;
204 }
205
206 static void pass_buffer_to_program(const char *buffer, size_t length, char **argv) {
207     int fds[2];
208     FILE *fh;
209
210     pid_t pid;
211
212     if (pipe(fds) != 0) {
213         perror("pipe");
214         return;
215     }
216
217     fh = fdopen(fds[1] /* write side */, "w");
218     if (!fh) {
219         perror("fdopen");
220         close(fds[0]);
221         close(fds[1]);
222         return;
223     }
224
225     pid = fork();
226     if (pid < 0) {
227         perror("fork");
228         goto out;
229     } else if (pid == 0) {
230         /* child */
231
232         close(fds[1]); /* write side */
233
234         /* Pass read side as stdin to the program. */
235         if (dup2(fds[0], STDIN_FILENO) < 0) {
236             perror("dup2");
237             exit(EXIT_FAILURE);
238         }
239         close(fds[0]);
240
241         /* Double fork so `wall-notify` doesn't have to wait for the
242          * notification process to terminate. We can't just use
243          * signal(SIGCHLD, SIG_IGN); because utempter on at least FreeBSD
244          * doesn't work if SIGCHLD is ignored. */
245         pid = fork();
246         if (pid < 0) {
247             perror("fork");
248             exit(EXIT_FAILURE);
249         } else if (pid == 0) {
250             execvp(argv[0], argv);
251             perror("execvp");
252             exit(EXIT_FAILURE);
253         }
254
255         exit(EXIT_SUCCESS);
256     }
257     /* father */
258
259     if (fwrite(buffer, 1, length, fh) != length) {
260         perror("fwrite");
261         /* continue to perform cleanup */
262     }
263
264 out:
265     close(fds[0]); /* read side */
266     fclose(fh);
267
268     if (waitpid(pid, NULL, 0) < 0) {
269         perror("waitpid");
270     }
271 }
272 static void handle_wall(int fd, char **argv) {
273     char buffer[4096];
274     ssize_t r;
275
276     assert(SSIZE_MAX <= SIZE_MAX);
277     while ((r = read(fd, buffer, sizeof(buffer))) > 0) {
278         size_t space;
279         ssize_t r2;
280
281         /* To prevent partial messages (sometimes it takes multiple reads to
282          * get the complete message) wait for a short time to get the rest of
283          * the message. */
284         space = sizeof(buffer) - (size_t)r;
285         while (space > 0 && wait_for_write(fd, 1 /* second */)) {
286             r2 = read(fd, buffer + r, space);
287             if (r2 <= 0) {
288                 break;
289             }
290             r += r2;
291             space -= (size_t)r2;
292         }
293
294         pass_buffer_to_program(buffer, (size_t)r, argv);
295     }
296 }
297 #ifndef DONT_USE_X11
298 static void *x11_event_loop_thread(void *unused) {
299     Display *display;
300     XEvent event;
301
302     (void)unused;
303
304     pthread_detach(pthread_self());
305
306     display = XOpenDisplay(NULL);
307     if (!display) {
308         fprintf(stderr, "failed to connect to X server\n");
309         exit(EXIT_FAILURE);
310     }
311
312     /* Do nothing. We just want to die if the X11 session is closed. */
313     while (1) {
314         XNextEvent(display, &event);
315     }
316 }
317 #endif
318
319 static void usage(const char *argv0) {
320     fprintf(stderr, "usage: %s <cmd args..>\n", argv0);
321     exit(EXIT_FAILURE);
322 }
323
324
325 int main(int argc, char **argv) {
326     int ptm, pts;
327     char *name;
328     const char *argv0;
329
330     argv0 = argv[0];
331     /* Don't pass our argv[0] to the notification program. */
332     argv++;
333
334     if (argc < 2) {
335         usage(argv0);
336     }
337
338     ptm = open_tty();
339     if (ptm < 0) {
340         perror("open_tty");
341         exit(EXIT_FAILURE);
342     }
343     name = ptsname(ptm);
344     if (!name) {
345         perror("ptsname");
346         exit(EXIT_FAILURE);
347     }
348
349 #ifdef DEBUG
350     printf("%s\n", name);
351 #endif
352
353     /* We need to open the slave or reading from the master yields EOF after
354      * the first wall write to it. */
355     pts = open(name, O_RDWR);
356     if (pts < 0) {
357         perror(name);
358         exit(EXIT_FAILURE);
359     }
360
361 #ifndef DONT_USE_X11
362     /* Start a thread which connects to X11. This way we die if the user logs
363      * out of its X11 session. */
364     {
365         pthread_t tid;
366
367         if (pthread_create(&tid, NULL, x11_event_loop_thread, NULL) != 0) {
368             perror("pthread_create");
369             exit(EXIT_FAILURE);
370         }
371     }
372 #endif
373
374     /* Cleanup on signals. Necessary before login(). */
375     setup_signals();
376
377     if (!login(ptm)) {
378         perror("login");
379         exit(EXIT_FAILURE);
380     }
381
382     /* Main loop. Handle all wall messages sent to our PTY. */
383     handle_wall(ptm, argv);
384
385     if (!logout(ptm)) {
386         perror("logout");
387         exit(EXIT_FAILURE);
388     }
389
390     close(ptm);
391     close(pts);
392
393     return EXIT_SUCCESS;
394 }