]>
git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/parse.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
12 #include <sys/sendfile.h>
15 #include "file_utils.h"
19 #include "syscall_wrappers.h"
22 lxc_log_define(parse
, lxc
);
24 void *lxc_strmmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
27 void *tmp
= NULL
, *overlap
= NULL
;
29 /* We establish an anonymous mapping that is one byte larger than the
30 * underlying file. The pages handed to us are zero filled. */
31 tmp
= mmap(addr
, length
+ 1, PROT_READ
, MAP_PRIVATE
| MAP_ANONYMOUS
, -1, 0);
32 if (tmp
== MAP_FAILED
)
35 /* Now we establish a fixed-address mapping starting at the address we
36 * received from our anonymous mapping and replace all bytes excluding
37 * the additional \0-byte with the file. This allows us to use normal
38 * string-handling functions. */
39 overlap
= mmap(tmp
, length
, prot
, MAP_FIXED
| flags
, fd
, offset
);
40 if (overlap
== MAP_FAILED
)
41 munmap(tmp
, length
+ 1);
46 int lxc_strmunmap(void *addr
, size_t length
)
48 return munmap(addr
, length
+ 1);
51 int lxc_file_for_each_line_mmap(const char *file
, lxc_file_cb callback
, void *data
)
54 ssize_t ret
= -1, bytes_sent
;
56 int fd
= -1, memfd
= -1;
59 memfd
= memfd_create(".lxc_config_file", MFD_CLOEXEC
);
61 char template[] = P_tmpdir
"/.lxc_config_file_XXXXXX";
63 if (errno
!= ENOSYS
) {
64 SYSERROR("Failed to create memory file");
68 TRACE("Failed to create in-memory file. Falling back to "
70 memfd
= lxc_make_tmpfile(template, true);
72 SYSERROR("Failed to create temporary file \"%s\"", template);
77 fd
= open(file
, O_RDONLY
| O_CLOEXEC
);
79 SYSERROR("Failed to open file \"%s\"", file
);
83 /* sendfile() handles up to 2GB. No config file should be that big. */
84 bytes_sent
= lxc_sendfile_nointr(memfd
, fd
, NULL
, LXC_SENDFILE_MAX
);
86 SYSERROR("Failed to sendfile \"%s\"", file
);
90 ret
= lxc_write_nointr(memfd
, "\0", 1);
92 SYSERROR("Failed to append zero byte");
97 ret
= lseek(memfd
, 0, SEEK_SET
);
99 SYSERROR("Failed to lseek");
104 buf
= mmap(NULL
, bytes_sent
, PROT_READ
| PROT_WRITE
,
105 MAP_SHARED
| MAP_POPULATE
, memfd
, 0);
106 if (buf
== MAP_FAILED
) {
108 SYSERROR("Failed to mmap");
113 lxc_iterate_parts(line
, buf
, "\r\n\0") {
114 ret
= callback(line
, data
);
116 /* Callback rv > 0 means stop here callback rv < 0 means
120 ERROR("Failed to parse config file \"%s\" at "
121 "line \"%s\"", file
, line
);
132 if (buf
&& munmap(buf
, bytes_sent
)) {
133 SYSERROR("Failed to unmap");
142 int lxc_file_for_each_line(const char *file
, lxc_file_cb callback
, void *data
)
144 __do_fclose
FILE *f
= NULL
;
145 __do_free
char *line
= NULL
;
149 f
= fopen(file
, "re");
151 SYSERROR("Failed to open \"%s\"", file
);
155 while (getline(&line
, &len
, f
) != -1) {
156 err
= callback(line
, data
);
158 /* Callback rv > 0 means stop here callback rv < 0 means
162 ERROR("Failed to parse config: \"%s\"", line
);