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 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 = sstrdup(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  * Checks if the given path exists by calling stat().
164  *
165  */
166 bool path_exists(const char *path) {
167  struct stat buf;
168  return (stat(path, &buf) == 0);
169 }
170 
171 /*
172  * Goes through the list of arguments (for exec()) and add/replace the given option,
173  * including the option name, its argument, and the option character.
174  */
175 static char **add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name) {
176  int num_args;
177  for (num_args = 0; original[num_args] != NULL; num_args++)
178  ;
179  char **result = scalloc(num_args + 3, sizeof(char *));
180 
181  /* copy the arguments, but skip the ones we'll replace */
182  int write_index = 0;
183  bool skip_next = false;
184  for (int i = 0; i < num_args; ++i) {
185  if (skip_next) {
186  skip_next = false;
187  continue;
188  }
189  if (!strcmp(original[i], opt_char) ||
190  (opt_name && !strcmp(original[i], opt_name))) {
191  if (opt_arg)
192  skip_next = true;
193  continue;
194  }
195  result[write_index++] = original[i];
196  }
197 
198  /* add the arguments we'll replace */
199  result[write_index++] = opt_char;
200  result[write_index] = opt_arg;
201 
202  return result;
203 }
204 
205 #define y(x, ...) yajl_gen_##x(gen, ##__VA_ARGS__)
206 #define ystr(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str))
207 
208 char *store_restart_layout(void) {
209  setlocale(LC_NUMERIC, "C");
210  yajl_gen gen = yajl_gen_alloc(NULL);
211 
212  dump_node(gen, croot, true);
213 
214  setlocale(LC_NUMERIC, "");
215 
216  const unsigned char *payload;
217  size_t length;
218  y(get_buf, &payload, &length);
219 
220  /* create a temporary file if one hasn't been specified, or just
221  * resolve the tildes in the specified path */
222  char *filename;
223  if (config.restart_state_path == NULL) {
224  filename = get_process_filename("restart-state");
225  if (!filename)
226  return NULL;
227  } else {
229  }
230 
231  /* create the directory, it could have been cleaned up before restarting or
232  * may not exist at all in case it was user-specified. */
233  char *filenamecopy = sstrdup(filename);
234  char *base = dirname(filenamecopy);
235  DLOG("Creating \"%s\" for storing the restart layout\n", base);
236  if (mkdirp(base, DEFAULT_DIR_MODE) != 0)
237  ELOG("Could not create \"%s\" for storing the restart layout, layout will be lost.\n", base);
238  free(filenamecopy);
239 
240  int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
241  if (fd == -1) {
242  perror("open()");
243  free(filename);
244  return NULL;
245  }
246 
247  if (writeall(fd, payload, length) == -1) {
248  ELOG("Could not write restart layout to \"%s\", layout will be lost: %s\n", filename, strerror(errno));
249  free(filename);
250  close(fd);
251  return NULL;
252  }
253 
254  close(fd);
255 
256  if (length > 0) {
257  DLOG("layout: %.*s\n", (int)length, payload);
258  }
259 
260  y(free);
261 
262  return filename;
263 }
264 
265 /*
266  * Restart i3 in-place
267  * appends -a to argument list to disable autostart
268  *
269  */
270 void i3_restart(bool forget_layout) {
271  char *restart_filename = forget_layout ? NULL : store_restart_layout();
272 
275 
277 
278  ipc_shutdown();
279 
280  LOG("restarting \"%s\"...\n", start_argv[0]);
281  /* make sure -a is in the argument list or add it */
282  start_argv = add_argument(start_argv, "-a", NULL, NULL);
283 
284  /* make debuglog-on persist */
285  if (get_debug_logging()) {
286  start_argv = add_argument(start_argv, "-d", "all", NULL);
287  }
288 
289  /* replace -r <file> so that the layout is restored */
290  if (restart_filename != NULL) {
291  start_argv = add_argument(start_argv, "--restart", restart_filename, "-r");
292  }
293 
294  execvp(start_argv[0], start_argv);
295 
296  /* not reached */
297 }
298 
299 #if defined(__OpenBSD__) || defined(__APPLE__)
300 
301 /*
302  * Taken from FreeBSD
303  * Find the first occurrence of the byte string s in byte string l.
304  *
305  */
306 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
307  register char *cur, *last;
308  const char *cl = (const char *)l;
309  const char *cs = (const char *)s;
310 
311  /* we need something to compare */
312  if (l_len == 0 || s_len == 0)
313  return NULL;
314 
315  /* "s" must be smaller or equal to "l" */
316  if (l_len < s_len)
317  return NULL;
318 
319  /* special case where s_len == 1 */
320  if (s_len == 1)
321  return memchr(l, (int)*cs, l_len);
322 
323  /* the last position where its possible to find "s" in "l" */
324  last = (char *)cl + l_len - s_len;
325 
326  for (cur = (char *)cl; cur <= last; cur++)
327  if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
328  return cur;
329 
330  return NULL;
331 }
332 
333 #endif
334 
335 /*
336  * Escapes the given string if a pango font is currently used.
337  * If the string has to be escaped, the input string will be free'd.
338  *
339  */
340 char *pango_escape_markup(char *input) {
341  if (!font_is_pango())
342  return input;
343 
344  char *escaped = g_markup_escape_text(input, -1);
345  FREE(input);
346 
347  return escaped;
348 }
349 
350 /*
351  * Handler which will be called when we get a SIGCHLD for the nagbar, meaning
352  * it exited (or could not be started, depending on the exit code).
353  *
354  */
355 static void nagbar_exited(EV_P_ ev_child *watcher, int revents) {
356  ev_child_stop(EV_A_ watcher);
357 
358  if (!WIFEXITED(watcher->rstatus)) {
359  ELOG("ERROR: i3-nagbar did not exit normally.\n");
360  return;
361  }
362 
363  int exitcode = WEXITSTATUS(watcher->rstatus);
364  DLOG("i3-nagbar process exited with status %d\n", exitcode);
365  if (exitcode == 2) {
366  ELOG("ERROR: i3-nagbar could not be found. Is it correctly installed on your system?\n");
367  }
368 
369  *((pid_t *)watcher->data) = -1;
370 }
371 
372 /*
373  * Cleanup handler. Will be called when i3 exits. Kills i3-nagbar with signal
374  * SIGKILL (9) to make sure there are no left-over i3-nagbar processes.
375  *
376  */
377 static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent) {
378  pid_t *nagbar_pid = (pid_t *)watcher->data;
379  if (*nagbar_pid != -1) {
380  LOG("Sending SIGKILL (%d) to i3-nagbar with PID %d\n", SIGKILL, *nagbar_pid);
381  kill(*nagbar_pid, SIGKILL);
382  }
383 }
384 
385 /*
386  * Starts an i3-nagbar instance with the given parameters. Takes care of
387  * handling SIGCHLD and killing i3-nagbar when i3 exits.
388  *
389  * The resulting PID will be stored in *nagbar_pid and can be used with
390  * kill_nagbar() to kill the bar later on.
391  *
392  */
393 void start_nagbar(pid_t *nagbar_pid, char *argv[]) {
394  if (*nagbar_pid != -1) {
395  DLOG("i3-nagbar already running (PID %d), not starting again.\n", *nagbar_pid);
396  return;
397  }
398 
399  *nagbar_pid = fork();
400  if (*nagbar_pid == -1) {
401  warn("Could not fork()");
402  return;
403  }
404 
405  /* child */
406  if (*nagbar_pid == 0)
407  exec_i3_utility("i3-nagbar", argv);
408 
409  DLOG("Starting i3-nagbar with PID %d\n", *nagbar_pid);
410 
411  /* parent */
412  /* install a child watcher */
413  ev_child *child = smalloc(sizeof(ev_child));
414  ev_child_init(child, &nagbar_exited, *nagbar_pid, 0);
415  child->data = nagbar_pid;
416  ev_child_start(main_loop, child);
417 
418  /* install a cleanup watcher (will be called when i3 exits and i3-nagbar is
419  * still running) */
420  ev_cleanup *cleanup = smalloc(sizeof(ev_cleanup));
421  ev_cleanup_init(cleanup, nagbar_cleanup);
422  cleanup->data = nagbar_pid;
423  ev_cleanup_start(main_loop, cleanup);
424 }
425 
426 /*
427  * Kills the i3-nagbar process, if *nagbar_pid != -1.
428  *
429  * If wait_for_it is set (restarting i3), this function will waitpid(),
430  * otherwise, ev is assumed to handle it (reloading).
431  *
432  */
433 void kill_nagbar(pid_t *nagbar_pid, bool wait_for_it) {
434  if (*nagbar_pid == -1)
435  return;
436 
437  if (kill(*nagbar_pid, SIGTERM) == -1)
438  warn("kill(configerror_nagbar) failed");
439 
440  if (!wait_for_it)
441  return;
442 
443  /* When restarting, we don’t enter the ev main loop anymore and after the
444  * exec(), our old pid is no longer watched. So, ev won’t handle SIGCHLD
445  * for us and we would end up with a <defunct> process. Therefore we
446  * waitpid() here. */
447  waitpid(*nagbar_pid, NULL, 0);
448 }
uint32_t height
Definition: data.h:145
uint32_t x
Definition: data.h:142
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
void * smalloc(size_t size)
Safe-wrapper around malloc which exits if malloc returns NULL (meaning that there is no more memory a...
void i3_restart(bool forget_layout)
Restart i3 in-place appends -a to argument list to disable autostart.
Definition: util.c:270
bool get_debug_logging(void)
Checks if debug logging is active.
Definition: log.c:197
#define y(x,...)
Definition: commands.c:23
void * scalloc(size_t num, size_t size)
Safe-wrapper around calloc which exits if malloc returns NULL (meaning that there is no more memory a...
Rect rect_add(Rect a, Rect b)
Definition: util.c:44
xcb_connection_t * conn
XCB connection and root screen.
Definition: main.c:43
Config config
Definition: config.c:17
char * store_restart_layout(void)
Definition: util.c:208
static char ** add_argument(char **original, char *opt_char, char *opt_arg, char *opt_name)
Definition: util.c:175
uint32_t y
Definition: data.h:143
char * pango_escape_markup(char *input)
Escapes the given string if a pango font is currently used.
Definition: util.c:340
pid_t config_error_nagbar_pid
Definition: config_parser.c:46
void start_nagbar(pid_t *nagbar_pid, char *argv[])
Starts an i3-nagbar instance with the given parameters.
Definition: util.c:393
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:433
struct Con * croot
Definition: tree.c:14
#define ELOG(fmt,...)
Definition: libi3.h:93
uint32_t width
Definition: data.h:144
#define LOG(fmt,...)
Definition: libi3.h:88
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
void dump_node(yajl_gen gen, struct Con *con, bool inplace_restart)
Definition: ipc.c:217
ssize_t writeall(int fd, const void *buf, size_t count)
Wrapper around correct write which returns -1 (meaning that write failed) or count (meaning that all ...
static void nagbar_exited(EV_P_ ev_child *watcher, int revents)
Definition: util.c:355
bool rect_contains(Rect rect, uint32_t x, uint32_t y)
Definition: util.c:37
uint32_t x
Definition: data.h:120
Stores a rectangle, for example the size of a window, the child window etc.
Definition: data.h:141
void ipc_shutdown(void)
Calls shutdown() on each socket and closes it.
Definition: ipc.c:68
int min(int a, int b)
Definition: util.c:29
struct ev_loop * main_loop
Definition: main.c:65
bool path_exists(const char *path)
Checks if the given path exists by calling stat().
Definition: util.c:166
pid_t command_error_nagbar_pid
Definition: bindings.c:17
#define FREE(pointer)
Definition: util.h:48
#define DLOG(fmt,...)
Definition: libi3.h:98
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...
char * resolve_tilde(const char *path)
This function resolves ~ in pathnames.
char * sstrdup(const char *str)
Safe-wrapper around strdup which exits if malloc returns NULL (meaning that there is no more memory a...
#define DEFAULT_DIR_MODE
Definition: libi3.h:27
int mkdirp(const char *path, mode_t mode)
Emulates mkdir -p (creates any missing folders)
int max(int a, int b)
Definition: util.c:33
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
char * get_process_filename(const char *prefix)
Returns the name of a temporary file with the specified prefix.
static void nagbar_cleanup(EV_P_ ev_cleanup *watcher, int revent)
Definition: util.c:377
struct reservedpx __attribute__
long ws_name_to_number(const char *name)
Parses the workspace name as a number.
Definition: util.c:76
char ** start_argv
Definition: main.c:41
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
bool font_is_pango(void)
Returns true if and only if the current font is a pango font.
char * restart_state_path
Definition: config.h:97