chiark / gitweb /
remove unused includes
[elogind.git] / src / shared / path-util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010-2012 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <string.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <fcntl.h>
28 #include <sys/statvfs.h>
29
30 #include "macro.h"
31 #include "util.h"
32 #include "log.h"
33 #include "strv.h"
34 #include "path-util.h"
35 #include "missing.h"
36
37 bool path_is_absolute(const char *p) {
38         return p[0] == '/';
39 }
40
41 bool is_path(const char *p) {
42         return !!strchr(p, '/');
43 }
44
45 int path_get_parent(const char *path, char **_r) {
46         const char *e, *a = NULL, *b = NULL, *p;
47         char *r;
48         bool slash = false;
49
50         assert(path);
51         assert(_r);
52
53         if (!*path)
54                 return -EINVAL;
55
56         for (e = path; *e; e++) {
57
58                 if (!slash && *e == '/') {
59                         a = b;
60                         b = e;
61                         slash = true;
62                 } else if (slash && *e != '/')
63                         slash = false;
64         }
65
66         if (*(e-1) == '/')
67                 p = a;
68         else
69                 p = b;
70
71         if (!p)
72                 return -EINVAL;
73
74         if (p == path)
75                 r = strdup("/");
76         else
77                 r = strndup(path, p-path);
78
79         if (!r)
80                 return -ENOMEM;
81
82         *_r = r;
83         return 0;
84 }
85
86 char **path_split_and_make_absolute(const char *p) {
87         char **l;
88         assert(p);
89
90         l = strv_split(p, ":");
91         if (!l)
92                 return NULL;
93
94         if (!path_strv_make_absolute_cwd(l)) {
95                 strv_free(l);
96                 return NULL;
97         }
98
99         return l;
100 }
101
102 char *path_make_absolute(const char *p, const char *prefix) {
103         assert(p);
104
105         /* Makes every item in the list an absolute path by prepending
106          * the prefix, if specified and necessary */
107
108         if (path_is_absolute(p) || !prefix)
109                 return strdup(p);
110
111         return strjoin(prefix, "/", p, NULL);
112 }
113
114 char *path_make_absolute_cwd(const char *p) {
115         _cleanup_free_ char *cwd = NULL;
116
117         assert(p);
118
119         /* Similar to path_make_absolute(), but prefixes with the
120          * current working directory. */
121
122         if (path_is_absolute(p))
123                 return strdup(p);
124
125         cwd = get_current_dir_name();
126         if (!cwd)
127                 return NULL;
128
129         return strjoin(cwd, "/", p, NULL);
130 }
131
132 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
133         char *r, *p;
134         unsigned n_parents;
135
136         assert(from_dir);
137         assert(to_path);
138         assert(_r);
139
140         /* Strips the common part, and adds ".." elements as necessary. */
141
142         if (!path_is_absolute(from_dir))
143                 return -EINVAL;
144
145         if (!path_is_absolute(to_path))
146                 return -EINVAL;
147
148         /* Skip the common part. */
149         for (;;) {
150                 size_t a;
151                 size_t b;
152
153                 from_dir += strspn(from_dir, "/");
154                 to_path += strspn(to_path, "/");
155
156                 if (!*from_dir) {
157                         if (!*to_path)
158                                 /* from_dir equals to_path. */
159                                 r = strdup(".");
160                         else
161                                 /* from_dir is a parent directory of to_path. */
162                                 r = strdup(to_path);
163
164                         if (!r)
165                                 return -ENOMEM;
166
167                         path_kill_slashes(r);
168
169                         *_r = r;
170                         return 0;
171                 }
172
173                 if (!*to_path)
174                         break;
175
176                 a = strcspn(from_dir, "/");
177                 b = strcspn(to_path, "/");
178
179                 if (a != b)
180                         break;
181
182                 if (memcmp(from_dir, to_path, a) != 0)
183                         break;
184
185                 from_dir += a;
186                 to_path += b;
187         }
188
189         /* If we're here, then "from_dir" has one or more elements that need to
190          * be replaced with "..". */
191
192         /* Count the number of necessary ".." elements. */
193         for (n_parents = 0;;) {
194                 from_dir += strspn(from_dir, "/");
195
196                 if (!*from_dir)
197                         break;
198
199                 from_dir += strcspn(from_dir, "/");
200                 n_parents++;
201         }
202
203         r = malloc(n_parents * 3 + strlen(to_path) + 1);
204         if (!r)
205                 return -ENOMEM;
206
207         for (p = r; n_parents > 0; n_parents--, p += 3)
208                 memcpy(p, "../", 3);
209
210         strcpy(p, to_path);
211         path_kill_slashes(r);
212
213         *_r = r;
214         return 0;
215 }
216
217 char **path_strv_make_absolute_cwd(char **l) {
218         char **s;
219
220         /* Goes through every item in the string list and makes it
221          * absolute. This works in place and won't rollback any
222          * changes on failure. */
223
224         STRV_FOREACH(s, l) {
225                 char *t;
226
227                 t = path_make_absolute_cwd(*s);
228                 if (!t)
229                         return NULL;
230
231                 free(*s);
232                 *s = t;
233         }
234
235         return l;
236 }
237
238 char **path_strv_resolve(char **l, const char *prefix) {
239         char **s;
240         unsigned k = 0;
241         bool enomem = false;
242
243         if (strv_isempty(l))
244                 return l;
245
246         /* Goes through every item in the string list and canonicalize
247          * the path. This works in place and won't rollback any
248          * changes on failure. */
249
250         STRV_FOREACH(s, l) {
251                 char *t, *u;
252                 _cleanup_free_ char *orig = NULL;
253
254                 if (!path_is_absolute(*s)) {
255                         free(*s);
256                         continue;
257                 }
258
259                 if (prefix) {
260                         orig = *s;
261                         t = strappend(prefix, orig);
262                         if (!t) {
263                                 enomem = true;
264                                 continue;
265                         }
266                 } else
267                         t = *s;
268
269                 errno = 0;
270                 u = canonicalize_file_name(t);
271                 if (!u) {
272                         if (errno == ENOENT) {
273                                 if (prefix) {
274                                         u = orig;
275                                         orig = NULL;
276                                         free(t);
277                                 } else
278                                         u = t;
279                         } else {
280                                 free(t);
281                                 if (errno == ENOMEM || errno == 0)
282                                         enomem = true;
283
284                                 continue;
285                         }
286                 } else if (prefix) {
287                         char *x;
288
289                         free(t);
290                         x = path_startswith(u, prefix);
291                         if (x) {
292                                 /* restore the slash if it was lost */
293                                 if (!startswith(x, "/"))
294                                         *(--x) = '/';
295
296                                 t = strdup(x);
297                                 free(u);
298                                 if (!t) {
299                                         enomem = true;
300                                         continue;
301                                 }
302                                 u = t;
303                         } else {
304                                 /* canonicalized path goes outside of
305                                  * prefix, keep the original path instead */
306                                 free(u);
307                                 u = orig;
308                                 orig = NULL;
309                         }
310                 } else
311                         free(t);
312
313                 l[k++] = u;
314         }
315
316         l[k] = NULL;
317
318         if (enomem)
319                 return NULL;
320
321         return l;
322 }
323
324 char **path_strv_resolve_uniq(char **l, const char *prefix) {
325
326         if (strv_isempty(l))
327                 return l;
328
329         if (!path_strv_resolve(l, prefix))
330                 return NULL;
331
332         return strv_uniq(l);
333 }
334
335 char *path_kill_slashes(char *path) {
336         char *f, *t;
337         bool slash = false;
338
339         /* Removes redundant inner and trailing slashes. Modifies the
340          * passed string in-place.
341          *
342          * ///foo///bar/ becomes /foo/bar
343          */
344
345         for (f = path, t = path; *f; f++) {
346
347                 if (*f == '/') {
348                         slash = true;
349                         continue;
350                 }
351
352                 if (slash) {
353                         slash = false;
354                         *(t++) = '/';
355                 }
356
357                 *(t++) = *f;
358         }
359
360         /* Special rule, if we are talking of the root directory, a
361         trailing slash is good */
362
363         if (t == path && slash)
364                 *(t++) = '/';
365
366         *t = 0;
367         return path;
368 }
369
370 char* path_startswith(const char *path, const char *prefix) {
371         assert(path);
372         assert(prefix);
373
374         if ((path[0] == '/') != (prefix[0] == '/'))
375                 return NULL;
376
377         for (;;) {
378                 size_t a, b;
379
380                 path += strspn(path, "/");
381                 prefix += strspn(prefix, "/");
382
383                 if (*prefix == 0)
384                         return (char*) path;
385
386                 if (*path == 0)
387                         return NULL;
388
389                 a = strcspn(path, "/");
390                 b = strcspn(prefix, "/");
391
392                 if (a != b)
393                         return NULL;
394
395                 if (memcmp(path, prefix, a) != 0)
396                         return NULL;
397
398                 path += a;
399                 prefix += b;
400         }
401 }
402
403 bool path_equal(const char *a, const char *b) {
404         assert(a);
405         assert(b);
406
407         if ((a[0] == '/') != (b[0] == '/'))
408                 return false;
409
410         for (;;) {
411                 size_t j, k;
412
413                 a += strspn(a, "/");
414                 b += strspn(b, "/");
415
416                 if (*a == 0 && *b == 0)
417                         return true;
418
419                 if (*a == 0 || *b == 0)
420                         return false;
421
422                 j = strcspn(a, "/");
423                 k = strcspn(b, "/");
424
425                 if (j != k)
426                         return false;
427
428                 if (memcmp(a, b, j) != 0)
429                         return false;
430
431                 a += j;
432                 b += k;
433         }
434 }
435
436 bool path_equal_or_files_same(const char *a, const char *b) {
437         return path_equal(a, b) || files_same(a, b) > 0;
438 }
439
440 char* path_join(const char *root, const char *path, const char *rest) {
441         assert(path);
442
443         if (!isempty(root))
444                 return strjoin(root, endswith(root, "/") ? "" : "/",
445                                path[0] == '/' ? path+1 : path,
446                                rest ? (endswith(path, "/") ? "" : "/") : NULL,
447                                rest && rest[0] == '/' ? rest+1 : rest,
448                                NULL);
449         else
450                 return strjoin(path,
451                                rest ? (endswith(path, "/") ? "" : "/") : NULL,
452                                rest && rest[0] == '/' ? rest+1 : rest,
453                                NULL);
454 }
455
456 int path_is_mount_point(const char *t, bool allow_symlink) {
457
458         union file_handle_union h = FILE_HANDLE_INIT;
459         int mount_id = -1, mount_id_parent = -1;
460         _cleanup_free_ char *parent = NULL;
461         struct stat a, b;
462         int r;
463         bool nosupp = false;
464
465         /* We are not actually interested in the file handles, but
466          * name_to_handle_at() also passes us the mount ID, hence use
467          * it but throw the handle away */
468
469         if (path_equal(t, "/"))
470                 return 1;
471
472         r = name_to_handle_at(AT_FDCWD, t, &h.handle, &mount_id, allow_symlink ? AT_SYMLINK_FOLLOW : 0);
473         if (r < 0) {
474                 if (errno == ENOSYS)
475                         /* This kernel does not support name_to_handle_at()
476                          * fall back to the traditional stat() logic. */
477                         goto fallback;
478                 else if (errno == EOPNOTSUPP)
479                         /* This kernel or file system does not support
480                          * name_to_handle_at(), hence fallback to the
481                          * traditional stat() logic */
482                         nosupp = true;
483                 else if (errno == ENOENT)
484                         return 0;
485                 else
486                         return -errno;
487         }
488
489         r = path_get_parent(t, &parent);
490         if (r < 0)
491                 return r;
492
493         h.handle.handle_bytes = MAX_HANDLE_SZ;
494         r = name_to_handle_at(AT_FDCWD, parent, &h.handle, &mount_id_parent, AT_SYMLINK_FOLLOW);
495         if (r < 0)
496                 if (errno == EOPNOTSUPP)
497                         if (nosupp)
498                                 /* Neither parent nor child do name_to_handle_at()?
499                                    We have no choice but to fall back. */
500                                 goto fallback;
501                         else
502                                 /* The parent can't do name_to_handle_at() but
503                                  * the directory we are interested in can?
504                                  * Or the other way around?
505                                  * If so, it must be a mount point. */
506                                 return 1;
507                 else
508                         return -errno;
509         else
510                 return mount_id != mount_id_parent;
511
512 fallback:
513         if (allow_symlink)
514                 r = stat(t, &a);
515         else
516                 r = lstat(t, &a);
517
518         if (r < 0) {
519                 if (errno == ENOENT)
520                         return 0;
521
522                 return -errno;
523         }
524
525         free(parent);
526         parent = NULL;
527
528         r = path_get_parent(t, &parent);
529         if (r < 0)
530                 return r;
531
532         r = stat(parent, &b);
533         if (r < 0)
534                 return -errno;
535
536         return a.st_dev != b.st_dev;
537 }
538
539 int path_is_read_only_fs(const char *path) {
540         struct statvfs st;
541
542         assert(path);
543
544         if (statvfs(path, &st) < 0)
545                 return -errno;
546
547         if (st.f_flag & ST_RDONLY)
548                 return true;
549
550         /* On NFS, statvfs() might not reflect whether we can actually
551          * write to the remote share. Let's try again with
552          * access(W_OK) which is more reliable, at least sometimes. */
553         if (access(path, W_OK) < 0 && errno == EROFS)
554                 return true;
555
556         return false;
557 }
558
559 int path_is_os_tree(const char *path) {
560         char *p;
561         int r;
562
563         /* We use /usr/lib/os-release as flag file if something is an OS */
564         p = strjoina(path, "/usr/lib/os-release");
565         r = access(p, F_OK);
566
567         if (r >= 0)
568                 return 1;
569
570         /* Also check for the old location in /etc, just in case. */
571         p = strjoina(path, "/etc/os-release");
572         r = access(p, F_OK);
573
574         return r >= 0;
575 }
576
577 int find_binary(const char *name, bool local, char **filename) {
578         assert(name);
579
580         if (is_path(name)) {
581                 if (local && access(name, X_OK) < 0)
582                         return -errno;
583
584                 if (filename) {
585                         char *p;
586
587                         p = path_make_absolute_cwd(name);
588                         if (!p)
589                                 return -ENOMEM;
590
591                         *filename = p;
592                 }
593
594                 return 0;
595         } else {
596                 const char *path;
597                 const char *word, *state;
598                 size_t l;
599
600                 /**
601                  * Plain getenv, not secure_getenv, because we want
602                  * to actually allow the user to pick the binary.
603                  */
604                 path = getenv("PATH");
605                 if (!path)
606                         path = DEFAULT_PATH;
607
608                 FOREACH_WORD_SEPARATOR(word, l, path, ":", state) {
609                         _cleanup_free_ char *p = NULL;
610
611                         if (asprintf(&p, "%.*s/%s", (int) l, word, name) < 0)
612                                 return -ENOMEM;
613
614                         if (access(p, X_OK) < 0)
615                                 continue;
616
617                         if (filename) {
618                                 *filename = path_kill_slashes(p);
619                                 p = NULL;
620                         }
621
622                         return 0;
623                 }
624
625                 return -ENOENT;
626         }
627 }
628
629 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
630         bool changed = false;
631         const char* const* i;
632
633         assert(timestamp);
634
635         if (paths == NULL)
636                 return false;
637
638         STRV_FOREACH(i, paths) {
639                 struct stat stats;
640                 usec_t u;
641
642                 if (stat(*i, &stats) < 0)
643                         continue;
644
645                 u = timespec_load(&stats.st_mtim);
646
647                 /* first check */
648                 if (*timestamp >= u)
649                         continue;
650
651                 log_debug("timestamp of '%s' changed", *i);
652
653                 /* update timestamp */
654                 if (update) {
655                         *timestamp = u;
656                         changed = true;
657                 } else
658                         return true;
659         }
660
661         return changed;
662 }
663
664 int fsck_exists(const char *fstype) {
665         _cleanup_free_ char *p = NULL, *d = NULL;
666         const char *checker;
667         int r;
668
669         checker = strjoina("fsck.", fstype);
670
671         r = find_binary(checker, true, &p);
672         if (r < 0)
673                 return r;
674
675         /* An fsck that is linked to /bin/true is a non-existent
676          * fsck */
677
678         r = readlink_malloc(p, &d);
679         if (r >= 0 &&
680             (path_equal(d, "/bin/true") ||
681              path_equal(d, "/usr/bin/true") ||
682              path_equal(d, "/dev/null")))
683                 return -ENOENT;
684
685         return 0;
686 }