]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/import/import-raw.c
tree-wide: check if return value of lseek() and friends is negative
[thirdparty/systemd.git] / src / import / import-raw.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/fs.h>
4
5 #include "sd-daemon.h"
6 #include "sd-event.h"
7
8 #include "alloc-util.h"
9 #include "btrfs-util.h"
10 #include "copy.h"
11 #include "fd-util.h"
12 #include "format-util.h"
13 #include "fs-util.h"
14 #include "hostname-util.h"
15 #include "import-common.h"
16 #include "import-compress.h"
17 #include "import-raw.h"
18 #include "install-file.h"
19 #include "io-util.h"
20 #include "machine-pool.h"
21 #include "mkdir-label.h"
22 #include "path-util.h"
23 #include "qcow2-util.h"
24 #include "ratelimit.h"
25 #include "rm-rf.h"
26 #include "string-util.h"
27 #include "tmpfile-util.h"
28
29 struct RawImport {
30 sd_event *event;
31
32 char *image_root;
33
34 RawImportFinished on_finished;
35 void *userdata;
36
37 char *local;
38 ImportFlags flags;
39
40 char *temp_path;
41 char *final_path;
42
43 int input_fd;
44 int output_fd;
45
46 ImportCompress compress;
47
48 sd_event_source *input_event_source;
49
50 uint8_t buffer[16*1024];
51 size_t buffer_size;
52
53 uint64_t written_compressed;
54 uint64_t written_uncompressed;
55
56 struct stat input_stat;
57 struct stat output_stat;
58
59 unsigned last_percent;
60 RateLimit progress_ratelimit;
61
62 uint64_t offset;
63 uint64_t size_max;
64 };
65
66 RawImport* raw_import_unref(RawImport *i) {
67 if (!i)
68 return NULL;
69
70 sd_event_source_unref(i->input_event_source);
71
72 unlink_and_free(i->temp_path);
73
74 import_compress_free(&i->compress);
75
76 sd_event_unref(i->event);
77
78 safe_close(i->output_fd);
79
80 free(i->final_path);
81 free(i->image_root);
82 free(i->local);
83 return mfree(i);
84 }
85
86 int raw_import_new(
87 RawImport **ret,
88 sd_event *event,
89 const char *image_root,
90 RawImportFinished on_finished,
91 void *userdata) {
92
93 _cleanup_(raw_import_unrefp) RawImport *i = NULL;
94 _cleanup_free_ char *root = NULL;
95 int r;
96
97 assert(ret);
98
99 root = strdup(image_root ?: "/var/lib/machines");
100 if (!root)
101 return -ENOMEM;
102
103 i = new(RawImport, 1);
104 if (!i)
105 return -ENOMEM;
106
107 *i = (RawImport) {
108 .input_fd = -EBADF,
109 .output_fd = -EBADF,
110 .on_finished = on_finished,
111 .userdata = userdata,
112 .last_percent = UINT_MAX,
113 .image_root = TAKE_PTR(root),
114 .progress_ratelimit = { 100 * USEC_PER_MSEC, 1 },
115 .offset = UINT64_MAX,
116 .size_max = UINT64_MAX,
117 };
118
119 if (event)
120 i->event = sd_event_ref(event);
121 else {
122 r = sd_event_default(&i->event);
123 if (r < 0)
124 return r;
125 }
126
127 *ret = TAKE_PTR(i);
128 return 0;
129 }
130
131 static void raw_import_report_progress(RawImport *i) {
132 unsigned percent;
133 assert(i);
134
135 /* We have no size information, unless the source is a regular file */
136 if (!S_ISREG(i->input_stat.st_mode))
137 return;
138
139 if (i->written_compressed >= (uint64_t) i->input_stat.st_size)
140 percent = 100;
141 else
142 percent = (unsigned) ((i->written_compressed * UINT64_C(100)) / (uint64_t) i->input_stat.st_size);
143
144 if (percent == i->last_percent)
145 return;
146
147 if (!ratelimit_below(&i->progress_ratelimit))
148 return;
149
150 sd_notifyf(false, "X_IMPORT_PROGRESS=%u", percent);
151 log_info("Imported %u%%.", percent);
152
153 i->last_percent = percent;
154 }
155
156 static int raw_import_maybe_convert_qcow2(RawImport *i) {
157 _cleanup_close_ int converted_fd = -EBADF;
158 _cleanup_(unlink_and_freep) char *t = NULL;
159 _cleanup_free_ char *f = NULL;
160 int r;
161
162 assert(i);
163
164 /* Do QCOW2 conversion if enabled and not in direct mode */
165 if ((i->flags & (IMPORT_CONVERT_QCOW2|IMPORT_DIRECT)) != IMPORT_CONVERT_QCOW2)
166 return 0;
167
168 assert(i->final_path);
169
170 r = qcow2_detect(i->output_fd);
171 if (r < 0)
172 return log_error_errno(r, "Failed to detect whether this is a QCOW2 image: %m");
173 if (r == 0)
174 return 0;
175
176 /* This is a QCOW2 image, let's convert it */
177 r = tempfn_random(i->final_path, NULL, &f);
178 if (r < 0)
179 return log_oom();
180
181 converted_fd = open(f, O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_CLOEXEC, 0664);
182 if (converted_fd < 0)
183 return log_error_errno(errno, "Failed to create %s: %m", f);
184
185 t = TAKE_PTR(f);
186
187 (void) import_set_nocow_and_log(converted_fd, t);
188
189 log_info("Unpacking QCOW2 file.");
190
191 r = qcow2_convert(i->output_fd, converted_fd);
192 if (r < 0)
193 return log_error_errno(r, "Failed to convert qcow2 image: %m");
194
195 unlink_and_free(i->temp_path);
196 i->temp_path = TAKE_PTR(t);
197 close_and_replace(i->output_fd, converted_fd);
198
199 return 1;
200 }
201
202 static int raw_import_finish(RawImport *i) {
203 int r;
204
205 assert(i);
206 assert(i->output_fd >= 0);
207
208 /* Nothing of what is below applies to block devices */
209 if (S_ISBLK(i->output_stat.st_mode)) {
210
211 if (i->flags & IMPORT_SYNC) {
212 if (fsync(i->output_fd) < 0)
213 return log_error_errno(errno, "Failed to synchronize block device: %m");
214 }
215
216 return 0;
217 }
218
219 assert(S_ISREG(i->output_stat.st_mode));
220
221 /* If an offset is specified we only are supposed to affect part of an existing output file or block
222 * device, thus don't manipulate file properties in that case */
223
224 if (i->offset == UINT64_MAX) {
225 /* In case this was a sparse file, make sure the file size is right */
226 if (i->written_uncompressed > 0) {
227 if (ftruncate(i->output_fd, i->written_uncompressed) < 0)
228 return log_error_errno(errno, "Failed to truncate file: %m");
229 }
230
231 r = raw_import_maybe_convert_qcow2(i);
232 if (r < 0)
233 return r;
234
235 if (S_ISREG(i->input_stat.st_mode)) {
236 (void) copy_times(i->input_fd, i->output_fd, COPY_CRTIME);
237 (void) copy_xattr(i->input_fd, NULL, i->output_fd, NULL, 0);
238 }
239 }
240
241 r = install_file(AT_FDCWD, i->temp_path ?: i->local,
242 AT_FDCWD, i->final_path,
243 (i->flags & IMPORT_FORCE ? INSTALL_REPLACE : 0) |
244 (i->flags & IMPORT_READ_ONLY ? INSTALL_READ_ONLY : 0) |
245 (i->flags & IMPORT_SYNC ? INSTALL_FSYNC_FULL : 0));
246 if (r < 0)
247 return log_error_errno(r, "Failed to move image into place: %m");
248
249 i->temp_path = mfree(i->temp_path);
250
251 log_info("Wrote %s.", FORMAT_BYTES(i->written_uncompressed));
252
253 return 0;
254 }
255
256 static int raw_import_open_disk(RawImport *i) {
257 int r;
258
259 assert(i);
260 assert(i->local);
261 assert(!i->final_path);
262 assert(!i->temp_path);
263 assert(i->output_fd < 0);
264
265 if (i->flags & IMPORT_DIRECT) {
266 (void) mkdir_parents_label(i->local, 0700);
267
268 /* In direct mode we just open/create the local path and truncate it (like shell >
269 * redirection would do it) — except if an offset was passed, in which case we are supposed
270 * to operate on a section of the file only, in which case we apparently work on an some
271 * existing thing (i.e. are not the sole thing stored in the file), in which case we will
272 * neither truncate nor create. */
273
274 i->output_fd = open(i->local, O_RDWR|O_NOCTTY|O_CLOEXEC|(i->offset == UINT64_MAX ? O_TRUNC|O_CREAT : 0), 0664);
275 if (i->output_fd < 0)
276 return log_error_errno(errno, "Failed to open destination '%s': %m", i->local);
277
278 if (i->offset == UINT64_MAX)
279 (void) import_set_nocow_and_log(i->output_fd, i->local);
280 } else {
281 i->final_path = strjoin(i->image_root, "/", i->local, ".raw");
282 if (!i->final_path)
283 return log_oom();
284
285 r = tempfn_random(i->final_path, NULL, &i->temp_path);
286 if (r < 0)
287 return log_oom();
288
289 (void) mkdir_parents_label(i->temp_path, 0700);
290
291 i->output_fd = open(i->temp_path, O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_CLOEXEC, 0664);
292 if (i->output_fd < 0)
293 return log_error_errno(errno, "Failed to open destination '%s': %m", i->temp_path);
294
295 (void) import_set_nocow_and_log(i->output_fd, i->temp_path);
296 }
297
298 if (fstat(i->output_fd, &i->output_stat) < 0)
299 return log_error_errno(errno, "Failed to stat() output file: %m");
300
301 if (!S_ISREG(i->output_stat.st_mode) && !S_ISBLK(i->output_stat.st_mode))
302 return log_error_errno(SYNTHETIC_ERRNO(EBADFD),
303 "Target file is not a regular file or block device");
304
305 if (i->offset != UINT64_MAX) {
306 if (lseek(i->output_fd, i->offset, SEEK_SET) < 0)
307 return log_error_errno(errno, "Failed to seek to offset: %m");
308 }
309
310 return 0;
311 }
312
313 static int raw_import_try_reflink(RawImport *i) {
314 off_t p;
315 int r;
316
317 assert(i);
318 assert(i->input_fd >= 0);
319 assert(i->output_fd >= 0);
320
321 if (i->compress.type != IMPORT_COMPRESS_UNCOMPRESSED)
322 return 0;
323
324 if (i->offset != UINT64_MAX || i->size_max != UINT64_MAX)
325 return 0;
326
327 if (!S_ISREG(i->input_stat.st_mode) || !S_ISREG(i->output_stat.st_mode))
328 return 0;
329
330 p = lseek(i->input_fd, 0, SEEK_CUR);
331 if (p < 0)
332 return log_error_errno(errno, "Failed to read file offset of input file: %m");
333
334 /* Let's only try a btrfs reflink, if we are reading from the beginning of the file */
335 if ((uint64_t) p != (uint64_t) i->buffer_size)
336 return 0;
337
338 r = reflink(i->input_fd, i->output_fd);
339 if (r >= 0)
340 return 1;
341
342 log_debug_errno(r, "Couldn't establish reflink, using copy: %m");
343 return 0;
344 }
345
346 static int raw_import_write(const void *p, size_t sz, void *userdata) {
347 RawImport *i = ASSERT_PTR(userdata);
348 bool too_much = false;
349 int r;
350
351 assert(p);
352 assert(sz > 0);
353
354 if (i->written_uncompressed >= UINT64_MAX - sz)
355 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
356
357 if (i->size_max != UINT64_MAX) {
358 if (i->written_uncompressed >= i->size_max) {
359 too_much = true;
360 goto finish;
361 }
362
363 if (i->written_uncompressed + sz > i->size_max) {
364 too_much = true;
365 sz = i->size_max - i->written_uncompressed; /* since we have the data in memory
366 * already, we might as well write it to
367 * disk to the max */
368 }
369 }
370
371 /* Generate sparse file if we created/truncated the file */
372 if (S_ISREG(i->output_stat.st_mode) && i->offset == UINT64_MAX) {
373 ssize_t n;
374
375 n = sparse_write(i->output_fd, p, sz, 64);
376 if (n < 0)
377 return log_error_errno((int) n, "Failed to write file: %m");
378 if ((size_t) n < sz)
379 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write");
380 } else {
381 r = loop_write(i->output_fd, p, sz);
382 if (r < 0)
383 return log_error_errno(r, "Failed to write file: %m");
384 }
385
386 i->written_uncompressed += sz;
387
388 finish:
389 if (too_much)
390 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "File too large");
391
392 return 0;
393 }
394
395 static int raw_import_process(RawImport *i) {
396 ssize_t l;
397 int r;
398
399 assert(i);
400 assert(i->buffer_size < sizeof(i->buffer));
401
402 l = read(i->input_fd, i->buffer + i->buffer_size, sizeof(i->buffer) - i->buffer_size);
403 if (l < 0) {
404 if (errno == EAGAIN)
405 return 0;
406
407 r = log_error_errno(errno, "Failed to read input file: %m");
408 goto finish;
409 }
410
411 i->buffer_size += l;
412
413 if (i->compress.type == IMPORT_COMPRESS_UNKNOWN) {
414
415 if (l == 0) { /* EOF */
416 log_debug("File too short to be compressed, as no compression signature fits in, thus assuming uncompressed.");
417 import_uncompress_force_off(&i->compress);
418 } else {
419 r = import_uncompress_detect(&i->compress, i->buffer, i->buffer_size);
420 if (r < 0) {
421 log_error_errno(r, "Failed to detect file compression: %m");
422 goto finish;
423 }
424 if (r == 0) /* Need more data */
425 return 0;
426 }
427
428 r = raw_import_open_disk(i);
429 if (r < 0)
430 goto finish;
431
432 r = raw_import_try_reflink(i);
433 if (r < 0)
434 goto finish;
435 if (r > 0)
436 goto complete;
437 }
438
439 r = import_uncompress(&i->compress, i->buffer, i->buffer_size, raw_import_write, i);
440 if (r < 0) {
441 log_error_errno(r, "Failed to decode and write: %m");
442 goto finish;
443 }
444
445 i->written_compressed += i->buffer_size;
446 i->buffer_size = 0;
447
448 if (l == 0) /* EOF */
449 goto complete;
450
451 raw_import_report_progress(i);
452
453 return 0;
454
455 complete:
456 r = raw_import_finish(i);
457
458 finish:
459 if (i->on_finished)
460 i->on_finished(i, r, i->userdata);
461 else
462 sd_event_exit(i->event, r);
463
464 return 0;
465 }
466
467 static int raw_import_on_input(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
468 RawImport *i = userdata;
469
470 return raw_import_process(i);
471 }
472
473 static int raw_import_on_defer(sd_event_source *s, void *userdata) {
474 RawImport *i = userdata;
475
476 return raw_import_process(i);
477 }
478
479 int raw_import_start(
480 RawImport *i,
481 int fd,
482 const char *local,
483 uint64_t offset,
484 uint64_t size_max,
485 ImportFlags flags) {
486 int r;
487
488 assert(i);
489 assert(fd >= 0);
490 assert(local);
491 assert(!(flags & ~IMPORT_FLAGS_MASK_RAW));
492 assert(offset == UINT64_MAX || FLAGS_SET(flags, IMPORT_DIRECT));
493
494 if (!import_validate_local(local, flags))
495 return -EINVAL;
496
497 if (i->input_fd >= 0)
498 return -EBUSY;
499
500 r = fd_nonblock(fd, true);
501 if (r < 0)
502 return r;
503
504 r = free_and_strdup(&i->local, local);
505 if (r < 0)
506 return r;
507
508 i->flags = flags;
509 i->offset = offset;
510 i->size_max = size_max;
511
512 if (fstat(fd, &i->input_stat) < 0)
513 return -errno;
514
515 r = sd_event_add_io(i->event, &i->input_event_source, fd, EPOLLIN, raw_import_on_input, i);
516 if (r == -EPERM) {
517 /* This fd does not support epoll, for example because it is a regular file. Busy read in that case */
518 r = sd_event_add_defer(i->event, &i->input_event_source, raw_import_on_defer, i);
519 if (r < 0)
520 return r;
521
522 r = sd_event_source_set_enabled(i->input_event_source, SD_EVENT_ON);
523 }
524 if (r < 0)
525 return r;
526
527 i->input_fd = fd;
528 return 0;
529 }