]> git.ipfire.org Git - thirdparty/util-linux.git/blob - libmount/src/utils.c
lib/strutils: move *swith() functions to private library
[thirdparty/util-linux.git] / libmount / src / utils.c
1 /*
2 * Copyright (C) 2008-2009 Karel Zak <kzak@redhat.com>
3 *
4 * This file may be redistributed under the terms of the
5 * GNU Lesser General Public License.
6 */
7
8 /**
9 * SECTION: utils
10 * @title: Utils
11 * @short_description: misc utils.
12 */
13 #include <ctype.h>
14 #include <fcntl.h>
15 #include <pwd.h>
16 #include <grp.h>
17
18 #include "strutils.h"
19 #include "pathnames.h"
20 #include "mountP.h"
21 #include "mangle.h"
22 #include "canonicalize.h"
23 #include "env.h"
24 #include "match.h"
25
26 int append_string(char **a, const char *b)
27 {
28 size_t al, bl;
29 char *tmp;
30
31 assert(a);
32
33 if (!b || !*b)
34 return 0;
35 if (!*a) {
36 *a = strdup(b);
37 return !*a ? -ENOMEM : 0;
38 }
39
40 al = strlen(*a);
41 bl = b ? strlen(b) : 0;
42
43 tmp = realloc(*a, al + bl + 1);
44 if (!tmp)
45 return -ENOMEM;
46 *a = tmp;
47 memcpy((*a) + al, b, bl + 1);
48 return 0;
49 }
50
51 /*
52 * Return 1 if the file is not accessible or empty
53 */
54 int is_file_empty(const char *name)
55 {
56 struct stat st;
57 assert(name);
58
59 return (stat(name, &st) != 0 || st.st_size == 0);
60 }
61
62 int mnt_valid_tagname(const char *tagname)
63 {
64 if (tagname && *tagname && (
65 strcmp("UUID", tagname) == 0 ||
66 strcmp("LABEL", tagname) == 0 ||
67 strcmp("PARTUUID", tagname) == 0 ||
68 strcmp("PARTLABEL", tagname) == 0))
69 return 1;
70
71 return 0;
72 }
73
74 int mnt_parse_offset(const char *str, size_t len, uintmax_t *res)
75 {
76 char *p;
77 int rc = 0;
78
79 if (!str || !*str)
80 return -EINVAL;
81
82 p = strndup(str, len);
83 if (!p)
84 return -errno;
85
86 if (strtosize(p, res))
87 rc = -EINVAL;
88 free(p);
89 return rc;
90 }
91
92 /* used as a callback by bsearch in mnt_fstype_is_pseudofs() */
93 static int fstype_cmp(const void *v1, const void *v2)
94 {
95 const char *s1 = *(const char **)v1;
96 const char *s2 = *(const char **)v2;
97
98 return strcmp(s1, s2);
99 }
100
101 /* returns basename and keeps dirname in the @path, if @path is "/" (root)
102 * then returns empty string */
103 char *stripoff_last_component(char *path)
104 {
105 char *p = path ? strrchr(path, '/') : NULL;
106
107 if (!p)
108 return NULL;
109 *p = '\0';
110 return p + 1;
111 }
112
113 /*
114 * Note that the @target has to be an absolute path (so at least "/"). The
115 * @filename returns an allocated buffer with the last path component, for example:
116 *
117 * mnt_chdir_to_parent("/mnt/test", &buf) ==> chdir("/mnt"), buf="test"
118 */
119 int mnt_chdir_to_parent(const char *target, char **filename)
120 {
121 char *buf, *parent, *last = NULL;
122 char cwd[PATH_MAX];
123 int rc = -EINVAL;
124
125 if (!target || *target != '/')
126 return -EINVAL;
127
128 DBG(UTILS, mnt_debug("moving to %s parent", target));
129
130 buf = strdup(target);
131 if (!buf)
132 return -ENOMEM;
133
134 if (*(buf + 1) != '\0') {
135 last = stripoff_last_component(buf);
136 if (!last)
137 goto err;
138 }
139
140 parent = buf && *buf ? buf : "/";
141
142 if (chdir(parent) == -1) {
143 DBG(UTILS, mnt_debug("failed to chdir to %s: %m", parent));
144 rc = -errno;
145 goto err;
146 }
147 if (!getcwd(cwd, sizeof(cwd))) {
148 DBG(UTILS, mnt_debug("failed to obtain current directory: %m"));
149 rc = -errno;
150 goto err;
151 }
152 if (strcmp(cwd, parent) != 0) {
153 DBG(UTILS, mnt_debug(
154 "unexpected chdir (expected=%s, cwd=%s)", parent, cwd));
155 goto err;
156 }
157
158 DBG(CXT, mnt_debug(
159 "current directory moved to %s [last_component='%s']",
160 parent, last));
161
162 if (filename) {
163 *filename = buf;
164
165 if (!last || !*last)
166 memcpy(*filename, ".", 2);
167 else
168 memcpy(*filename, last, strlen(last) + 1);
169 } else
170 free(buf);
171 return 0;
172 err:
173 free(buf);
174 return rc;
175 }
176
177 /*
178 * Check if @path is on a read-only filesystem independently of file permissions.
179 */
180 int mnt_is_readonly(const char *path)
181 {
182 if (access(path, W_OK) == 0)
183 return 0;
184 if (errno == EROFS)
185 return 1;
186 if (errno != EACCES)
187 return 0;
188
189 #ifdef HAVE_FUTIMENS
190 /*
191 * access(2) returns EACCES on read-only FS:
192 *
193 * - for set-uid application if one component of the path is not
194 * accessible for the current rUID. (Note that euidaccess(2) does not
195 * check for EROFS at all).
196 *
197 * - for a read-write filesystem with a read-only VFS node (aka -o remount,ro,bind)
198 */
199 {
200 struct timespec times[2];
201
202 times[0].tv_nsec = UTIME_NOW; /* atime */
203 times[1].tv_nsec = UTIME_OMIT; /* mtime */
204
205 if (utimensat(AT_FDCWD, path, times, 0) == -1)
206 return errno == EROFS;
207 }
208 #endif
209 return 0;
210 }
211
212 /**
213 * mnt_mangle:
214 * @str: string
215 *
216 * Encode @str to be compatible with fstab/mtab
217 *
218 * Returns: newly allocated string or NULL in case of error.
219 */
220 char *mnt_mangle(const char *str)
221 {
222 return mangle(str);
223 }
224
225 /**
226 * mnt_unmangle:
227 * @str: string
228 *
229 * Decode @str from fstab/mtab
230 *
231 * Returns: newly allocated string or NULL in case of error.
232 */
233 char *mnt_unmangle(const char *str)
234 {
235 return unmangle(str, NULL);
236 }
237
238 /**
239 * mnt_fstype_is_pseudofs:
240 * @type: filesystem name
241 *
242 * Returns: 1 for filesystems like proc, sysfs, ... or 0.
243 */
244 int mnt_fstype_is_pseudofs(const char *type)
245 {
246 /* This array must remain sorted when adding new fstypes */
247 static const char *pseudofs[] = {
248 "anon_inodefs",
249 "autofs",
250 "bdev",
251 "binfmt_misc",
252 "cgroup",
253 "configfs",
254 "cpuset",
255 "debugfs",
256 "devfs",
257 "devpts",
258 "devtmpfs",
259 "dlmfs",
260 "fuse.gvfs-fuse-daemon",
261 "fusectl",
262 "hugetlbfs",
263 "mqueue",
264 "nfsd",
265 "none",
266 "pipefs",
267 "proc",
268 "pstore",
269 "ramfs",
270 "rootfs",
271 "rpc_pipefs",
272 "securityfs",
273 "sockfs",
274 "spufs",
275 "sysfs",
276 "tmpfs"
277 };
278
279 assert(type);
280
281 return !(bsearch(&type, pseudofs, ARRAY_SIZE(pseudofs),
282 sizeof(char*), fstype_cmp) == NULL);
283 }
284
285 /**
286 * mnt_fstype_is_netfs:
287 * @type: filesystem name
288 *
289 * Returns: 1 for filesystems like cifs, nfs, ... or 0.
290 */
291 int mnt_fstype_is_netfs(const char *type)
292 {
293 assert(type);
294
295 if (strcmp(type, "cifs") == 0 ||
296 strcmp(type, "smbfs") == 0 ||
297 strncmp(type,"nfs", 3) == 0 ||
298 strcmp(type, "afs") == 0 ||
299 strcmp(type, "ncpfs") == 0 ||
300 strncmp(type,"9p", 2) == 0)
301 return 1;
302 return 0;
303 }
304
305 /**
306 * mnt_match_fstype:
307 * @type: filesystem type
308 * @pattern: filesystem name or comma delimited list of names
309 *
310 * The @pattern list of filesystems can be prefixed with a global
311 * "no" prefix to invert matching of the whole list. The "no" could
312 * also be used for individual items in the @pattern list. So,
313 * "nofoo,bar" has the same meaning as "nofoo,nobar".
314 *
315 * "bar" : "nofoo,bar" -> False (global "no" prefix)
316 *
317 * "bar" : "foo,bar" -> True
318 *
319 * "bar" : "foo,nobar" -> False
320 *
321 * Returns: 1 if type is matching, else 0. This function also returns
322 * 0 if @pattern is NULL and @type is non-NULL.
323 */
324 int mnt_match_fstype(const char *type, const char *pattern)
325 {
326 return match_fstype(type, pattern);
327 }
328
329
330 /* Returns 1 if needle found or noneedle not found in haystack
331 * Otherwise returns 0
332 */
333 static int check_option(const char *haystack, size_t len,
334 const char *needle, size_t needle_len)
335 {
336 const char *p;
337 int no = 0;
338
339 if (needle_len >= 1 && *needle == '+') {
340 needle++;
341 needle_len--;
342 } else if (needle_len >= 2 && !strncmp(needle, "no", 2)) {
343 no = 1;
344 needle += 2;
345 needle_len -= 2;
346 }
347
348 for (p = haystack; p && p < haystack + len; p++) {
349 char *sep = strchr(p, ',');
350 size_t plen = sep ? (size_t) (sep - p) :
351 len - (p - haystack);
352
353 if (plen == needle_len) {
354 if (!strncmp(p, needle, plen))
355 return !no; /* foo or nofoo was found */
356 }
357 p += plen;
358 }
359
360 return no; /* foo or nofoo was not found */
361 }
362
363 /**
364 * mnt_match_options:
365 * @optstr: options string
366 * @pattern: comma delimited list of options
367 *
368 * The "no" could be used for individual items in the @options list. The "no"
369 * prefix does not have a global meaning.
370 *
371 * Unlike fs type matching, nonetdev,user and nonetdev,nouser have
372 * DIFFERENT meanings; each option is matched explicitly as specified.
373 *
374 * The "no" prefix interpretation could be disabled by the "+" prefix, for example
375 * "+noauto" matches if @optstr literally contains the "noauto" string.
376 *
377 * "xxx,yyy,zzz" : "nozzz" -> False
378 *
379 * "xxx,yyy,zzz" : "xxx,noeee" -> True
380 *
381 * "bar,zzz" : "nofoo" -> True
382 *
383 * "nofoo,bar" : "+nofoo" -> True
384 *
385 * "bar,zzz" : "+nofoo" -> False
386 *
387 *
388 * Returns: 1 if pattern is matching, else 0. This function also returns 0
389 * if @pattern is NULL and @optstr is non-NULL.
390 */
391 int mnt_match_options(const char *optstr, const char *pattern)
392 {
393 const char *p;
394 size_t len, optstr_len = 0;
395
396 if (!pattern && !optstr)
397 return 1;
398 if (!pattern)
399 return 0;
400
401 len = strlen(pattern);
402 if (optstr)
403 optstr_len = strlen(optstr);
404
405 for (p = pattern; p < pattern + len; p++) {
406 char *sep = strchr(p, ',');
407 size_t plen = sep ? (size_t) (sep - p) :
408 len - (p - pattern);
409
410 if (!plen)
411 continue; /* if two ',' appear in a row */
412
413 if (!check_option(optstr, optstr_len, p, plen))
414 return 0; /* any match failure means failure */
415
416 p += plen;
417 }
418
419 /* no match failures in list means success */
420 return 1;
421 }
422
423 void mnt_free_filesystems(char **filesystems)
424 {
425 char **p;
426
427 if (!filesystems)
428 return;
429 for (p = filesystems; *p; p++)
430 free(*p);
431 free(filesystems);
432 }
433
434 static int add_filesystem(char ***filesystems, char *name)
435 {
436 int n = 0;
437
438 assert(filesystems);
439 assert(name);
440
441 if (*filesystems) {
442 char **p;
443 for (n = 0, p = *filesystems; *p; p++, n++) {
444 if (strcmp(*p, name) == 0)
445 return 0;
446 }
447 }
448
449 #define MYCHUNK 16
450
451 if (n == 0 || !((n + 1) % MYCHUNK)) {
452 size_t items = ((n + 1 + MYCHUNK) / MYCHUNK) * MYCHUNK;
453 char **x = realloc(*filesystems, items * sizeof(char *));
454
455 if (!x)
456 goto err;
457 *filesystems = x;
458 }
459 name = strdup(name);
460 if (!name)
461 goto err;
462 (*filesystems)[n] = name;
463 (*filesystems)[n + 1] = NULL;
464 return 0;
465 err:
466 mnt_free_filesystems(*filesystems);
467 return -ENOMEM;
468 }
469
470 static int get_filesystems(const char *filename, char ***filesystems, const char *pattern)
471 {
472 int rc = 0;
473 FILE *f;
474 char line[128];
475
476 f = fopen(filename, "r" UL_CLOEXECSTR);
477 if (!f)
478 return 1;
479
480 DBG(UTILS, mnt_debug("reading filesystems list from: %s", filename));
481
482 while (fgets(line, sizeof(line), f)) {
483 char name[sizeof(line)];
484
485 if (*line == '#' || strncmp(line, "nodev", 5) == 0)
486 continue;
487 if (sscanf(line, " %128[^\n ]\n", name) != 1)
488 continue;
489 if (strcmp(name, "*") == 0) {
490 rc = 1;
491 break; /* end of the /etc/filesystems */
492 }
493 if (pattern && !mnt_match_fstype(name, pattern))
494 continue;
495 rc = add_filesystem(filesystems, name);
496 if (rc)
497 break;
498 }
499
500 fclose(f);
501 return rc;
502 }
503
504 /*
505 * Always check the @filesystems pointer!
506 *
507 * man mount:
508 *
509 * ...mount will try to read the file /etc/filesystems, or, if that does not
510 * exist, /proc/filesystems. All of the filesystem types listed there will
511 * be tried, except for those that are labeled "nodev" (e.g., devpts,
512 * proc and nfs). If /etc/filesystems ends in a line with a single * only,
513 * mount will read /proc/filesystems afterwards.
514 */
515 int mnt_get_filesystems(char ***filesystems, const char *pattern)
516 {
517 int rc;
518
519 if (!filesystems)
520 return -EINVAL;
521
522 *filesystems = NULL;
523
524 rc = get_filesystems(_PATH_FILESYSTEMS, filesystems, pattern);
525 if (rc != 1)
526 return rc;
527
528 rc = get_filesystems(_PATH_PROC_FILESYSTEMS, filesystems, pattern);
529 if (rc == 1 && *filesystems)
530 rc = 0; /* /proc/filesystems not found */
531
532 return rc;
533 }
534
535 static size_t get_pw_record_size(void)
536 {
537 #ifdef _SC_GETPW_R_SIZE_MAX
538 long sz = sysconf(_SC_GETPW_R_SIZE_MAX);
539 if (sz > 0)
540 return sz;
541 #endif
542 return 16384;
543 }
544
545 /*
546 * Returns an allocated string with username or NULL.
547 */
548 char *mnt_get_username(const uid_t uid)
549 {
550 struct passwd pwd;
551 struct passwd *res;
552 size_t sz = get_pw_record_size();
553 char *buf, *username = NULL;
554
555 buf = malloc(sz);
556 if (!buf)
557 return NULL;
558
559 if (!getpwuid_r(uid, &pwd, buf, sz, &res) && res)
560 username = strdup(pwd.pw_name);
561
562 free(buf);
563 return username;
564 }
565
566 int mnt_get_uid(const char *username, uid_t *uid)
567 {
568 int rc = -1;
569 struct passwd pwd;
570 struct passwd *pw;
571 size_t sz = get_pw_record_size();
572 char *buf;
573
574 if (!username || !uid)
575 return -EINVAL;
576
577 buf = malloc(sz);
578 if (!buf)
579 return -ENOMEM;
580
581 if (!getpwnam_r(username, &pwd, buf, sz, &pw) && pw) {
582 *uid= pw->pw_uid;
583 rc = 0;
584 } else {
585 DBG(UTILS, mnt_debug(
586 "cannot convert '%s' username to UID", username));
587 rc = errno ? -errno : -EINVAL;
588 }
589
590 free(buf);
591 return rc;
592 }
593
594 int mnt_get_gid(const char *groupname, gid_t *gid)
595 {
596 int rc = -1;
597 struct group grp;
598 struct group *gr;
599 size_t sz = get_pw_record_size();
600 char *buf;
601
602 if (!groupname || !gid)
603 return -EINVAL;
604
605 buf = malloc(sz);
606 if (!buf)
607 return -ENOMEM;
608
609 if (!getgrnam_r(groupname, &grp, buf, sz, &gr) && gr) {
610 *gid= gr->gr_gid;
611 rc = 0;
612 } else {
613 DBG(UTILS, mnt_debug(
614 "cannot convert '%s' groupname to GID", groupname));
615 rc = errno ? -errno : -EINVAL;
616 }
617
618 free(buf);
619 return rc;
620 }
621
622 int mnt_in_group(gid_t gid)
623 {
624 int rc = 0, n, i;
625 gid_t *grps = NULL;
626
627 if (getgid() == gid)
628 return 1;
629
630 n = getgroups(0, NULL);
631 if (n <= 0)
632 goto done;
633
634 grps = malloc(n * sizeof(*grps));
635 if (!grps)
636 goto done;
637
638 if (getgroups(n, grps) == n) {
639 for (i = 0; i < n; i++) {
640 if (grps[i] == gid) {
641 rc = 1;
642 break;
643 }
644 }
645 }
646 done:
647 free(grps);
648 return rc;
649 }
650
651 static int try_write(const char *filename)
652 {
653 int fd;
654
655 if (!filename)
656 return -EINVAL;
657
658 fd = open(filename, O_RDWR|O_CREAT|O_CLOEXEC,
659 S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH);
660 if (fd >= 0) {
661 close(fd);
662 return 0;
663 }
664 return -errno;
665 }
666
667 /**
668 * mnt_has_regular_mtab:
669 * @mtab: returns path to mtab
670 * @writable: returns 1 if the file is writable
671 *
672 * If the file does not exist and @writable argument is not NULL, then it will
673 * try to create the file.
674 *
675 * Returns: 1 if /etc/mtab is a regular file, and 0 in case of error (check
676 * errno for more details).
677 */
678 int mnt_has_regular_mtab(const char **mtab, int *writable)
679 {
680 struct stat st;
681 int rc;
682 const char *filename = mtab && *mtab ? *mtab : mnt_get_mtab_path();
683
684 if (writable)
685 *writable = 0;
686 if (mtab && !*mtab)
687 *mtab = filename;
688
689 DBG(UTILS, mnt_debug("mtab: %s", filename));
690
691 rc = lstat(filename, &st);
692
693 if (rc == 0) {
694 /* file exists */
695 if (S_ISREG(st.st_mode)) {
696 if (writable)
697 *writable = !try_write(filename);
698 return 1;
699 }
700 goto done;
701 }
702
703 /* try to create the file */
704 if (writable) {
705 *writable = !try_write(filename);
706 if (*writable)
707 return 1;
708 }
709
710 done:
711 DBG(UTILS, mnt_debug("%s: irregular/non-writable", filename));
712 return 0;
713 }
714
715 /*
716 * Don't export this to libmount API -- utab is private library stuff.
717 *
718 * If the file does not exist and @writable argument is not NULL, then it will
719 * try to create the directory (e.g. /run/mount) and the file.
720 *
721 * Returns: 1 if utab is a regular file, and 0 in case of
722 * error (check errno for more details).
723 */
724 int mnt_has_regular_utab(const char **utab, int *writable)
725 {
726 struct stat st;
727 int rc;
728 const char *filename = utab && *utab ? *utab : mnt_get_utab_path();
729
730 if (writable)
731 *writable = 0;
732 if (utab && !*utab)
733 *utab = filename;
734
735 DBG(UTILS, mnt_debug("utab: %s", filename));
736
737 rc = lstat(filename, &st);
738
739 if (rc == 0) {
740 /* file exists */
741 if (S_ISREG(st.st_mode)) {
742 if (writable)
743 *writable = !try_write(filename);
744 return 1;
745 }
746 goto done; /* it's not a regular file */
747 }
748
749 if (writable) {
750 char *dirname = strdup(filename);
751
752 if (!dirname)
753 goto done;
754
755 stripoff_last_component(dirname); /* remove filename */
756
757 rc = mkdir(dirname, S_IWUSR|
758 S_IRUSR|S_IRGRP|S_IROTH|
759 S_IXUSR|S_IXGRP|S_IXOTH);
760 free(dirname);
761 if (rc && errno != EEXIST)
762 goto done; /* probably EACCES */
763
764 *writable = !try_write(filename);
765 if (*writable)
766 return 1;
767 }
768 done:
769 DBG(UTILS, mnt_debug("%s: irregular/non-writable file", filename));
770 return 0;
771 }
772
773 /**
774 * mnt_get_swaps_path:
775 *
776 * Returns: path to /proc/swaps or $LIBMOUNT_SWAPS.
777 */
778 const char *mnt_get_swaps_path(void)
779 {
780 const char *p = safe_getenv("LIBMOUNT_SWAPS");
781 return p ? : _PATH_PROC_SWAPS;
782 }
783
784 /**
785 * mnt_get_fstab_path:
786 *
787 * Returns: path to /etc/fstab or $LIBMOUNT_FSTAB.
788 */
789 const char *mnt_get_fstab_path(void)
790 {
791 const char *p = safe_getenv("LIBMOUNT_FSTAB");
792 return p ? : _PATH_MNTTAB;
793 }
794
795 /**
796 * mnt_get_mtab_path:
797 *
798 * This function returns the *default* location of the mtab file. The result does
799 * not have to be writable. See also mnt_has_regular_mtab().
800 *
801 * Returns: path to /etc/mtab or $LIBMOUNT_MTAB.
802 */
803 const char *mnt_get_mtab_path(void)
804 {
805 const char *p = safe_getenv("LIBMOUNT_MTAB");
806 return p ? : _PATH_MOUNTED;
807 }
808
809 /*
810 * Don't export this to libmount API -- utab is private library stuff.
811 *
812 * Returns: path to /run/mount/utab (or /dev/.mount/utab) or $LIBMOUNT_UTAB.
813 */
814 const char *mnt_get_utab_path(void)
815 {
816 struct stat st;
817 const char *p = safe_getenv("LIBMOUNT_UTAB");
818
819 if (p)
820 return p;
821
822 if (stat(MNT_RUNTIME_TOPDIR, &st) == 0)
823 return MNT_PATH_UTAB;
824
825 return MNT_PATH_UTAB_OLD;
826 }
827
828
829 /* returns file descriptor or -errno, @name returns a unique filename
830 */
831 int mnt_open_uniq_filename(const char *filename, char **name)
832 {
833 int rc, fd;
834 char *n;
835 mode_t oldmode;
836
837 if (!filename)
838 return -EINVAL;
839 if (name)
840 *name = NULL;
841
842 rc = asprintf(&n, "%s.XXXXXX", filename);
843 if (rc <= 0)
844 return -errno;
845
846 /* This is for very old glibc and for compatibility with Posix, which says
847 * nothing about mkstemp() mode. All sane glibc use secure mode (0600).
848 */
849 oldmode = umask(S_IRGRP|S_IWGRP|S_IXGRP|
850 S_IROTH|S_IWOTH|S_IXOTH);
851 fd = mkostemp(n, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC);
852 umask(oldmode);
853
854 if (fd >= 0 && name)
855 *name = n;
856 else
857 free(n);
858
859 return fd < 0 ? -errno : fd;
860 }
861
862 /**
863 * mnt_get_mountpoint:
864 * @path: pathname
865 *
866 * This function finds the mountpoint that a given path resides in. @path
867 * should be canonicalized. The returned pointer should be freed by the caller.
868 *
869 * Returns: allocated string with the target of the mounted device or NULL on error
870 */
871 char *mnt_get_mountpoint(const char *path)
872 {
873 char *mnt;
874 struct stat st;
875 dev_t dir, base;
876
877 assert(path);
878
879 mnt = strdup(path);
880 if (!mnt)
881 return NULL;
882 if (*mnt == '/' && *(mnt + 1) == '\0')
883 goto done;
884
885 if (stat(mnt, &st))
886 goto err;
887 base = st.st_dev;
888
889 do {
890 char *p = stripoff_last_component(mnt);
891
892 if (!p)
893 break;
894 if (stat(*mnt ? mnt : "/", &st))
895 goto err;
896 dir = st.st_dev;
897 if (dir != base) {
898 if (p > mnt)
899 *(p - 1) = '/';
900 goto done;
901 }
902 base = dir;
903 } while (mnt && *(mnt + 1) != '\0');
904
905 memcpy(mnt, "/", 2);
906 done:
907 DBG(UTILS, mnt_debug("%s mountpoint is %s", path, mnt));
908 return mnt;
909 err:
910 free(mnt);
911 return NULL;
912 }
913
914 char *mnt_get_fs_root(const char *path, const char *mnt)
915 {
916 char *m = (char *) mnt, *res;
917 const char *p;
918 size_t sz;
919
920 if (!m)
921 m = mnt_get_mountpoint(path);
922 if (!m)
923 return NULL;
924
925 sz = strlen(m);
926 p = sz > 1 ? path + sz : path;
927
928 if (m != mnt)
929 free(m);
930
931 res = *p ? strdup(p) : strdup("/");
932 DBG(UTILS, mnt_debug("%s fs-root is %s", path, res));
933 return res;
934 }
935
936 /*
937 * Search for @name kernel command parametr.
938 *
939 * Returns newly allocated string with a parameter argument if the @name is
940 * specified as "name=" or returns pointer to @name or returns NULL if not
941 * found.
942 *
943 * For example cmdline: "aaa bbb=BBB ccc"
944 *
945 * @name is "aaa" --returns--> "aaa" (pointer to @name)
946 * @name is "bbb=" --returns--> "BBB" (allocated)
947 * @name is "foo" --returns--> NULL
948 */
949 char *mnt_get_kernel_cmdline_option(const char *name)
950 {
951 FILE *f;
952 size_t len;
953 int val = 0;
954 char *p, *res = NULL;
955 char buf[BUFSIZ]; /* see kernel include/asm-generic/setup.h: COMMAND_LINE_SIZE */
956 const char *path = _PATH_PROC_CMDLINE;
957
958 if (!name)
959 return NULL;
960
961 #ifdef TEST_PROGRAM
962 path = getenv("LIBMOUNT_KERNEL_CMDLINE");
963 if (!path)
964 path = _PATH_PROC_CMDLINE;
965 #endif
966 f = fopen(path, "r" UL_CLOEXECSTR);
967 if (!f)
968 return NULL;
969
970 p = fgets(buf, sizeof(buf), f);
971 fclose(f);
972
973 if (!p || !*p || *p == '\n')
974 return NULL;
975
976 len = strlen(buf);
977 *(buf + len - 1) = '\0'; /* remove last '\n' */
978
979 len = strlen(name);
980 if (len && *(name + len - 1) == '=')
981 val = 1;
982
983 for ( ; p && *p; p++) {
984 if (!(p = strstr(p, name)))
985 break; /* not found the option */
986 if (p != buf && !isblank(*(p - 1)))
987 continue; /* no space before the option */
988 if (!val && *(p + len) != '\0' && !isblank(*(p + len)))
989 continue; /* no space after the option */
990 if (val) {
991 char *v = p + len;
992
993 while (*p && !isblank(*p)) /* jump to the end of the argument */
994 p++;
995 *p = '\0';
996 res = strdup(v);
997 break;
998 } else
999 res = (char *) name; /* option without '=' */
1000 break;
1001 }
1002
1003 return res;
1004 }
1005
1006 int mkdir_p(const char *path, mode_t mode)
1007 {
1008 char *p, *dir;
1009 int rc = 0;
1010
1011 if (!path || !*path)
1012 return -EINVAL;
1013
1014 dir = p = strdup(path);
1015 if (!dir)
1016 return -ENOMEM;
1017
1018 if (*p == '/')
1019 p++;
1020
1021 while (p && *p) {
1022 char *e = strchr(p, '/');
1023 if (e)
1024 *e = '\0';
1025 if (*p) {
1026 rc = mkdir(dir, mode);
1027 if (rc && errno != EEXIST)
1028 break;
1029 rc = 0;
1030 }
1031 if (!e)
1032 break;
1033 *e = '/';
1034 p = e + 1;
1035 }
1036
1037 DBG(UTILS, mnt_debug("%s mkdir %s", path, rc ? "FAILED" : "SUCCESS"));
1038
1039 free(dir);
1040 return rc;
1041 }
1042
1043 #ifdef TEST_PROGRAM
1044 int test_match_fstype(struct libmnt_test *ts, int argc, char *argv[])
1045 {
1046 char *type = argv[1];
1047 char *pattern = argv[2];
1048
1049 printf("%s\n", mnt_match_fstype(type, pattern) ? "MATCH" : "NOT-MATCH");
1050 return 0;
1051 }
1052
1053 int test_match_options(struct libmnt_test *ts, int argc, char *argv[])
1054 {
1055 char *optstr = argv[1];
1056 char *pattern = argv[2];
1057
1058 printf("%s\n", mnt_match_options(optstr, pattern) ? "MATCH" : "NOT-MATCH");
1059 return 0;
1060 }
1061
1062 int test_startswith(struct libmnt_test *ts, int argc, char *argv[])
1063 {
1064 char *optstr = argv[1];
1065 char *pattern = argv[2];
1066
1067 printf("%s\n", startswith(optstr, pattern) ? "YES" : "NOT");
1068 return 0;
1069 }
1070
1071 int test_endswith(struct libmnt_test *ts, int argc, char *argv[])
1072 {
1073 char *optstr = argv[1];
1074 char *pattern = argv[2];
1075
1076 printf("%s\n", endswith(optstr, pattern) ? "YES" : "NOT");
1077 return 0;
1078 }
1079
1080 int test_appendstr(struct libmnt_test *ts, int argc, char *argv[])
1081 {
1082 char *str = strdup(argv[1]);
1083 const char *ap = argv[2];
1084
1085 append_string(&str, ap);
1086 printf("new string: '%s'\n", str);
1087
1088 free(str);
1089 return 0;
1090 }
1091
1092 int test_mountpoint(struct libmnt_test *ts, int argc, char *argv[])
1093 {
1094 char *path = canonicalize_path(argv[1]),
1095 *mnt = path ? mnt_get_mountpoint(path) : NULL;
1096
1097 printf("%s: %s\n", argv[1], mnt ? : "unknown");
1098 free(mnt);
1099 free(path);
1100 return 0;
1101 }
1102
1103 int test_fsroot(struct libmnt_test *ts, int argc, char *argv[])
1104 {
1105 char *path = canonicalize_path(argv[1]),
1106 *mnt = path ? mnt_get_fs_root(path, NULL) : NULL;
1107
1108 printf("%s: %s\n", argv[1], mnt ? : "unknown");
1109 free(mnt);
1110 free(path);
1111 return 0;
1112 }
1113
1114 int test_filesystems(struct libmnt_test *ts, int argc, char *argv[])
1115 {
1116 char **filesystems = NULL;
1117 int rc;
1118
1119 rc = mnt_get_filesystems(&filesystems, argc ? argv[1] : NULL);
1120 if (!rc) {
1121 char **p;
1122 for (p = filesystems; *p; p++)
1123 printf("%s\n", *p);
1124 mnt_free_filesystems(filesystems);
1125 }
1126 return rc;
1127 }
1128
1129 int test_chdir(struct libmnt_test *ts, int argc, char *argv[])
1130 {
1131 int rc;
1132 char *path = canonicalize_path(argv[1]),
1133 *last = NULL;
1134
1135 if (!path)
1136 return -errno;
1137
1138 rc = mnt_chdir_to_parent(path, &last);
1139 if (!rc) {
1140 printf("path='%s', abs='%s', last='%s'\n",
1141 argv[1], path, last);
1142 }
1143 free(path);
1144 free(last);
1145 return rc;
1146 }
1147
1148 int test_kernel_cmdline(struct libmnt_test *ts, int argc, char *argv[])
1149 {
1150 char *name = argv[1];
1151 char *res;
1152
1153 res = mnt_get_kernel_cmdline_option(name);
1154 if (!res)
1155 printf("'%s' not found\n", name);
1156 else if (res == name)
1157 printf("'%s' found\n", name);
1158 else {
1159 printf("'%s' found, argument: '%s'\n", name, res);
1160 free(res);
1161 }
1162
1163 return 0;
1164 }
1165
1166 int test_mkdir(struct libmnt_test *ts, int argc, char *argv[])
1167 {
1168 int rc;
1169
1170 rc = mkdir_p(argv[1], S_IRWXU |
1171 S_IRGRP | S_IXGRP |
1172 S_IROTH | S_IXOTH);
1173 if (rc)
1174 printf("mkdir %s failed\n", argv[1]);
1175 return rc;
1176 }
1177
1178
1179 int main(int argc, char *argv[])
1180 {
1181 struct libmnt_test tss[] = {
1182 { "--match-fstype", test_match_fstype, "<type> <pattern> FS types matching" },
1183 { "--match-options", test_match_options, "<options> <pattern> options matching" },
1184 { "--filesystems", test_filesystems, "[<pattern>] list /{etc,proc}/filesystems" },
1185 { "--starts-with", test_startswith, "<string> <prefix>" },
1186 { "--ends-with", test_endswith, "<string> <prefix>" },
1187 { "--append-string", test_appendstr, "<string> <appendix>" },
1188 { "--mountpoint", test_mountpoint, "<path>" },
1189 { "--fs-root", test_fsroot, "<path>" },
1190 { "--cd-parent", test_chdir, "<path>" },
1191 { "--kernel-cmdline",test_kernel_cmdline, "<option> | <option>=" },
1192 { "--mkdir", test_mkdir, "<path>" },
1193
1194 { NULL }
1195 };
1196
1197 return mnt_run_test(tss, argc, argv);
1198 }
1199
1200 #endif /* TEST_PROGRAM */