]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/utils.h
implement lxc_string_split_quoted
[mirror_lxc.git] / src / lxc / utils.h
1 /*
2 * lxc: linux Container library
3 *
4 * (C) Copyright IBM Corp. 2007, 2008
5 *
6 * Authors:
7 * Daniel Lezcano <daniel.lezcano at free.fr>
8 *
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
13 *
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
18 *
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23 #ifndef __LXC_UTILS_H
24 #define __LXC_UTILS_H
25
26 /* Properly support loop devices on 32bit systems. */
27 #define _FILE_OFFSET_BITS 64
28
29 #include "config.h"
30
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <stdbool.h>
35 #include <unistd.h>
36 #include <linux/loop.h>
37 #include <linux/magic.h>
38 #include <sys/syscall.h>
39 #include <sys/types.h>
40 #include <sys/vfs.h>
41
42 #include "initutils.h"
43
44 /* Define __S_ISTYPE if missing from the C library. */
45 #ifndef __S_ISTYPE
46 #define __S_ISTYPE(mode, mask) (((mode)&S_IFMT) == (mask))
47 #endif
48
49 /* Useful macros */
50 /* Maximum number for 64 bit integer is a string with 21 digits: 2^64 - 1 = 21 */
51 #define LXC_NUMSTRLEN64 21
52 #define LXC_LINELEN 4096
53 #define LXC_IDMAPLEN 4096
54
55 /* returns 1 on success, 0 if there were any failures */
56 extern int lxc_rmdir_onedev(char *path, const char *exclude);
57 extern int get_u16(unsigned short *val, const char *arg, int base);
58 extern int mkdir_p(const char *dir, mode_t mode);
59 extern char *get_rundir(void);
60
61 /* Define getline() if missing from the C library */
62 #ifndef HAVE_GETLINE
63 #ifdef HAVE_FGETLN
64 #include <../include/getline.h>
65 #endif
66 #endif
67
68 /* Define setns() if missing from the C library */
69 #ifndef HAVE_SETNS
70 static inline int setns(int fd, int nstype)
71 {
72 #ifdef __NR_setns
73 return syscall(__NR_setns, fd, nstype);
74 #elif defined(__NR_set_ns)
75 return syscall(__NR_set_ns, fd, nstype);
76 #else
77 errno = ENOSYS;
78 return -1;
79 #endif
80 }
81 #endif
82
83 /* Define unshare() if missing from the C library */
84 #ifndef HAVE_UNSHARE
85 static inline int unshare(int flags)
86 {
87 #ifdef __NR_unshare
88 return syscall(__NR_unshare, flags);
89 #else
90 errno = ENOSYS;
91 return -1;
92 #endif
93 }
94 #else
95 extern int unshare(int);
96 #endif
97
98 /* Define signalfd() if missing from the C library */
99 #ifdef HAVE_SYS_SIGNALFD_H
100 # include <sys/signalfd.h>
101 #else
102 /* assume kernel headers are too old */
103 #include <stdint.h>
104 struct signalfd_siginfo
105 {
106 uint32_t ssi_signo;
107 int32_t ssi_errno;
108 int32_t ssi_code;
109 uint32_t ssi_pid;
110 uint32_t ssi_uid;
111 int32_t ssi_fd;
112 uint32_t ssi_tid;
113 uint32_t ssi_band;
114 uint32_t ssi_overrun;
115 uint32_t ssi_trapno;
116 int32_t ssi_status;
117 int32_t ssi_int;
118 uint64_t ssi_ptr;
119 uint64_t ssi_utime;
120 uint64_t ssi_stime;
121 uint64_t ssi_addr;
122 uint8_t __pad[48];
123 };
124
125 # ifndef __NR_signalfd4
126 /* assume kernel headers are too old */
127 # if __i386__
128 # define __NR_signalfd4 327
129 # elif __x86_64__
130 # define __NR_signalfd4 289
131 # elif __powerpc__
132 # define __NR_signalfd4 313
133 # elif __s390x__
134 # define __NR_signalfd4 322
135 # elif __arm__
136 # define __NR_signalfd4 355
137 # elif __mips__ && _MIPS_SIM == _ABIO32
138 # define __NR_signalfd4 4324
139 # elif __mips__ && _MIPS_SIM == _ABI64
140 # define __NR_signalfd4 5283
141 # elif __mips__ && _MIPS_SIM == _ABIN32
142 # define __NR_signalfd4 6287
143 # endif
144 #endif
145
146 # ifndef __NR_signalfd
147 /* assume kernel headers are too old */
148 # if __i386__
149 # define __NR_signalfd 321
150 # elif __x86_64__
151 # define __NR_signalfd 282
152 # elif __powerpc__
153 # define __NR_signalfd 305
154 # elif __s390x__
155 # define __NR_signalfd 316
156 # elif __arm__
157 # define __NR_signalfd 349
158 # elif __mips__ && _MIPS_SIM == _ABIO32
159 # define __NR_signalfd 4317
160 # elif __mips__ && _MIPS_SIM == _ABI64
161 # define __NR_signalfd 5276
162 # elif __mips__ && _MIPS_SIM == _ABIN32
163 # define __NR_signalfd 6280
164 # endif
165 #endif
166
167 static inline int signalfd(int fd, const sigset_t *mask, int flags)
168 {
169 int retval;
170
171 retval = syscall (__NR_signalfd4, fd, mask, _NSIG / 8, flags);
172 if (errno == ENOSYS && flags == 0)
173 retval = syscall (__NR_signalfd, fd, mask, _NSIG / 8);
174 return retval;
175 }
176 #endif
177
178 /* loop devices */
179 #ifndef LO_FLAGS_AUTOCLEAR
180 #define LO_FLAGS_AUTOCLEAR 4
181 #endif
182
183 #ifndef LOOP_CTL_GET_FREE
184 #define LOOP_CTL_GET_FREE 0x4C82
185 #endif
186
187 /* Struct to carry child pid from lxc_popen() to lxc_pclose().
188 * Not an opaque struct to allow direct access to the underlying FILE *
189 * (i.e., struct lxc_popen_FILE *file; fgets(buf, sizeof(buf), file->f))
190 * without additional wrappers.
191 */
192 struct lxc_popen_FILE {
193 int pipe;
194 FILE *f;
195 pid_t child_pid;
196 };
197
198 /* popen(command, "re") replacement that restores default signal mask
199 * via sigprocmask(2) (unblocks all signals) after fork(2) but prior to calling exec(3).
200 * In short, popen(command, "re") does pipe() + fork() + exec()
201 * while lxc_popen(command) does pipe() + fork() + sigprocmask() + exec().
202 * Returns pointer to struct lxc_popen_FILE, that should be freed with lxc_pclose().
203 * On error returns NULL.
204 */
205 extern struct lxc_popen_FILE *lxc_popen(const char *command);
206
207 /* pclose() replacement to be used on struct lxc_popen_FILE *,
208 * returned by lxc_popen().
209 * Waits for associated process to terminate, returns its exit status and
210 * frees resources, pointed to by struct lxc_popen_FILE *.
211 */
212 extern int lxc_pclose(struct lxc_popen_FILE *fp);
213
214 /**
215 * BUILD_BUG_ON - break compile if a condition is true.
216 * @condition: the condition which the compiler should know is false.
217 *
218 * If you have some code which relies on certain constants being equal, or
219 * other compile-time-evaluated condition, you should use BUILD_BUG_ON to
220 * detect if someone changes it.
221 *
222 * The implementation uses gcc's reluctance to create a negative array, but
223 * gcc (as of 4.4) only emits that error for obvious cases (eg. not arguments
224 * to inline functions). So as a fallback we use the optimizer; if it can't
225 * prove the condition is false, it will cause a link error on the undefined
226 * "__build_bug_on_failed". This error message can be harder to track down
227 * though, hence the two different methods.
228 */
229 #ifndef __OPTIMIZE__
230 #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
231 #else
232 extern int __build_bug_on_failed;
233 #define BUILD_BUG_ON(condition) \
234 do { \
235 ((void)sizeof(char[1 - 2*!!(condition)])); \
236 if (condition) __build_bug_on_failed = 1; \
237 } while(0)
238 #endif
239
240 /*
241 * wait on a child we forked
242 */
243 extern int wait_for_pid(pid_t pid);
244 extern int lxc_wait_for_pid_status(pid_t pid);
245
246 /* send and receive buffers completely */
247 extern ssize_t lxc_write_nointr(int fd, const void* buf, size_t count);
248 extern ssize_t lxc_read_nointr(int fd, void* buf, size_t count);
249 extern ssize_t lxc_read_nointr_expect(int fd, void *buf, size_t count,
250 const void *expected_buf);
251 #if HAVE_LIBGNUTLS
252 #define SHA_DIGEST_LENGTH 20
253 extern int sha1sum_file(char *fnam, unsigned char *md_value);
254 #endif
255
256 /* read and write whole files */
257 extern int lxc_write_to_file(const char *filename, const void *buf,
258 size_t count, bool add_newline);
259 extern int lxc_read_from_file(const char *filename, void* buf, size_t count);
260
261 /* convert variadic argument lists to arrays (for execl type argument lists) */
262 extern char** lxc_va_arg_list_to_argv(va_list ap, size_t skip, int do_strdup);
263 extern const char** lxc_va_arg_list_to_argv_const(va_list ap, size_t skip);
264
265 /* Some simple string functions; if they return pointers, they are allocated
266 * buffers.
267 */
268 extern char *lxc_string_replace(const char *needle, const char *replacement,
269 const char *haystack);
270 extern bool lxc_string_in_array(const char *needle, const char **haystack);
271 extern char *lxc_string_join(const char *sep, const char **parts,
272 bool use_as_prefix);
273 /* Normalize and split path: Leading and trailing / are removed, multiple
274 * / are compactified, .. and . are resolved (.. on the top level is considered
275 * identical to .).
276 * Examples:
277 * / -> { NULL }
278 * foo/../bar -> { bar, NULL }
279 * ../../ -> { NULL }
280 * ./bar/baz/.. -> { bar, NULL }
281 * foo//bar -> { foo, bar, NULL }
282 */
283 extern char **lxc_normalize_path(const char *path);
284 /* remove multiple slashes from the path, e.g. ///foo//bar -> /foo/bar */
285 extern char *lxc_deslashify(const char *path);
286 extern char *lxc_append_paths(const char *first, const char *second);
287 /* Note: the following two functions use strtok(), so they will never
288 * consider an empty element, even if two delimiters are next to
289 * each other.
290 */
291 extern bool lxc_string_in_list(const char *needle, const char *haystack,
292 char sep);
293 extern char **lxc_string_split(const char *string, char sep);
294 extern char **lxc_string_split_and_trim(const char *string, char sep);
295 extern char **lxc_string_split_quoted(char *string);
296 /* Append string to NULL-terminated string array. */
297 extern int lxc_append_string(char ***list, char *entry);
298
299 /* some simple array manipulation utilities */
300 typedef void (*lxc_free_fn)(void *);
301 typedef void *(*lxc_dup_fn)(void *);
302 extern int lxc_grow_array(void ***array, size_t *capacity, size_t new_size,
303 size_t capacity_increment);
304 extern void lxc_free_array(void **array, lxc_free_fn element_free_fn);
305 extern size_t lxc_array_len(void **array);
306
307 extern void **lxc_append_null_to_array(void **array, size_t count);
308
309 /* mmap() wrapper. lxc_strmmap() will take care to \0-terminate files so that
310 * normal string-handling functions can be used on the buffer. */
311 extern void *lxc_strmmap(void *addr, size_t length, int prot, int flags, int fd,
312 off_t offset);
313 /* munmap() wrapper. Use it to free memory mmap()ed with lxc_strmmap(). */
314 extern int lxc_strmunmap(void *addr, size_t length);
315
316 /* initialize rand with urandom */
317 extern int randseed(bool);
318
319 inline static bool am_unpriv(void) {
320 return geteuid() != 0;
321 }
322
323 /*
324 * parse /proc/self/uid_map to find what @orig maps to
325 */
326 extern uid_t get_ns_uid(uid_t orig);
327
328 extern bool dir_exists(const char *path);
329
330 #define FNV1A_64_INIT ((uint64_t)0xcbf29ce484222325ULL)
331 extern uint64_t fnv_64a_buf(void *buf, size_t len, uint64_t hval);
332
333 extern int detect_shared_rootfs(void);
334 extern bool detect_ramfs_rootfs(void);
335 extern char *on_path(const char *cmd, const char *rootfs);
336 extern bool file_exists(const char *f);
337 extern bool cgns_supported(void);
338 extern char *choose_init(const char *rootfs);
339 extern int print_to_file(const char *file, const char *content);
340 extern bool switch_to_ns(pid_t pid, const char *ns);
341 extern int is_dir(const char *path);
342 extern char *get_template_path(const char *t);
343 extern int setproctitle(char *title);
344 extern int safe_mount(const char *src, const char *dest, const char *fstype,
345 unsigned long flags, const void *data,
346 const char *rootfs);
347 extern int lxc_mount_proc_if_needed(const char *rootfs);
348 extern int open_devnull(void);
349 extern int set_stdfds(int fd);
350 extern int null_stdfds(void);
351 extern int lxc_count_file_lines(const char *fn);
352 extern int lxc_preserve_ns(const int pid, const char *ns);
353
354 /* Check whether a signal is blocked by a process. */
355 extern bool task_blocking_signal(pid_t pid, int signal);
356
357 /* Helper functions to parse numbers. */
358 extern int lxc_safe_uint(const char *numstr, unsigned int *converted);
359 extern int lxc_safe_int(const char *numstr, int *converted);
360 extern int lxc_safe_long(const char *numstr, long int *converted);
361 extern int lxc_safe_ulong(const char *numstr, unsigned long *converted);
362
363 /* Switch to a new uid and gid. */
364 extern int lxc_switch_uid_gid(uid_t uid, gid_t gid);
365 extern int lxc_setgroups(int size, gid_t list[]);
366
367 /* Find an unused loop device and associate it with source. */
368 extern int lxc_prepare_loop_dev(const char *source, char *loop_dev, int flags);
369
370 /* Clear all mounts on a given node.
371 * >= 0 successfully cleared. The number returned is the number of umounts
372 * performed.
373 * < 0 error umounting. Return -errno.
374 */
375 extern int lxc_unstack_mountpoint(const char *path, bool lazy);
376
377 /*
378 * run_command runs a command and collect it's std{err,out} output in buf.
379 *
380 * @param[out] buf The buffer where the commands std{err,out] output will be
381 * read into. If no output was produced, buf will be memset
382 * to 0.
383 * @param[in] buf_size The size of buf. This function will reserve one byte for
384 * \0-termination.
385 * @param[in] child_fn The function to be run in the child process. This
386 * function must exec.
387 * @param[in] args Arguments to be passed to child_fn.
388 */
389 extern int run_command(char *buf, size_t buf_size, int (*child_fn)(void *),
390 void *args);
391
392 /* Concatenate all passed-in strings into one path. Do not fail. If any piece
393 * is not prefixed with '/', add a '/'.
394 */
395 extern char *must_make_path(const char *first, ...) __attribute__((sentinel));
396
397 /* return copy of string @entry; do not fail. */
398 extern char *must_copy_string(const char *entry);
399
400 /* Re-alllocate a pointer, do not fail */
401 extern void *must_realloc(void *orig, size_t sz);
402
403 /* __typeof__ should be safe to use with all compilers. */
404 typedef __typeof__(((struct statfs *)NULL)->f_type) fs_type_magic;
405 extern bool has_fs_type(const char *path, fs_type_magic magic_val);
406 extern bool is_fs_type(const struct statfs *fs, fs_type_magic magic_val);
407 extern bool lxc_nic_exists(char *nic);
408
409 #endif /* __LXC_UTILS_H */