futil.c revision 222035
1/*
2 * FreeBSD install - a package for the installation and maintainance
3 * of non-core utilities.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * Jordan K. Hubbard
15 * 18 July 1993
16 *
17 * Miscellaneous file access utilities.
18 *
19 */
20
21#include <sys/cdefs.h>
22__FBSDID("$FreeBSD: head/usr.sbin/pkg_install/add/futil.c 222035 2011-05-17 19:11:47Z flz $");
23
24#include <err.h>
25#include "lib.h"
26#include "add.h"
27
28/*
29 * Assuming dir is a desired directory name, make it and all intervening
30 * directories necessary.
31 */
32
33int
34make_hierarchy(char *dir)
35{
36    char *cp1, *cp2;
37
38    if (dir[0] == '/')
39	cp1 = cp2 = dir + 1;
40    else
41	cp1 = cp2 = dir;
42    while (cp2) {
43	if ((cp2 = strchr(cp1, '/')) !=NULL )
44	    *cp2 = '\0';
45	if (fexists(dir)) {
46	    if (!isdir(dir)) {
47		if (cp2)
48		    *cp2 = '/';
49		return FAIL;
50	    }
51	}
52	else {
53	    if (mkdir(dir, 0777) < 0) {
54		if (cp2)
55		    *cp2 = '/';
56		return FAIL;
57	    }
58	    apply_perms(NULL, dir);
59	}
60	/* Put it back */
61	if (cp2) {
62	    *cp2 = '/';
63	    cp1 = cp2 + 1;
64	}
65    }
66    return SUCCESS;
67}
68
69/* Using permission defaults, apply them as necessary */
70void
71apply_perms(const char *dir, const char *arg)
72{
73    const char *cd_to;
74
75    if (!dir || *arg == '/')	/* absolute path? */
76	cd_to = "/";
77    else
78	cd_to = dir;
79
80    if (Mode)
81	if (vsystem("cd %s && /bin/chmod -R %s %s", cd_to, Mode, arg))
82	    warnx("couldn't change modes of '%s' to '%s'", arg, Mode);
83    if (Owner && Group) {
84	if (vsystem("cd %s && /usr/sbin/chown -R %s:%s %s", cd_to, Owner, Group, arg))
85	    warnx("couldn't change owner/group of '%s' to '%s:%s'",
86		   arg, Owner, Group);
87	return;
88    }
89    if (Owner) {
90	if (vsystem("cd %s && /usr/sbin/chown -R %s %s", cd_to, Owner, arg))
91	    warnx("couldn't change owner of '%s' to '%s'", arg, Owner);
92	return;
93    } else if (Group)
94	if (vsystem("cd %s && /usr/bin/chgrp -R %s %s", cd_to, Group, arg))
95	    warnx("couldn't change group of '%s' to '%s'", arg, Group);
96}
97
98