Debian Codegraph @

src/import/import-raw.c

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