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