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