i3
util.c
Go to the documentation of this file.
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 
45  return (Rect) {a.x + b.x,
46  a.y + b.y,
47  a.width + b.width,
48  a.height + b.height};
49 }
50 
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 {
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 
299 
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 */
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  ;
314  char **new_argv = scalloc((num_args + 3) * sizeof(char *));
315 
316  /* copy the arguments, but skip the ones we'll replace */
317  int write_index = 0;
318  bool skip_next = false;
319  for (int i = 0; i < num_args; ++i) {
320  if (skip_next)
321  skip_next = false;
322  else if (!strcmp(start_argv[i], "-r") ||
323  !strcmp(start_argv[i], "--restart"))
324  skip_next = true;
325  else
326  new_argv[write_index++] = start_argv[i];
327  }
328 
329  /* add the arguments we'll replace */
330  new_argv[write_index++] = "--restart";
331  new_argv[write_index] = restart_filename;
332 
333  /* swap the argvs */
334  start_argv = new_argv;
335  }
336 
337  execvp(start_argv[0], start_argv);
338  /* not reached */
339 }
340 
341 #if defined(__OpenBSD__) || defined(__APPLE__)
342 
343 /*
344  * Taken from FreeBSD
345  * Find the first occurrence of the byte string s in byte string l.
346  *
347  */
348 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
349  register char *cur, *last;
350  const char *cl = (const char *)l;
351  const char *cs = (const char *)s;
352 
353  /* we need something to compare */
354  if (l_len == 0 || s_len == 0)
355  return NULL;
356 
357  /* "s" must be smaller or equal to "l" */
358  if (l_len < s_len)
359  return NULL;
360 
361  /* special case where s_len == 1 */
362  if (s_len == 1)
363  return memchr(l, (int)*cs, l_len);
364 
365  /* the last position where its possible to find "s" in "l" */
366  last = (char *)cl + l_len - s_len;
367 
368  for (cur = (char *)cl; cur <= last; cur++)
369  if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
370  return cur;
371 
372  return NULL;
373 }
374 
375 #endif
376 
377 /*
378  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
379  * it exited (or could not be started, depending on the exit code).
380  *
381  */
382 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
383  ev_child_stop(EV_A_ watcher);
384 
385  if (!WIFEXITED(watcher->rstatus)) {
386  ELOG("ERROR: i3-nagbar did not exit normally.\n");
387  return;
388  }
389 
390  int exitcode = WEXITSTATUS(watcher->rstatus);
391  DLOG("i3-nagbar process exited with status %d\n", exitcode);
392  if (exitcode == 2) {
393  ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
394  }
395 
396  *((pid_t *)watcher->data) = -1;
397 }
398 
399 /*
400  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
401  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
402  *
403  */
404 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
405  pid_t *nagbar_pid = (pid_t *)watcher->data;
406  if (*nagbar_pid != -1) {
407  LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
408  kill(*nagbar_pid, SIGKILL);
409  }
410 }
411 
412 /*
413  * Starts an i3-nagbar instance with the given parameters. Takes care of
414  * handling SIGCHLD and killing i3-nagbar when i3 exits.
415  *
416  * The resulting PID will be stored in *nagbar_pid and can be used with
417  * kill_nagbar() to kill the bar later on.
418  *
419  */
420 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
421  if (*nagbar_pid != -1) {
422  DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
423  return;
424  }
425 
426  *nagbar_pid = fork();
427  if (*nagbar_pid == -1) {
428  warn("Could not fork()");
429  return;
430  }
431 
432  /* child */
433  if (*nagbar_pid == 0)
434  exec_i3_utility("i3-nagbar", argv);
435 
436  DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
437 
438  /* parent */
439  /* install a child watcher */
440  ev_child *child = smalloc(sizeof(ev_child));
441  ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
442  child->data = nagbar_pid;
443  ev_child_start(main_loop, child);
444 
445  /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
446  * still running) */
447  ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
448  ev_cleanup_init(cleanup, nagbar_cleanup);
449  cleanup->data = nagbar_pid;
450  ev_cleanup_start(main_loop, cleanup);
451 }
452 
453 /*
454  * Kills the i3-nagbar process, if *nagbar_pid != -1.
455  *
456  * If wait_for_it is set (restarting i3), this function will waitpid(),
457  * otherwise, ev is assumed to handle it (reloading).
458  *
459  */
460 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
461  if (*nagbar_pid == -1)
462  return;
463 
464  if (kill(*nagbar_pid, SIGTERM) == -1)
465  warn("kill(configerror_nagbar) failed");
466 
467  if (!wait_for_it)
468  return;
469 
470  /* When restarting, we don’t enter the ev main loop anymore and after the
471  * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
472  * for us and we would end up with a <defunct> process. Therefore we
473  * waitpid() here. */
474  waitpid(*nagbar_pid, NULL, 0);
475 }
bool update_if_necessary(uint32_t *destination, const uint32_t new_value)
Updates *destination with new_value and returns true if it was changed or false if it was the same...
Definition: util.c:95
struct reservedpx __attribute__
static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent)
Definition: util.c:404
long ws_name_to_number(const char *name)
Parses the workspace name as a number.
Definition: util.c:76
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
void ipc_shutdown(void)
Calls shutdown() on each socket and closes it.
Definition: ipc.c:98
Rect rect_add(Rect a, Rect b)
Definition: util.c:44
uint32_t y
Definition: data.h:124
void exec_i3_utility(char *name, char *argv[])
exec()s an i3 utility, for example the config file migration script or i3-nagbar. ...
Definition: util.c:116
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
Config config
Definition: config.c:19
xcb_connection_t * conn
Definition: main.c:47
char ** start_argv
Definition: main.c:45
char * store_restart_layout(void)
Definition: util.c:229
Stores a rectangle, for example the size of a window, the child window etc.
Definition: data.h:122
#define LOG(fmt,...)
Definition: libi3.h:76
struct ev_loop * main_loop
Definition: main.c:69
void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart)
Definition: ipc.c:154
bool rect_contains(Rect rect, uint32_t x, uint32_t y)
Definition: util.c:37
static char ** append_argument(char **original, char *argument)
Definition: util.c:209
void i3_restart(bool forget_layout)
Restart i3 in-place appends -a to argument list to disable autostart.
Definition: util.c:294
pid_t command_error_nagbar_pid
Definition: bindings.c:11
#define DLOG(fmt,...)
Definition: libi3.h:86
pid_t config_error_nagbar_pid
Definition: config_parser.c:46
int sasprintf(char **strp, const char *fmt,...)
Safe-wrapper around asprintf which exits if it returns -1 (meaning that there is no more memory avail...
#define die(...)
Definition: util.h:17
uint32_t height
Definition: data.h:126
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:420
Rect rect_sub(Rect a, Rect b)
Definition: util.c:51
void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it)
Kills the i3-nagbar process, if *nagbar_pid != -1.
Definition: util.c:460
void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message)
Checks a generic cookie for errors and quits with the given message if there was an error...
Definition: util.c:153
int max(int a, int b)
Definition: util.c:33
char * resolve_tilde(const char *path)
This function resolves ~ in pathnames.
Definition: util.c:168
const char * restart_state_path
Definition: config.h:95
#define ELOG(fmt,...)
Definition: libi3.h:81
static void nagbar_exited(EV_P_ ev_child *watcher, int revents)
Definition: util.c:382
uint32_t x
Definition: data.h:123
void * scalloc(size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
#define y(x,...)
Definition: commands.c:19
int min(int a, int b)
Definition: util.c:29
void restore_geometry(void)
Restores the geometry of each window by reparenting it to the root window at the position of its fram...
Definition: manage.c:55
struct Con * croot
Definition: tree.c:14
bool path_exists(const char *path)
Checks if the given path exists by calling stat().
Definition: util.c:198
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
uint32_t x
Definition: data.h:30
uint32_t width
Definition: data.h:125