]> git.sur5r.net Git - i3/i3/blob - src/util.c
d8fb30fe99b55a72cc45e6349aed837b97509d05
[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     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
253     if (fd == -1) {
254         perror("open()");
255         free(filename);
256         return NULL;
257     }
258
259     size_t written = 0;
260     while (written < length) {
261         int n = write(fd, payload + written, length - written);
262         /* TODO: correct error-handling */
263         if (n == -1) {
264             perror("write()");
265             free(filename);
266             close(fd);
267             return NULL;
268         }
269         if (n == 0) {
270             DLOG("write == 0?\n");
271             free(filename);
272             close(fd);
273             return NULL;
274         }
275         written += n;
276         DLOG("written: %zd of %zd\n", written, length);
277     }
278     close(fd);
279
280     if (length > 0) {
281         DLOG("layout: %.*s\n", (int)length, payload);
282     }
283
284     y(free);
285
286     return filename;
287 }
288
289 /*
290  * Restart i3 in-place
291  * appends -a to argument list to disable autostart
292  *
293  */
294 void i3_restart(bool forget_layout) {
295     char *restart_filename = forget_layout ? NULL : store_restart_layout();
296
297     kill_nagbar(&config_error_nagbar_pid, true);
298     kill_nagbar(&command_error_nagbar_pid, true);
299
300     restore_geometry();
301
302     ipc_shutdown();
303
304     LOG("restarting \"%s\"...\n", start_argv[0]);
305     /* make sure -a is in the argument list or append it */
306     start_argv = append_argument(start_argv, "-a");
307
308     /* replace -r <file> so that the layout is restored */
309     if (restart_filename != NULL) {
310         /* create the new argv */
311         int num_args;
312         for (num_args = 0; start_argv[num_args] != NULL; num_args++);
313         char **new_argv = scalloc((num_args + 3) * sizeof(char*));
314
315         /* copy the arguments, but skip the ones we'll replace */
316         int write_index = 0;
317         bool skip_next = false;
318         for (int i = 0; i < num_args; ++i) {
319             if (skip_next)
320                 skip_next = false;
321             else if (!strcmp(start_argv[i], "-r") ||
322                      !strcmp(start_argv[i], "--restart"))
323                 skip_next = true;
324             else
325                 new_argv[write_index++] = start_argv[i];
326         }
327
328         /* add the arguments we'll replace */
329         new_argv[write_index++] = "--restart";
330         new_argv[write_index] = restart_filename;
331
332         /* swap the argvs */
333         start_argv = new_argv;
334     }
335
336     execvp(start_argv[0], start_argv);
337     /* not reached */
338 }
339
340 #if defined(__OpenBSD__) || defined(__APPLE__)
341
342 /*
343  * Taken from FreeBSD
344  * Find the first occurrence of the byte string s in byte string l.
345  *
346  */
347 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
348     register char *cur, *last;
349     const char *cl = (const char *)l;
350     const char *cs = (const char *)s;
351
352     /* we need something to compare */
353     if (l_len == 0 || s_len == 0)
354         return NULL;
355
356     /* "s" must be smaller or equal to "l" */
357     if (l_len < s_len)
358         return NULL;
359
360     /* special case where s_len == 1 */
361     if (s_len == 1)
362         return memchr(l, (int)*cs, l_len);
363
364     /* the last position where its possible to find "s" in "l" */
365     last = (char *)cl + l_len - s_len;
366
367     for (cur = (char *)cl; cur <= last; cur++)
368         if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
369             return cur;
370
371     return NULL;
372 }
373
374 #endif
375
376 /*
377  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
378  * it exited (or could not be started, depending on the exit code).
379  *
380  */
381 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
382     ev_child_stop(EV_A_ watcher);
383
384     if (!WIFEXITED(watcher->rstatus)) {
385         ELOG("ERROR: i3-nagbar did not exit normally.\n");
386         return;
387     }
388
389     int exitcode = WEXITSTATUS(watcher->rstatus);
390     DLOG("i3-nagbar process exited with status %d\n", exitcode);
391     if (exitcode == 2) {
392         ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
393     }
394
395     *((pid_t*)watcher->data) = -1;
396 }
397
398 /*
399  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
400  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
401  *
402  */
403 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
404     pid_t *nagbar_pid = (pid_t*)watcher->data;
405     if (*nagbar_pid != -1) {
406         LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
407         kill(*nagbar_pid, SIGKILL);
408     }
409 }
410
411 /*
412  * Starts an i3-nagbar instance with the given parameters. Takes care of
413  * handling SIGCHLD and killing i3-nagbar when i3 exits.
414  *
415  * The resulting PID will be stored in *nagbar_pid and can be used with
416  * kill_nagbar() to kill the bar later on.
417  *
418  */
419 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
420     if (*nagbar_pid != -1) {
421         DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
422         return;
423     }
424
425     *nagbar_pid = fork();
426     if (*nagbar_pid == -1) {
427         warn("Could not fork()");
428         return;
429     }
430
431     /* child */
432     if (*nagbar_pid == 0)
433         exec_i3_utility("i3-nagbar", argv);
434
435     DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
436
437     /* parent */
438     /* install a child watcher */
439     ev_child *child = smalloc(sizeof(ev_child));
440     ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
441     child->data = nagbar_pid;
442     ev_child_start(main_loop, child);
443
444     /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
445      * still running) */
446     ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
447     ev_cleanup_init(cleanup, nagbar_cleanup);
448     cleanup->data = nagbar_pid;
449     ev_cleanup_start(main_loop, cleanup);
450 }
451
452 /*
453  * Kills the i3-nagbar process, if *nagbar_pid != -1.
454  *
455  * If wait_for_it is set (restarting i3), this function will waitpid(),
456  * otherwise, ev is assumed to handle it (reloading).
457  *
458  */
459 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
460     if (*nagbar_pid == -1)
461         return;
462
463     if (kill(*nagbar_pid, SIGTERM) == -1)
464         warn("kill(configerror_nagbar) failed");
465
466     if (!wait_for_it)
467         return;
468
469     /* When restarting, we don’t enter the ev main loop anymore and after the
470      * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
471      * for us and we would end up with a <defunct> process. Therefore we
472      * waitpid() here. */
473     waitpid(*nagbar_pid, NULL, 0);
474 }