i3
src/util.c
Go to the documentation of this file.
00001 /*
00002  * vim:ts=4:sw=4:expandtab
00003  *
00004  * i3 - an improved dynamic tiling window manager
00005  * © 2009-2011 Michael Stapelberg and contributors (see also: LICENSE)
00006  *
00007  * util.c: Utility functions, which can be useful everywhere within i3 (see
00008  *         also libi3).
00009  *
00010  */
00011 #include "all.h"
00012 
00013 #include <sys/wait.h>
00014 #include <stdarg.h>
00015 #if defined(__OpenBSD__)
00016 #include <sys/cdefs.h>
00017 #endif
00018 #include <fcntl.h>
00019 #include <pwd.h>
00020 #include <yajl/yajl_version.h>
00021 #include <libgen.h>
00022 
00023 #define SN_API_NOT_YET_FROZEN 1
00024 #include <libsn/sn-launcher.h>
00025 
00026 int min(int a, int b) {
00027     return (a < b ? a : b);
00028 }
00029 
00030 int max(int a, int b) {
00031     return (a > b ? a : b);
00032 }
00033 
00034 bool rect_contains(Rect rect, uint32_t x, uint32_t y) {
00035     return (x >= rect.x &&
00036             x <= (rect.x + rect.width) &&
00037             y >= rect.y &&
00038             y <= (rect.y + rect.height));
00039 }
00040 
00041 Rect rect_add(Rect a, Rect b) {
00042     return (Rect){a.x + b.x,
00043                   a.y + b.y,
00044                   a.width + b.width,
00045                   a.height + b.height};
00046 }
00047 
00048 /*
00049  * Updates *destination with new_value and returns true if it was changed or false
00050  * if it was the same
00051  *
00052  */
00053 bool update_if_necessary(uint32_t *destination, const uint32_t new_value) {
00054     uint32_t old_value = *destination;
00055 
00056     return ((*destination = new_value) != old_value);
00057 }
00058 
00059 /*
00060  * exec()s an i3 utility, for example the config file migration script or
00061  * i3-nagbar. This function first searches $PATH for the given utility named,
00062  * then falls back to the dirname() of the i3 executable path and then falls
00063  * back to the dirname() of the target of /proc/self/exe (on linux).
00064  *
00065  * This function should be called after fork()ing.
00066  *
00067  * The first argument of the given argv vector will be overwritten with the
00068  * executable name, so pass NULL.
00069  *
00070  * If the utility cannot be found in any of these locations, it exits with
00071  * return code 2.
00072  *
00073  */
00074 void exec_i3_utility(char *name, char *argv[]) {
00075     /* start the migration script, search PATH first */
00076     char *migratepath = name;
00077     argv[0] = migratepath;
00078     execvp(migratepath, argv);
00079 
00080     /* if the script is not in path, maybe the user installed to a strange
00081      * location and runs the i3 binary with an absolute path. We use
00082      * argv[0]’s dirname */
00083     char *pathbuf = strdup(start_argv[0]);
00084     char *dir = dirname(pathbuf);
00085     sasprintf(&migratepath, "%s/%s", dir, name);
00086     argv[0] = migratepath;
00087     execvp(migratepath, argv);
00088 
00089 #if defined(__linux__)
00090     /* on linux, we have one more fall-back: dirname(/proc/self/exe) */
00091     char buffer[BUFSIZ];
00092     if (readlink("/proc/self/exe", buffer, BUFSIZ) == -1) {
00093         warn("could not read /proc/self/exe");
00094         exit(1);
00095     }
00096     dir = dirname(buffer);
00097     sasprintf(&migratepath, "%s/%s", dir, name);
00098     argv[0] = migratepath;
00099     execvp(migratepath, argv);
00100 #endif
00101 
00102     warn("Could not start %s", name);
00103     exit(2);
00104 }
00105 
00106 /*
00107  * Checks a generic cookie for errors and quits with the given message if there
00108  * was an error.
00109  *
00110  */
00111 void check_error(xcb_connection_t *conn, xcb_void_cookie_t cookie, char *err_message) {
00112     xcb_generic_error_t *error = xcb_request_check(conn, cookie);
00113     if (error != NULL) {
00114         fprintf(stderr, "ERROR: %s (X error %d)\n", err_message , error->error_code);
00115         xcb_disconnect(conn);
00116         exit(-1);
00117     }
00118 }
00119 
00120 /*
00121  * This function resolves ~ in pathnames.
00122  * It may resolve wildcards in the first part of the path, but if no match
00123  * or multiple matches are found, it just returns a copy of path as given.
00124  *
00125  */
00126 char *resolve_tilde(const char *path) {
00127         static glob_t globbuf;
00128         char *head, *tail, *result;
00129 
00130         tail = strchr(path, '/');
00131         head = strndup(path, tail ? tail - path : strlen(path));
00132 
00133         int res = glob(head, GLOB_TILDE, NULL, &globbuf);
00134         free(head);
00135         /* no match, or many wildcard matches are bad */
00136         if (res == GLOB_NOMATCH || globbuf.gl_pathc != 1)
00137                 result = sstrdup(path);
00138         else if (res != 0) {
00139                 die("glob() failed");
00140         } else {
00141                 head = globbuf.gl_pathv[0];
00142                 result = scalloc(strlen(head) + (tail ? strlen(tail) : 0) + 1);
00143                 strncpy(result, head, strlen(head));
00144                 if (tail)
00145                     strncat(result, tail, strlen(tail));
00146         }
00147         globfree(&globbuf);
00148 
00149         return result;
00150 }
00151 
00152 /*
00153  * Checks if the given path exists by calling stat().
00154  *
00155  */
00156 bool path_exists(const char *path) {
00157         struct stat buf;
00158         return (stat(path, &buf) == 0);
00159 }
00160 
00161 /*
00162  * Goes through the list of arguments (for exec()) and checks if the given argument
00163  * is present. If not, it copies the arguments (because we cannot realloc it) and
00164  * appends the given argument.
00165  *
00166  */
00167 static char **append_argument(char **original, char *argument) {
00168     int num_args;
00169     for (num_args = 0; original[num_args] != NULL; num_args++) {
00170         DLOG("original argument: \"%s\"\n", original[num_args]);
00171         /* If the argument is already present we return the original pointer */
00172         if (strcmp(original[num_args], argument) == 0)
00173             return original;
00174     }
00175     /* Copy the original array */
00176     char **result = smalloc((num_args+2) * sizeof(char*));
00177     memcpy(result, original, num_args * sizeof(char*));
00178     result[num_args] = argument;
00179     result[num_args+1] = NULL;
00180 
00181     return result;
00182 }
00183 
00184 /*
00185  * Returns the name of a temporary file with the specified prefix.
00186  *
00187  */
00188 char *get_process_filename(const char *prefix) {
00189     /* dir stores the directory path for this and all subsequent calls so that
00190      * we only create a temporary directory once per i3 instance. */
00191     static char *dir = NULL;
00192     if (dir == NULL) {
00193         /* Check if XDG_RUNTIME_DIR is set. If so, we use XDG_RUNTIME_DIR/i3 */
00194         if ((dir = getenv("XDG_RUNTIME_DIR"))) {
00195             char *tmp;
00196             sasprintf(&tmp, "%s/i3", dir);
00197             dir = tmp;
00198             if (!path_exists(dir)) {
00199                 if (mkdir(dir, 0700) == -1) {
00200                     perror("mkdir()");
00201                     return NULL;
00202                 }
00203             }
00204         } else {
00205             /* If not, we create a (secure) temp directory using the template
00206              * /tmp/i3-<user>.XXXXXX */
00207             struct passwd *pw = getpwuid(getuid());
00208             const char *username = pw ? pw->pw_name : "unknown";
00209             sasprintf(&dir, "/tmp/i3-%s.XXXXXX", username);
00210             /* mkdtemp modifies dir */
00211             if (mkdtemp(dir) == NULL) {
00212                 perror("mkdtemp()");
00213                 return NULL;
00214             }
00215         }
00216     }
00217     char *filename;
00218     sasprintf(&filename, "%s/%s.%d", dir, prefix, getpid());
00219     return filename;
00220 }
00221 
00222 #define y(x, ...) yajl_gen_ ## x (gen, ##__VA_ARGS__)
00223 #define ystr(str) yajl_gen_string(gen, (unsigned char*)str, strlen(str))
00224 
00225 char *store_restart_layout(void) {
00226     setlocale(LC_NUMERIC, "C");
00227 #if YAJL_MAJOR >= 2
00228     yajl_gen gen = yajl_gen_alloc(NULL);
00229 #else
00230     yajl_gen gen = yajl_gen_alloc(NULL, NULL);
00231 #endif
00232 
00233     dump_node(gen, croot, true);
00234 
00235     setlocale(LC_NUMERIC, "");
00236 
00237     const unsigned char *payload;
00238 #if YAJL_MAJOR >= 2
00239     size_t length;
00240 #else
00241     unsigned int length;
00242 #endif
00243     y(get_buf, &payload, &length);
00244 
00245     /* create a temporary file if one hasn't been specified, or just
00246      * resolve the tildes in the specified path */
00247     char *filename;
00248     if (config.restart_state_path == NULL) {
00249         filename = get_process_filename("restart-state");
00250         if (!filename)
00251             return NULL;
00252     } else {
00253         filename = resolve_tilde(config.restart_state_path);
00254     }
00255 
00256     int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
00257     if (fd == -1) {
00258         perror("open()");
00259         free(filename);
00260         return NULL;
00261     }
00262 
00263     int written = 0;
00264     while (written < length) {
00265         int n = write(fd, payload + written, length - written);
00266         /* TODO: correct error-handling */
00267         if (n == -1) {
00268             perror("write()");
00269             free(filename);
00270             close(fd);
00271             return NULL;
00272         }
00273         if (n == 0) {
00274             printf("write == 0?\n");
00275             free(filename);
00276             close(fd);
00277             return NULL;
00278         }
00279         written += n;
00280 #if YAJL_MAJOR >= 2
00281         printf("written: %d of %zd\n", written, length);
00282 #else
00283         printf("written: %d of %d\n", written, length);
00284 #endif
00285     }
00286     close(fd);
00287 
00288     if (length > 0) {
00289         printf("layout: %.*s\n", (int)length, payload);
00290     }
00291 
00292     y(free);
00293 
00294     return filename;
00295 }
00296 
00297 /*
00298  * Restart i3 in-place
00299  * appends -a to argument list to disable autostart
00300  *
00301  */
00302 void i3_restart(bool forget_layout) {
00303     char *restart_filename = forget_layout ? NULL : store_restart_layout();
00304 
00305     kill_configerror_nagbar(true);
00306 
00307     restore_geometry();
00308 
00309     ipc_shutdown();
00310 
00311     LOG("restarting \"%s\"...\n", start_argv[0]);
00312     /* make sure -a is in the argument list or append it */
00313     start_argv = append_argument(start_argv, "-a");
00314 
00315     /* replace -r <file> so that the layout is restored */
00316     if (restart_filename != NULL) {
00317         /* create the new argv */
00318         int num_args;
00319         for (num_args = 0; start_argv[num_args] != NULL; num_args++);
00320         char **new_argv = scalloc((num_args + 3) * sizeof(char*));
00321 
00322         /* copy the arguments, but skip the ones we'll replace */
00323         int write_index = 0;
00324         bool skip_next = false;
00325         for (int i = 0; i < num_args; ++i) {
00326             if (skip_next)
00327                 skip_next = false;
00328             else if (!strcmp(start_argv[i], "-r") ||
00329                      !strcmp(start_argv[i], "--restart"))
00330                 skip_next = true;
00331             else
00332                 new_argv[write_index++] = start_argv[i];
00333         }
00334 
00335         /* add the arguments we'll replace */
00336         new_argv[write_index++] = "--restart";
00337         new_argv[write_index] = restart_filename;
00338 
00339         /* swap the argvs */
00340         start_argv = new_argv;
00341     }
00342 
00343     execvp(start_argv[0], start_argv);
00344     /* not reached */
00345 }
00346 
00347 #if defined(__OpenBSD__) || defined(__APPLE__)
00348 
00349 /*
00350  * Taken from FreeBSD
00351  * Find the first occurrence of the byte string s in byte string l.
00352  *
00353  */
00354 void *memmem(const void *l, size_t l_len, const void *s, size_t s_len) {
00355     register char *cur, *last;
00356     const char *cl = (const char *)l;
00357     const char *cs = (const char *)s;
00358 
00359     /* we need something to compare */
00360     if (l_len == 0 || s_len == 0)
00361         return NULL;
00362 
00363     /* "s" must be smaller or equal to "l" */
00364     if (l_len < s_len)
00365         return NULL;
00366 
00367     /* special case where s_len == 1 */
00368     if (s_len == 1)
00369         return memchr(l, (int)*cs, l_len);
00370 
00371     /* the last position where its possible to find "s" in "l" */
00372     last = (char *)cl + l_len - s_len;
00373 
00374     for (cur = (char *)cl; cur <= last; cur++)
00375         if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0)
00376             return cur;
00377 
00378     return NULL;
00379 }
00380 
00381 #endif