2 * udev_utils_file.c - files operations
4 * Copyright (C) 2004-2005 Kay Sievers <kay.sievers@vrfy.org>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation version 2 of the License.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 675 Mass Ave, Cambridge, MA 02139, USA.
35 int create_path(const char *path)
42 pos = strrchr(p, '/');
43 if (pos == p || pos == NULL)
46 while (pos[-1] == '/')
51 dbg("stat '%s'\n", p);
52 if (stat (p, &stats) == 0 && (stats.st_mode & S_IFMT) == S_IFDIR)
55 if (create_path (p) != 0)
58 dbg("mkdir '%s'\n", p);
59 return mkdir(p, 0755);
62 int delete_path(const char *path)
69 pos = strrchr(p, '/');
72 pos = strrchr(p, '/');
74 /* don't remove the last one */
75 if ((pos == p) || (pos == NULL))
83 if (errno == ENOTEMPTY)
85 err("rmdir(%s) failed: %s", p, strerror(errno));
88 dbg("removed '%s'", p);
93 /* Reset permissions on the device node, before unlinking it to make sure,
94 * that permisions of possible hard links will be removed too.
96 int unlink_secure(const char *filename)
100 retval = chown(filename, 0, 0);
102 err("chown(%s, 0, 0) failed: %s", filename, strerror(errno));
104 retval = chmod(filename, 0000);
106 err("chmod(%s, 0000) failed: %s", filename, strerror(errno));
108 retval = unlink(filename);
113 err("unlink(%s) failed: %s", filename, strerror(errno));
118 int file_map(const char *filename, char **buf, size_t *bufsize)
123 fd = open(filename, O_RDONLY);
128 if (fstat(fd, &stats) < 0) {
133 *buf = mmap(NULL, stats.st_size, PROT_READ, MAP_SHARED, fd, 0);
134 if (*buf == MAP_FAILED) {
138 *bufsize = stats.st_size;
145 void file_unmap(void *buf, size_t bufsize)
147 munmap(buf, bufsize);
150 /* return number of chars until the next newline, skip escaped newline */
151 size_t buf_get_line(const char *buf, size_t buflen, size_t cur)
156 for (count = cur; count < buflen; count++) {
157 if (!escape && buf[count] == '\n')
160 if (buf[count] == '\\')