]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/parse.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/sendfile.h>
16 #include "file_utils.h"
20 #include "syscall_wrappers.h"
23 lxc_log_define(parse
, lxc
);
25 void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
28 void *tmp
= NULL
, *overlap
= NULL
;
30 /* We establish an anonymous mapping that is one byte larger than the
31 * underlying file. The pages handed to us are zero filled. */
32 tmp
= mmap(addr
, length
+ 1, PROT_READ
, MAP_PRIVATE
| MAP_ANONYMOUS
, -1, 0);
33 if (tmp
== MAP_FAILED
)
36 /* Now we establish a fixed-address mapping starting at the address we
37 * received from our anonymous mapping and replace all bytes excluding
38 * the additional \0-byte with the file. This allows us to use normal
39 * string-handling functions. */
40 overlap
= mmap(tmp
, length
, prot
, MAP_FIXED
| flags
, fd
, offset
);
41 if (overlap
== MAP_FAILED
)
42 munmap(tmp
, length
+ 1);
47 int lxc_strmunmap(void *addr
, size_t length
)
49 return munmap(addr
, length
+ 1);
52 int lxc_file_for_each_line_mmap(const char *file
, lxc_file_cb callback
, void *data
)
54 __do_close
int fd
= -EBADF
, memfd
= -EBADF
;
61 memfd
= memfd_create(".lxc_config_file", MFD_CLOEXEC
);
63 char template[] = P_tmpdir
"/.lxc_config_file_XXXXXX";
65 if (errno
!= ENOSYS
) {
66 SYSERROR("Failed to create memory file");
70 TRACE("Failed to create in-memory file. Falling back to temporary file");
71 memfd
= lxc_make_tmpfile(template, true);
73 SYSERROR("Failed to create temporary file \"%s\"", template);
78 fd
= open(file
, O_RDONLY
| O_CLOEXEC
);
80 SYSERROR("Failed to open file \"%s\"", file
);
86 SYSERROR("Failed to stat file \"%s\"", file
);
90 if (st
.st_size
> INT_MAX
) {
91 SYSERROR("Excessively large config file \"%s\"", file
);
96 bytes
= __fd_to_fd(fd
, memfd
);
98 SYSERROR("Failed to copy config file \"%s\"", file
);
102 ret
= lxc_write_nointr(memfd
, "\0", 1);
104 SYSERROR("Failed to append zero byte");
109 ret
= lseek(memfd
, 0, SEEK_SET
);
111 SYSERROR("Failed to lseek");
116 buf
= mmap(NULL
, bytes
, PROT_READ
| PROT_WRITE
, MAP_PRIVATE
| MAP_POPULATE
, memfd
, 0);
117 if (buf
== MAP_FAILED
) {
119 SYSERROR("Failed to mmap");
124 lxc_iterate_parts(line
, buf
, "\r\n\0") {
125 ret
= callback(line
, data
);
127 /* Callback rv > 0 means stop here callback rv < 0 means
131 ERROR("Failed to parse config file \"%s\" at line \"%s\"",
138 if (buf
&& munmap(buf
, bytes
)) {
139 SYSERROR("Failed to unmap");
147 int lxc_file_for_each_line(const char *file
, lxc_file_cb callback
, void *data
)
149 __do_fclose
FILE *f
= NULL
;
150 __do_free
char *line
= NULL
;
154 f
= fopen(file
, "re");
156 SYSERROR("Failed to open \"%s\"", file
);
160 while (getline(&line
, &len
, f
) != -1) {
161 err
= callback(line
, data
);
163 /* Callback rv > 0 means stop here callback rv < 0 means
167 ERROR("Failed to parse config: \"%s\"", line
);