]> git.sur5r.net Git - i3/i3/blob - libi3/get_process_filename.c
Merge branch 'master' into next
[i3/i3] / libi3 / get_process_filename.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2012 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <assert.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <stdbool.h>
13 #include <err.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <pwd.h>
17 #include <unistd.h>
18
19 #include "libi3.h"
20
21 /*
22  * Returns the name of a temporary file with the specified prefix.
23  *
24  */
25 char *get_process_filename(const char *prefix) {
26     /* dir stores the directory path for this and all subsequent calls so that
27      * we only create a temporary directory once per i3 instance. */
28     static char *dir = NULL;
29     if (dir == NULL) {
30         /* Check if XDG_RUNTIME_DIR is set. If so, we use XDG_RUNTIME_DIR/i3 */
31         if ((dir = getenv("XDG_RUNTIME_DIR"))) {
32             char *tmp;
33             sasprintf(&tmp, "%s/i3", dir);
34             dir = tmp;
35             struct stat buf;
36             if (stat(dir, &buf) != 0) {
37                 if (mkdir(dir, 0700) == -1) {
38                     perror("mkdir()");
39                     return NULL;
40                 }
41             }
42         } else {
43             /* If not, we create a (secure) temp directory using the template
44              * /tmp/i3-<user>.XXXXXX */
45             struct passwd *pw = getpwuid(getuid());
46             const char *username = pw ? pw->pw_name : "unknown";
47             sasprintf(&dir, "/tmp/i3-%s.XXXXXX", username);
48             /* mkdtemp modifies dir */
49             if (mkdtemp(dir) == NULL) {
50                 perror("mkdtemp()");
51                 return NULL;
52             }
53         }
54     }
55     char *filename;
56     sasprintf(&filename, "%s/%s.%d", dir, prefix, getpid());
57     return filename;
58 }