]> git.sur5r.net Git - i3/i3/blob - src/util.c
Add a safe wrapper for write and fix some warnings
[i3/i3] / src / util.c
1 #undef I3__FILE__
2 #define I3__FILE__ "util.c"
3 /*
4  * vim:ts=4:sw=4:expandtab
5  *
6  * i3 - an improved dynamic tiling window manager
7  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
8  *
9  * util.c: Utility functions, which can be useful everywhere within i3 (see
10  *         also libi3).
11  *
12  */
13 #include "all.h"
14
15 #include <sys/wait.h>
16 #include <stdarg.h>
17 #if defined(__OpenBSD__)
18 #include <sys/cdefs.h>
19 #endif
20 #include <fcntl.h>
21 #include <pwd.h>
22 #include <yajl/yajl_version.h>
23 #include <libgen.h>
24 #include <ctype.h>
25
26 #define SN_API_NOT_YET_FROZEN 1
27 #include <libsn/sn-launcher.h>
28
29 int min(int a, int b) {
30     return (a < b ? a : b);
31 }
32
33 int max(int a, int b) {
34     return (a > b ? a : b);
35 }
36
37 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
38     return (x >= rect.x &&
39             x <= (rect.x + rect.width) &&
40             y >= rect.y &&
41             y <= (rect.y + rect.height));
42 }
43
44 Rect rect_add(Rect a, Rect b) {
45     return (Rect){a.x + b.x,
46                   a.y + b.y,
47                   a.width + b.width,
48                   a.height + b.height};
49 }
50
51 Rect rect_sub(Rect a, Rect b) {
52     return (Rect){a.x - b.x,
53                   a.y - b.y,
54                   a.width - b.width,
55                   a.height - b.height};
56 }
57
58 /*
59  * Returns true if the name consists of only digits.
60  *
61  */
62 __attribute__((pure)) bool name_is_digits(const char *name) {
63     /* positive integers and zero are interpreted as numbers */
64     for (size_t i = 0; i < strlen(name); i++)
65         if (!isdigit(name[i]))
66             return false;
67
68     return true;
69 }
70
71 /*
72  * Parses the workspace name as a number. Returns -1 if the workspace should be
73  * interpreted as a "named workspace".
74  *
75  */
76 long ws_name_to_number(const char *name) {
77     /* positive integers and zero are interpreted as numbers */
78     char *endptr = NULL;
79     long parsed_num = strtol(name, &endptr, 10);
80     if (parsed_num == LONG_MIN ||
81         parsed_num == LONG_MAX ||
82         parsed_num < 0 ||
83         endptr == name) {
84         parsed_num = -1;
85     }
86
87     return parsed_num;
88 }
89
90 /*
91  * Updates *destination with new_value and returns true if it was changed or false
92  * if it was the same
93  *
94  */
95 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
96     uint32_t old_value = *destination;
97
98     return ((*destination = new_value) != old_value);
99 }
100
101 /*
102  * exec()s an i3 utility, for example the config file migration script or
103  * i3-nagbar. This function first searches $PATH for the given utility named,
104  * then falls back to the dirname() of the i3 executable path and then falls
105  * back to the dirname() of the target of /proc/self/exe (on linux).
106  *
107  * This function should be called after fork()ing.
108  *
109  * The first argument of the given argv vector will be overwritten with the
110  * executable name, so pass NULL.
111  *
112  * If the utility cannot be found in any of these locations, it exits with
113  * return code 2.
114  *
115  */
116 void exec_i3_utility(char *name, char *argv[]) {
117     /* start the migration script, search PATH first */
118     char *migratepath = name;
119     argv[0] = migratepath;
120     execvp(migratepath, argv);
121
122     /* if the script is not in path, maybe the user installed to a strange
123      * location and runs the i3 binary with an absolute path. We use
124      * argv[0]’s dirname */
125     char *pathbuf = strdup(start_argv[0]);
126     char *dir = dirname(pathbuf);
127     sasprintf(&migratepath, "%s/%s", dir, name);
128     argv[0] = migratepath;
129     execvp(migratepath, argv);
130
131 #if defined(__linux__)
132     /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
133     char buffer[BUFSIZ];
134     if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
135         warn("could not read /proc/self/exe");
136         _exit(1);
137     }
138     dir = dirname(buffer);
139     sasprintf(&migratepath, "%s/%s", dir, name);
140     argv[0] = migratepath;
141     execvp(migratepath, argv);
142 #endif
143
144     warn("Could not start %s", name);
145     _exit(2);
146 }
147
148 /*
149  * Checks a generic cookie for errors and quits with the given message if there
150  * was an error.
151  *
152  */
153 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
154     xcb_generic_error_t *error = xcb_request_check(conn, cookie);
155     if (error != NULL) {
156         fprintf(stderr, "ERROR: %s (X error %d)\n", err_message, error->error_code);
157         xcb_disconnect(conn);
158         exit(-1);
159     }
160 }
161
162 /*
163  * This function resolves ~ in pathnames.
164  * It may resolve wildcards in the first part of the path, but if no match
165  * or multiple matches are found, it just returns a copy of path as given.
166  *
167  */
168 char *resolve_tilde(const char *path) {
169     static glob_t globbuf;
170     char *head, *tail, *result;
171
172     tail = strchr(path, '/');
173     head = strndup(path, tail ? (size_t)(tail - path) : strlen(path));
174
175     int res = glob(head, GLOB_TILDE, NULL, &globbuf);
176     free(head);
177     /* no match, or many wildcard matches are bad */
178     if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
179         result = sstrdup(path);
180     else if (res != 0) {
181         die("glob() failed");
182     } else {
183         head = globbuf.gl_pathv[0];
184         result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
185         strncpy(result, head, strlen(head));
186         if (tail)
187             strncat(result, tail, strlen(tail));
188     }
189     globfree(&globbuf);
190
191     return result;
192 }
193
194 /*
195  * Checks if the given path exists by calling stat().
196  *
197  */
198 bool path_exists(const char *path) {
199     struct stat buf;
200     return (stat(path, &buf) == 0);
201 }
202
203 /*
204  * Goes through the list of arguments (for exec()) and checks if the given argument
205  * is present. If not, it copies the arguments (because we cannot realloc it) and
206  * appends the given argument.
207  *
208  */
209 static char **append_argument(char **original, char *argument) {
210     int num_args;
211     for (num_args = 0; original[num_args] != NULL; num_args++) {
212         DLOG("original argument: \"%s\"\n", original[num_args]);
213         /* If the argument is already present we return the original pointer */
214         if (strcmp(original[num_args], argument) == 0)
215             return original;
216     }
217     /* Copy the original array */
218     char **result = smalloc((num_args + 2) * sizeof(char *));
219     memcpy(result, original, num_args * sizeof(char *));
220     result[num_args] = argument;
221     result[num_args + 1] = NULL;
222
223     return result;
224 }
225
226 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
227 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
228
229 char *store_restart_layout(void) {
230     setlocale(LC_NUMERIC, "C");
231     yajl_gen gen = yajl_gen_alloc(NULL);
232
233     dump_node(gen, croot, true);
234
235     setlocale(LC_NUMERIC, "");
236
237     const unsigned char *payload;
238     size_t length;
239     y(get_buf, &payload, &length);
240
241     /* create a temporary file if one hasn't been specified, or just
242      * resolve the tildes in the specified path */
243     char *filename;
244     if (config.restart_state_path == NULL) {
245         filename = get_process_filename("restart-state");
246         if (!filename)
247             return NULL;
248     } else {
249         filename = resolve_tilde(config.restart_state_path);
250     }
251
252     /* create the directory, it could have been cleaned up before restarting or
253      * may not exist at all in case it was user-specified. */
254     char *filenamecopy = sstrdup(filename);
255     char *base = dirname(filenamecopy);
256     DLOG("Creating \"%s\" for storing the restart layout\n", base);
257     if (!mkdirp(base))
258         ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
259     free(filenamecopy);
260
261     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
262     if (fd == -1) {
263         perror("open()");
264         free(filename);
265         return NULL;
266     }
267
268     if (writeall(fd, payload, length) == -1) {
269         ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
270         free(filename);
271         close(fd);
272         return NULL;
273     }
274
275     close(fd);
276
277     if (length > 0) {
278         DLOG("layout: %.*s\n", (int)length, payload);
279     }
280
281     y(free);
282
283     return filename;
284 }
285
286 /*
287  * Restart i3 in-place
288  * appends -a to argument list to disable autostart
289  *
290  */
291 void i3_restart(bool forget_layout) {
292     char *restart_filename = forget_layout ? NULL : store_restart_layout();
293
294     kill_nagbar(&config_error_nagbar_pid, true);
295     kill_nagbar(&command_error_nagbar_pid, true);
296
297     restore_geometry();
298
299     ipc_shutdown();
300
301     LOG("restarting \"%s\"...\n", start_argv[0]);
302     /* make sure -a is in the argument list or append it */
303     start_argv = append_argument(start_argv, "-a");
304
305     /* replace -r <file> so that the layout is restored */
306     if (restart_filename != NULL) {
307         /* create the new argv */
308         int num_args;
309         for (num_args = 0; start_argv[num_args] != NULL; num_args++)
310             ;
311         char **new_argv = scalloc((num_args + 3) * sizeof(char *));
312
313         /* copy the arguments, but skip the ones we'll replace */
314         int write_index = 0;
315         bool skip_next = false;
316         for (int i = 0; i < num_args; ++i) {
317             if (skip_next)
318                 skip_next = false;
319             else if (!strcmp(start_argv[i], "-r") ||
320                      !strcmp(start_argv[i], "--restart"))
321                 skip_next = true;
322             else
323                 new_argv[write_index++] = start_argv[i];
324         }
325
326         /* add the arguments we'll replace */
327         new_argv[write_index++] = "--restart";
328         new_argv[write_index] = restart_filename;
329
330         /* swap the argvs */
331         start_argv = new_argv;
332     }
333
334     execvp(start_argv[0], start_argv);
335     /* not reached */
336 }
337
338 #if defined(__OpenBSD__) || defined(__APPLE__)
339
340 /*
341  * Taken from FreeBSD
342  * Find the first occurrence of the byte string s in byte string l.
343  *
344  */
345 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
346     register char *cur, *last;
347     const char *cl = (const char *)l;
348     const char *cs = (const char *)s;
349
350     /* we need something to compare */
351     if (l_len == 0 || s_len == 0)
352         return NULL;
353
354     /* "s" must be smaller or equal to "l" */
355     if (l_len < s_len)
356         return NULL;
357
358     /* special case where s_len == 1 */
359     if (s_len == 1)
360         return memchr(l, (int)*cs, l_len);
361
362     /* the last position where its possible to find "s" in "l" */
363     last = (char *)cl + l_len - s_len;
364
365     for (cur = (char *)cl; cur <= last; cur++)
366         if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
367             return cur;
368
369     return NULL;
370 }
371
372 #endif
373
374 /*
375  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
376  * it exited (or could not be started, depending on the exit code).
377  *
378  */
379 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
380     ev_child_stop(EV_A_ watcher);
381
382     if (!WIFEXITED(watcher->rstatus)) {
383         ELOG("ERROR: i3-nagbar did not exit normally.\n");
384         return;
385     }
386
387     int exitcode = WEXITSTATUS(watcher->rstatus);
388     DLOG("i3-nagbar process exited with status %d\n", exitcode);
389     if (exitcode == 2) {
390         ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
391     }
392
393     *((pid_t *)watcher->data) = -1;
394 }
395
396 /*
397  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
398  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
399  *
400  */
401 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
402     pid_t *nagbar_pid = (pid_t *)watcher->data;
403     if (*nagbar_pid != -1) {
404         LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
405         kill(*nagbar_pid, SIGKILL);
406     }
407 }
408
409 /*
410  * Starts an i3-nagbar instance with the given parameters. Takes care of
411  * handling SIGCHLD and killing i3-nagbar when i3 exits.
412  *
413  * The resulting PID will be stored in *nagbar_pid and can be used with
414  * kill_nagbar() to kill the bar later on.
415  *
416  */
417 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
418     if (*nagbar_pid != -1) {
419         DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
420         return;
421     }
422
423     *nagbar_pid = fork();
424     if (*nagbar_pid == -1) {
425         warn("Could not fork()");
426         return;
427     }
428
429     /* child */
430     if (*nagbar_pid == 0)
431         exec_i3_utility("i3-nagbar", argv);
432
433     DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
434
435     /* parent */
436     /* install a child watcher */
437     ev_child *child = smalloc(sizeof(ev_child));
438     ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
439     child->data = nagbar_pid;
440     ev_child_start(main_loop, child);
441
442     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
443      * still running) */
444     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
445     ev_cleanup_init(cleanup, nagbar_cleanup);
446     cleanup->data = nagbar_pid;
447     ev_cleanup_start(main_loop, cleanup);
448 }
449
450 /*
451  * Kills the i3-nagbar process, if *nagbar_pid != -1.
452  *
453  * If wait_for_it is set (restarting i3), this function will waitpid(),
454  * otherwise, ev is assumed to handle it (reloading).
455  *
456  */
457 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
458     if (*nagbar_pid == -1)
459         return;
460
461     if (kill(*nagbar_pid, SIGTERM) == -1)
462         warn("kill(configerror_nagbar) failed");
463
464     if (!wait_for_it)
465         return;
466
467     /* When restarting, we don’t enter the ev main loop anymore and after the
468      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
469      * for us and we would end up with a <defunct> process. Therefore we
470      * waitpid() here. */
471     waitpid(*nagbar_pid, NULL, 0);
472 }