1 /*
2  * This file is part of mpv.
3  *
4  * Get path to config dir/file.
5  *
6  * mpv is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * mpv is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with mpv.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include <assert.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdbool.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <errno.h>
29 
30 #include "config.h"
31 
32 #include "common/common.h"
33 #include "common/global.h"
34 #include "common/msg.h"
35 #include "options/options.h"
36 #include "options/path.h"
37 #include "mpv_talloc.h"
38 #include "osdep/io.h"
39 #include "osdep/path.h"
40 #include "misc/ctype.h"
41 
42 // In order of decreasing priority: the first has highest priority.
43 static const mp_get_platform_path_cb path_resolvers[] = {
44 #if HAVE_COCOA
45     mp_get_platform_path_osx,
46 #endif
47 #if !defined(_WIN32) || defined(__CYGWIN__)
48     mp_get_platform_path_unix,
49 #endif
50 #if HAVE_UWP
51     mp_get_platform_path_uwp,
52 #elif defined(_WIN32)
53     mp_get_platform_path_win,
54 #endif
55 };
56 
57 // from highest (most preferred) to lowest priority
58 static const char *const config_dirs[] = {
59     "home",
60     "old_home",
61     "osxbundle",
62     "exe_dir",
63     "global",
64 };
65 
mp_init_paths(struct mpv_global * global,struct MPOpts * opts)66 void mp_init_paths(struct mpv_global *global, struct MPOpts *opts)
67 {
68     TA_FREEP(&global->configdir);
69 
70     const char *force_configdir = getenv("MPV_HOME");
71     if (opts->force_configdir && opts->force_configdir[0])
72         force_configdir = opts->force_configdir;
73     if (!opts->load_config)
74         force_configdir = "";
75 
76     global->configdir = talloc_strdup(global, force_configdir);
77 }
78 
79 // Return a platform specific path using a path type as defined in osdep/path.h.
80 // Keep in mind that the only way to free the return value is freeing talloc_ctx
81 // (or its children), as this function can return a statically allocated string.
mp_get_platform_path(void * talloc_ctx,struct mpv_global * global,const char * type)82 static const char *mp_get_platform_path(void *talloc_ctx,
83                                         struct mpv_global *global,
84                                         const char *type)
85 {
86     assert(talloc_ctx);
87 
88     if (global->configdir) {
89         for (int n = 0; n < MP_ARRAY_SIZE(config_dirs); n++) {
90             if (strcmp(config_dirs[n], type) == 0)
91                 return (n == 0 && global->configdir[0]) ? global->configdir : NULL;
92         }
93     }
94 
95     for (int n = 0; n < MP_ARRAY_SIZE(path_resolvers); n++) {
96         const char *path = path_resolvers[n](talloc_ctx, type);
97         if (path && path[0])
98             return path;
99     }
100     return NULL;
101 }
102 
mp_find_user_config_file(void * talloc_ctx,struct mpv_global * global,const char * filename)103 char *mp_find_user_config_file(void *talloc_ctx, struct mpv_global *global,
104                                const char *filename)
105 {
106     void *tmp = talloc_new(NULL);
107     char *res = (char *)mp_get_platform_path(tmp, global, config_dirs[0]);
108     if (res)
109         res = mp_path_join(talloc_ctx, res, filename);
110     talloc_free(tmp);
111     MP_DBG(global, "config path: '%s' -> '%s'\n", filename, res ? res : "-");
112     return res;
113 }
114 
mp_find_all_config_files_limited(void * talloc_ctx,struct mpv_global * global,int max_files,const char * filename)115 static char **mp_find_all_config_files_limited(void *talloc_ctx,
116                                                struct mpv_global *global,
117                                                int max_files,
118                                                const char *filename)
119 {
120     char **ret = talloc_array(talloc_ctx, char*, 2); // 2 preallocated
121     int num_ret = 0;
122 
123     for (int i = 0; i < MP_ARRAY_SIZE(config_dirs); i++) {
124         const char *dir = mp_get_platform_path(ret, global, config_dirs[i]);
125         bstr s = bstr0(filename);
126         while (dir && num_ret < max_files && s.len) {
127             bstr fn;
128             bstr_split_tok(s, "|", &fn, &s);
129 
130             char *file = mp_path_join_bstr(ret, bstr0(dir), fn);
131             if (mp_path_exists(file)) {
132                 MP_DBG(global, "config path: '%.*s' -> '%s'\n",
133                         BSTR_P(fn), file);
134                 MP_TARRAY_APPEND(NULL, ret, num_ret, file);
135             } else {
136                 MP_DBG(global, "config path: '%.*s' -/-> '%s'\n",
137                         BSTR_P(fn), file);
138             }
139         }
140     }
141 
142     MP_TARRAY_GROW(NULL, ret, num_ret);
143     ret[num_ret] = NULL;
144 
145     for (int n = 0; n < num_ret / 2; n++)
146         MPSWAP(char*, ret[n], ret[num_ret - n - 1]);
147     return ret;
148 }
149 
mp_find_all_config_files(void * talloc_ctx,struct mpv_global * global,const char * filename)150 char **mp_find_all_config_files(void *talloc_ctx, struct mpv_global *global,
151                                 const char *filename)
152 {
153     return mp_find_all_config_files_limited(talloc_ctx, global, 64, filename);
154 }
155 
mp_find_config_file(void * talloc_ctx,struct mpv_global * global,const char * filename)156 char *mp_find_config_file(void *talloc_ctx, struct mpv_global *global,
157                           const char *filename)
158 {
159     char **l = mp_find_all_config_files_limited(talloc_ctx, global, 1, filename);
160     char *r = l && l[0] ? talloc_steal(talloc_ctx, l[0]) : NULL;
161     talloc_free(l);
162     return r;
163 }
164 
mp_get_user_path(void * talloc_ctx,struct mpv_global * global,const char * path)165 char *mp_get_user_path(void *talloc_ctx, struct mpv_global *global,
166                        const char *path)
167 {
168     if (!path)
169         return NULL;
170     char *res = NULL;
171     bstr bpath = bstr0(path);
172     if (bstr_eatstart0(&bpath, "~")) {
173         // parse to "~" <prefix> "/" <rest>
174         bstr prefix, rest;
175         if (bstr_split_tok(bpath, "/", &prefix, &rest)) {
176             const char *rest0 = rest.start; // ok in this case
177             if (bstr_equals0(prefix, "~")) {
178                 res = mp_find_config_file(talloc_ctx, global, rest0);
179                 if (!res) {
180                     void *tmp = talloc_new(NULL);
181                     const char *p = mp_get_platform_path(tmp, global, "home");
182                     res = mp_path_join_bstr(talloc_ctx, bstr0(p), rest);
183                     talloc_free(tmp);
184                 }
185             } else if (bstr_equals0(prefix, "")) {
186                 char *home = getenv("HOME");
187                 if (!home)
188                     home = getenv("USERPROFILE");
189                 res = mp_path_join_bstr(talloc_ctx, bstr0(home), rest);
190             } else if (bstr_eatstart0(&prefix, "~")) {
191                 void *tmp = talloc_new(NULL);
192                 char type[80];
193                 snprintf(type, sizeof(type), "%.*s", BSTR_P(prefix));
194                 const char *p = mp_get_platform_path(tmp, global, type);
195                 res = mp_path_join_bstr(talloc_ctx, bstr0(p), rest);
196                 talloc_free(tmp);
197             }
198         }
199     }
200     if (!res)
201         res = talloc_strdup(talloc_ctx, path);
202     MP_DBG(global, "user path: '%s' -> '%s'\n", path, res);
203     return res;
204 }
205 
mp_basename(const char * path)206 char *mp_basename(const char *path)
207 {
208     char *s;
209 
210 #if HAVE_DOS_PATHS
211     s = strrchr(path, '\\');
212     if (s)
213         path = s + 1;
214     s = strrchr(path, ':');
215     if (s)
216         path = s + 1;
217 #endif
218     s = strrchr(path, '/');
219     return s ? s + 1 : (char *)path;
220 }
221 
mp_dirname(const char * path)222 struct bstr mp_dirname(const char *path)
223 {
224     struct bstr ret = {
225         (uint8_t *)path, mp_basename(path) - path
226     };
227     if (ret.len == 0)
228         return bstr0(".");
229     return ret;
230 }
231 
232 
233 #if HAVE_DOS_PATHS
234 static const char mp_path_separators[] = "\\/";
235 #else
236 static const char mp_path_separators[] = "/";
237 #endif
238 
239 // Mutates path and removes a trailing '/' (or '\' on Windows)
mp_path_strip_trailing_separator(char * path)240 void mp_path_strip_trailing_separator(char *path)
241 {
242     size_t len = strlen(path);
243     if (len > 0 && strchr(mp_path_separators, path[len - 1]))
244         path[len - 1] = '\0';
245 }
246 
mp_splitext(const char * path,bstr * root)247 char *mp_splitext(const char *path, bstr *root)
248 {
249     assert(path);
250     const char *split = strrchr(path, '.');
251     if (!split || !split[1] || strchr(split, '/'))
252         return NULL;
253     if (root)
254         *root = (bstr){(char *)path, split - path};
255     return (char *)split + 1;
256 }
257 
mp_path_is_absolute(struct bstr path)258 bool mp_path_is_absolute(struct bstr path)
259 {
260     if (path.len && strchr(mp_path_separators, path.start[0]))
261         return true;
262 
263 #if HAVE_DOS_PATHS
264     // Note: "X:filename" is a path relative to the current working directory
265     //       of drive X, and thus is not an absolute path. It needs to be
266     //       followed by \ or /.
267     if (path.len >= 3 && path.start[1] == ':' &&
268         strchr(mp_path_separators, path.start[2]))
269         return true;
270 #endif
271 
272     return false;
273 }
274 
mp_path_join_bstr(void * talloc_ctx,struct bstr p1,struct bstr p2)275 char *mp_path_join_bstr(void *talloc_ctx, struct bstr p1, struct bstr p2)
276 {
277     if (p1.len == 0)
278         return bstrdup0(talloc_ctx, p2);
279     if (p2.len == 0)
280         return bstrdup0(talloc_ctx, p1);
281 
282     if (mp_path_is_absolute(p2))
283         return bstrdup0(talloc_ctx, p2);
284 
285     bool have_separator = strchr(mp_path_separators, p1.start[p1.len - 1]);
286 #if HAVE_DOS_PATHS
287     // "X:" only => path relative to "X:" current working directory.
288     if (p1.len == 2 && p1.start[1] == ':')
289         have_separator = true;
290 #endif
291 
292     return talloc_asprintf(talloc_ctx, "%.*s%s%.*s", BSTR_P(p1),
293                            have_separator ? "" : "/", BSTR_P(p2));
294 }
295 
mp_path_join(void * talloc_ctx,const char * p1,const char * p2)296 char *mp_path_join(void *talloc_ctx, const char *p1, const char *p2)
297 {
298     return mp_path_join_bstr(talloc_ctx, bstr0(p1), bstr0(p2));
299 }
300 
mp_getcwd(void * talloc_ctx)301 char *mp_getcwd(void *talloc_ctx)
302 {
303     char *e_wd = getenv("PWD");
304     if (e_wd)
305         return talloc_strdup(talloc_ctx, e_wd);
306 
307     char *wd = talloc_array(talloc_ctx, char, 20);
308     while (getcwd(wd, talloc_get_size(wd)) == NULL) {
309         if (errno != ERANGE) {
310             talloc_free(wd);
311             return NULL;
312         }
313         wd = talloc_realloc(talloc_ctx, wd, char, talloc_get_size(wd) * 2);
314     }
315     return wd;
316 }
317 
mp_path_exists(const char * path)318 bool mp_path_exists(const char *path)
319 {
320     struct stat st;
321     return path && stat(path, &st) == 0;
322 }
323 
mp_path_isdir(const char * path)324 bool mp_path_isdir(const char *path)
325 {
326     struct stat st;
327     return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
328 }
329 
330 // Return false if it's considered a normal local filesystem path.
mp_is_url(bstr path)331 bool mp_is_url(bstr path)
332 {
333     int proto = bstr_find0(path, "://");
334     if (proto < 1)
335         return false;
336     // Per RFC3986, the first character of the protocol must be alphabetic.
337     // The rest must be alphanumeric plus -, + and .
338     for (int i = 0; i < proto; i++) {
339         unsigned char c = path.start[i];
340         if ((i == 0 && !mp_isalpha(c)) ||
341             (!mp_isalnum(c) && c != '.' && c != '-' && c != '+'))
342         {
343             return false;
344         }
345     }
346     return true;
347 }
348 
349 // Return the protocol part of path, e.g. "http" if path is "http://...".
350 // On success, out_url (if not NULL) is set to the part after the "://".
mp_split_proto(bstr path,bstr * out_url)351 bstr mp_split_proto(bstr path, bstr *out_url)
352 {
353     if (!mp_is_url(path))
354         return (bstr){0};
355     bstr r;
356     bstr_split_tok(path, "://", &r, out_url ? out_url : &(bstr){0});
357     return r;
358 }
359 
mp_mkdirp(const char * dir)360 void mp_mkdirp(const char *dir)
361 {
362     char *path = talloc_strdup(NULL, dir);
363     char *cdir = path + 1;
364 
365     while (cdir) {
366         cdir = strchr(cdir, '/');
367         if (cdir)
368             *cdir = 0;
369 
370         mkdir(path, 0700);
371 
372         if (cdir)
373             *cdir++ = '/';
374     }
375 
376     talloc_free(path);
377 }
378 
mp_mk_config_dir(struct mpv_global * global,char * subdir)379 void mp_mk_config_dir(struct mpv_global *global, char *subdir)
380 {
381     char *dir = mp_find_user_config_file(NULL, global, subdir);
382     if (dir)
383         mp_mkdirp(dir);
384     talloc_free(dir);
385 }
386