]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/import/pull-job.c
Merge pull request #20456 from tomty89/man
[thirdparty/systemd.git] / src / import / pull-job.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <sys/stat.h>
5 #include <sys/xattr.h>
6
7 #include "alloc-util.h"
8 #include "fd-util.h"
9 #include "format-util.h"
10 #include "fs-util.h"
11 #include "gcrypt-util.h"
12 #include "hexdecoct.h"
13 #include "import-util.h"
14 #include "io-util.h"
15 #include "machine-pool.h"
16 #include "parse-util.h"
17 #include "pull-common.h"
18 #include "pull-job.h"
19 #include "string-util.h"
20 #include "strv.h"
21 #include "xattr-util.h"
22
23 void pull_job_close_disk_fd(PullJob *j) {
24 if (!j)
25 return;
26
27 if (j->close_disk_fd)
28 safe_close(j->disk_fd);
29
30 j->disk_fd = -1;
31 }
32
33 PullJob* pull_job_unref(PullJob *j) {
34 if (!j)
35 return NULL;
36
37 pull_job_close_disk_fd(j);
38
39 curl_glue_remove_and_free(j->glue, j->curl);
40 curl_slist_free_all(j->request_header);
41
42 import_compress_free(&j->compress);
43
44 if (j->checksum_context)
45 gcry_md_close(j->checksum_context);
46
47 free(j->url);
48 free(j->etag);
49 strv_free(j->old_etags);
50 free(j->payload);
51 free(j->checksum);
52
53 return mfree(j);
54 }
55
56 static void pull_job_finish(PullJob *j, int ret) {
57 assert(j);
58
59 if (IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED))
60 return;
61
62 if (ret == 0) {
63 j->state = PULL_JOB_DONE;
64 j->progress_percent = 100;
65 log_info("Download of %s complete.", j->url);
66 } else {
67 j->state = PULL_JOB_FAILED;
68 j->error = ret;
69 }
70
71 if (j->on_finished)
72 j->on_finished(j);
73 }
74
75 static int pull_job_restart(PullJob *j, const char *new_url) {
76 int r;
77
78 assert(j);
79 assert(new_url);
80
81 r = free_and_strdup(&j->url, new_url);
82 if (r < 0)
83 return r;
84
85 j->state = PULL_JOB_INIT;
86 j->error = 0;
87 j->payload = mfree(j->payload);
88 j->payload_size = 0;
89 j->written_compressed = 0;
90 j->written_uncompressed = 0;
91 j->content_length = UINT64_MAX;
92 j->etag = mfree(j->etag);
93 j->etag_exists = false;
94 j->mtime = 0;
95 j->checksum = mfree(j->checksum);
96
97 curl_glue_remove_and_free(j->glue, j->curl);
98 j->curl = NULL;
99
100 curl_slist_free_all(j->request_header);
101 j->request_header = NULL;
102
103 import_compress_free(&j->compress);
104
105 if (j->checksum_context) {
106 gcry_md_close(j->checksum_context);
107 j->checksum_context = NULL;
108 }
109
110 r = pull_job_begin(j);
111 if (r < 0)
112 return r;
113
114 return 0;
115 }
116
117 void pull_job_curl_on_finished(CurlGlue *g, CURL *curl, CURLcode result) {
118 PullJob *j = NULL;
119 CURLcode code;
120 long status;
121 int r;
122
123 if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&j) != CURLE_OK)
124 return;
125
126 if (!j || IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED))
127 return;
128
129 if (result != CURLE_OK) {
130 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Transfer failed: %s", curl_easy_strerror(result));
131 goto finish;
132 }
133
134 code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
135 if (code != CURLE_OK) {
136 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve response code: %s", curl_easy_strerror(code));
137 goto finish;
138 } else if (status == 304) {
139 log_info("Image already downloaded. Skipping download.");
140 j->etag_exists = true;
141 r = 0;
142 goto finish;
143 } else if (status >= 300) {
144
145 if (status == 404 && j->on_not_found) {
146 _cleanup_free_ char *new_url = NULL;
147
148 /* This resource wasn't found, but the implementor wants to maybe let us know a new URL, query for it. */
149 r = j->on_not_found(j, &new_url);
150 if (r < 0)
151 goto finish;
152
153 if (r > 0) { /* A new url to use */
154 assert(new_url);
155
156 r = pull_job_restart(j, new_url);
157 if (r < 0)
158 goto finish;
159
160 code = curl_easy_getinfo(j->curl, CURLINFO_RESPONSE_CODE, &status);
161 if (code != CURLE_OK) {
162 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve response code: %s", curl_easy_strerror(code));
163 goto finish;
164 }
165
166 if (status == 0)
167 return;
168 }
169 }
170
171 r = log_error_errno(
172 status == 404 ? SYNTHETIC_ERRNO(ENOMEDIUM) : SYNTHETIC_ERRNO(EIO), /* Make the most common error recognizable */
173 "HTTP request to %s failed with code %li.", j->url, status);
174 goto finish;
175 } else if (status < 200) {
176 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "HTTP request to %s finished with unexpected code %li.", j->url, status);
177 goto finish;
178 }
179
180 if (j->state != PULL_JOB_RUNNING) {
181 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Premature connection termination.");
182 goto finish;
183 }
184
185 if (j->content_length != UINT64_MAX &&
186 j->content_length != j->written_compressed) {
187 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Download truncated.");
188 goto finish;
189 }
190
191 if (j->checksum_context) {
192 uint8_t *k;
193
194 k = gcry_md_read(j->checksum_context, GCRY_MD_SHA256);
195 if (!k) {
196 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get checksum.");
197 goto finish;
198 }
199
200 j->checksum = hexmem(k, gcry_md_get_algo_dlen(GCRY_MD_SHA256));
201 if (!j->checksum) {
202 r = log_oom();
203 goto finish;
204 }
205
206 log_debug("SHA256 of %s is %s.", j->url, j->checksum);
207 }
208
209 /* Do a couple of finishing disk operations, but only if we are the sole owner of the file (i.e. no
210 * offset is specified, which indicates we only own the file partially) */
211
212 if (j->disk_fd >= 0) {
213
214 if (S_ISREG(j->disk_stat.st_mode)) {
215
216 if (j->offset == UINT64_MAX) {
217
218 if (j->written_compressed > 0) {
219 /* Make sure the file size is right, in case the file was sparse and we just seeked
220 * for the last part */
221 if (ftruncate(j->disk_fd, j->written_uncompressed) < 0) {
222 r = log_error_errno(errno, "Failed to truncate file: %m");
223 goto finish;
224 }
225 }
226
227 if (j->etag)
228 (void) fsetxattr(j->disk_fd, "user.source_etag", j->etag, strlen(j->etag), 0);
229 if (j->url)
230 (void) fsetxattr(j->disk_fd, "user.source_url", j->url, strlen(j->url), 0);
231
232 if (j->mtime != 0) {
233 struct timespec ut;
234
235 timespec_store(&ut, j->mtime);
236
237 if (futimens(j->disk_fd, (struct timespec[]) { ut, ut }) < 0)
238 log_debug_errno(errno, "Failed to adjust atime/mtime of created image, ignoring: %m");
239
240 r = fd_setcrtime(j->disk_fd, j->mtime);
241 if (r < 0)
242 log_debug_errno(r, "Failed to adjust crtime of created image, ignoring: %m");
243 }
244 }
245
246 if (j->sync) {
247 r = fsync_full(j->disk_fd);
248 if (r < 0) {
249 log_error_errno(r, "Failed to synchronize file to disk: %m");
250 goto finish;
251 }
252 }
253
254 } else if (S_ISBLK(j->disk_stat.st_mode) && j->sync) {
255
256 if (fsync(j->disk_fd) < 0) {
257 r = log_error_errno(errno, "Failed to synchronize block device: %m");
258 goto finish;
259 }
260 }
261 }
262
263 r = 0;
264
265 finish:
266 pull_job_finish(j, r);
267 }
268
269 static int pull_job_write_uncompressed(const void *p, size_t sz, void *userdata) {
270 PullJob *j = userdata;
271 bool too_much = false;
272 int r;
273
274 assert(j);
275 assert(p);
276 assert(sz > 0);
277
278 if (j->written_uncompressed > UINT64_MAX - sz)
279 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
280
281 if (j->written_uncompressed >= j->uncompressed_max) {
282 too_much = true;
283 goto finish;
284 }
285
286 if (j->written_uncompressed + sz > j->uncompressed_max) {
287 too_much = true;
288 sz = j->uncompressed_max - j->written_uncompressed; /* since we have the data in memory
289 * already, we might as well write it to
290 * disk to the max */
291 }
292
293 if (j->disk_fd >= 0) {
294
295 if (S_ISREG(j->disk_stat.st_mode)) {
296 ssize_t n;
297
298 n = sparse_write(j->disk_fd, p, sz, 64);
299 if (n < 0)
300 return log_error_errno((int) n, "Failed to write file: %m");
301 if ((size_t) n < sz)
302 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write");
303 } else {
304 r = loop_write(j->disk_fd, p, sz, false);
305 if (r < 0)
306 return log_error_errno(r, "Failed to write file: %m");
307 }
308 }
309
310 if (j->disk_fd < 0 || j->force_memory) {
311 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz))
312 return log_oom();
313
314 memcpy(j->payload + j->payload_size, p, sz);
315 j->payload_size += sz;
316 }
317
318 j->written_uncompressed += sz;
319
320 finish:
321 if (too_much)
322 return log_error_errno(SYNTHETIC_ERRNO(EFBIG), "File overly large, refusing.");
323
324 return 0;
325 }
326
327 static int pull_job_write_compressed(PullJob *j, void *p, size_t sz) {
328 int r;
329
330 assert(j);
331 assert(p);
332
333 if (sz <= 0)
334 return 0;
335
336 if (j->written_compressed + sz < j->written_compressed)
337 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
338
339 if (j->written_compressed + sz > j->compressed_max)
340 return log_error_errno(SYNTHETIC_ERRNO(EFBIG), "File overly large, refusing.");
341
342 if (j->content_length != UINT64_MAX &&
343 j->written_compressed + sz > j->content_length)
344 return log_error_errno(SYNTHETIC_ERRNO(EFBIG),
345 "Content length incorrect.");
346
347 if (j->checksum_context)
348 gcry_md_write(j->checksum_context, p, sz);
349
350 r = import_uncompress(&j->compress, p, sz, pull_job_write_uncompressed, j);
351 if (r < 0)
352 return r;
353
354 j->written_compressed += sz;
355
356 return 0;
357 }
358
359 static int pull_job_open_disk(PullJob *j) {
360 int r;
361
362 assert(j);
363
364 if (j->on_open_disk) {
365 r = j->on_open_disk(j);
366 if (r < 0)
367 return r;
368 }
369
370 if (j->disk_fd >= 0) {
371 if (fstat(j->disk_fd, &j->disk_stat) < 0)
372 return log_error_errno(errno, "Failed to stat disk file: %m");
373
374 if (j->offset != UINT64_MAX) {
375 if (lseek(j->disk_fd, j->offset, SEEK_SET) == (off_t) -1)
376 return log_error_errno(errno, "Failed to seek on file descriptor: %m");
377 }
378 }
379
380 if (j->calc_checksum) {
381 initialize_libgcrypt(false);
382
383 if (gcry_md_open(&j->checksum_context, GCRY_MD_SHA256, 0) != 0)
384 return log_error_errno(SYNTHETIC_ERRNO(EIO),
385 "Failed to initialize hash context.");
386 }
387
388 return 0;
389 }
390
391 static int pull_job_detect_compression(PullJob *j) {
392 _cleanup_free_ uint8_t *stub = NULL;
393 size_t stub_size;
394
395 int r;
396
397 assert(j);
398
399 r = import_uncompress_detect(&j->compress, j->payload, j->payload_size);
400 if (r < 0)
401 return log_error_errno(r, "Failed to initialize compressor: %m");
402 if (r == 0)
403 return 0;
404
405 log_debug("Stream is compressed: %s", import_compress_type_to_string(j->compress.type));
406
407 r = pull_job_open_disk(j);
408 if (r < 0)
409 return r;
410
411 /* Now, take the payload we read so far, and decompress it */
412 stub = j->payload;
413 stub_size = j->payload_size;
414
415 j->payload = NULL;
416 j->payload_size = 0;
417
418 j->state = PULL_JOB_RUNNING;
419
420 r = pull_job_write_compressed(j, stub, stub_size);
421 if (r < 0)
422 return r;
423
424 return 0;
425 }
426
427 static size_t pull_job_write_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
428 PullJob *j = userdata;
429 size_t sz = size * nmemb;
430 int r;
431
432 assert(contents);
433 assert(j);
434
435 switch (j->state) {
436
437 case PULL_JOB_ANALYZING:
438 /* Let's first check what it actually is */
439
440 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz)) {
441 r = log_oom();
442 goto fail;
443 }
444
445 memcpy(j->payload + j->payload_size, contents, sz);
446 j->payload_size += sz;
447
448 r = pull_job_detect_compression(j);
449 if (r < 0)
450 goto fail;
451
452 break;
453
454 case PULL_JOB_RUNNING:
455
456 r = pull_job_write_compressed(j, contents, sz);
457 if (r < 0)
458 goto fail;
459
460 break;
461
462 case PULL_JOB_DONE:
463 case PULL_JOB_FAILED:
464 r = -ESTALE;
465 goto fail;
466
467 default:
468 assert_not_reached();
469 }
470
471 return sz;
472
473 fail:
474 pull_job_finish(j, r);
475 return 0;
476 }
477
478 static int http_status_ok(CURLcode status) {
479 /* Consider all HTTP status code in the 2xx range as OK */
480 return status >= 200 && status <= 299;
481 }
482
483 static int http_status_etag_exists(CURLcode status) {
484 /* This one is special, it's triggered by our etag mgmt logic */
485 return status == 304;
486 }
487
488 static size_t pull_job_header_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
489 _cleanup_free_ char *length = NULL, *last_modified = NULL, *etag = NULL;
490 size_t sz = size * nmemb;
491 PullJob *j = userdata;
492 CURLcode code;
493 long status;
494 int r;
495
496 assert(contents);
497 assert(j);
498
499 if (IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED)) {
500 r = -ESTALE;
501 goto fail;
502 }
503
504 assert(j->state == PULL_JOB_ANALYZING);
505
506 code = curl_easy_getinfo(j->curl, CURLINFO_RESPONSE_CODE, &status);
507 if (code != CURLE_OK) {
508 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to retrieve response code: %s", curl_easy_strerror(code));
509 goto fail;
510 }
511
512 if (http_status_ok(status) || http_status_etag_exists(status)) {
513 /* Check Etag on OK and etag exists responses. */
514
515 r = curl_header_strdup(contents, sz, "ETag:", &etag);
516 if (r < 0) {
517 log_oom();
518 goto fail;
519 }
520 if (r > 0) {
521 free_and_replace(j->etag, etag);
522
523 if (strv_contains(j->old_etags, j->etag)) {
524 log_info("Image already downloaded. Skipping download. (%s)", j->etag);
525 j->etag_exists = true;
526 pull_job_finish(j, 0);
527 return sz;
528 }
529
530 return sz;
531 }
532 }
533
534 if (!http_status_ok(status)) /* Let's ignore the rest here, these requests are probably redirects and
535 * stuff where the headers aren't interesting to us */
536 return sz;
537
538 r = curl_header_strdup(contents, sz, "Content-Length:", &length);
539 if (r < 0) {
540 log_oom();
541 goto fail;
542 }
543 if (r > 0) {
544 (void) safe_atou64(length, &j->content_length);
545
546 if (j->content_length != UINT64_MAX) {
547 if (j->content_length > j->compressed_max) {
548 r = log_error_errno(SYNTHETIC_ERRNO(EFBIG), "Content too large.");
549 goto fail;
550 }
551
552 log_info("Downloading %s for %s.", FORMAT_BYTES(j->content_length), j->url);
553 }
554
555 return sz;
556 }
557
558 r = curl_header_strdup(contents, sz, "Last-Modified:", &last_modified);
559 if (r < 0) {
560 log_oom();
561 goto fail;
562 }
563 if (r > 0) {
564 (void) curl_parse_http_time(last_modified, &j->mtime);
565 return sz;
566 }
567
568 if (j->on_header) {
569 r = j->on_header(j, contents, sz);
570 if (r < 0)
571 goto fail;
572 }
573
574 return sz;
575
576 fail:
577 pull_job_finish(j, r);
578 return 0;
579 }
580
581 static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
582 PullJob *j = userdata;
583 unsigned percent;
584 usec_t n;
585
586 assert(j);
587
588 if (dltotal <= 0)
589 return 0;
590
591 percent = ((100 * dlnow) / dltotal);
592 n = now(CLOCK_MONOTONIC);
593
594 if (n > j->last_status_usec + USEC_PER_SEC &&
595 percent != j->progress_percent &&
596 dlnow < dltotal) {
597
598 if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) {
599 usec_t left, done;
600
601 done = n - j->start_usec;
602 left = (usec_t) (((double) done * (double) dltotal) / dlnow) - done;
603
604 log_info("Got %u%% of %s. %s left at %s/s.",
605 percent,
606 j->url,
607 FORMAT_TIMESPAN(left, USEC_PER_SEC),
608 FORMAT_BYTES((uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC))));
609 } else
610 log_info("Got %u%% of %s.", percent, j->url);
611
612 j->progress_percent = percent;
613 j->last_status_usec = n;
614
615 if (j->on_progress)
616 j->on_progress(j);
617 }
618
619 return 0;
620 }
621
622 int pull_job_new(
623 PullJob **ret,
624 const char *url,
625 CurlGlue *glue,
626 void *userdata) {
627
628 _cleanup_(pull_job_unrefp) PullJob *j = NULL;
629 _cleanup_free_ char *u = NULL;
630
631 assert(url);
632 assert(glue);
633 assert(ret);
634
635 u = strdup(url);
636 if (!u)
637 return -ENOMEM;
638
639 j = new(PullJob, 1);
640 if (!j)
641 return -ENOMEM;
642
643 *j = (PullJob) {
644 .state = PULL_JOB_INIT,
645 .disk_fd = -1,
646 .close_disk_fd = true,
647 .userdata = userdata,
648 .glue = glue,
649 .content_length = UINT64_MAX,
650 .start_usec = now(CLOCK_MONOTONIC),
651 .compressed_max = 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
652 .uncompressed_max = 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
653 .url = TAKE_PTR(u),
654 .offset = UINT64_MAX,
655 .sync = true,
656 };
657
658 *ret = TAKE_PTR(j);
659
660 return 0;
661 }
662
663 int pull_job_begin(PullJob *j) {
664 int r;
665
666 assert(j);
667
668 if (j->state != PULL_JOB_INIT)
669 return -EBUSY;
670
671 r = curl_glue_make(&j->curl, j->url, j);
672 if (r < 0)
673 return r;
674
675 if (!strv_isempty(j->old_etags)) {
676 _cleanup_free_ char *cc = NULL, *hdr = NULL;
677
678 cc = strv_join(j->old_etags, ", ");
679 if (!cc)
680 return -ENOMEM;
681
682 hdr = strjoin("If-None-Match: ", cc);
683 if (!hdr)
684 return -ENOMEM;
685
686 if (!j->request_header) {
687 j->request_header = curl_slist_new(hdr, NULL);
688 if (!j->request_header)
689 return -ENOMEM;
690 } else {
691 struct curl_slist *l;
692
693 l = curl_slist_append(j->request_header, hdr);
694 if (!l)
695 return -ENOMEM;
696
697 j->request_header = l;
698 }
699 }
700
701 if (j->request_header) {
702 if (curl_easy_setopt(j->curl, CURLOPT_HTTPHEADER, j->request_header) != CURLE_OK)
703 return -EIO;
704 }
705
706 if (curl_easy_setopt(j->curl, CURLOPT_WRITEFUNCTION, pull_job_write_callback) != CURLE_OK)
707 return -EIO;
708
709 if (curl_easy_setopt(j->curl, CURLOPT_WRITEDATA, j) != CURLE_OK)
710 return -EIO;
711
712 if (curl_easy_setopt(j->curl, CURLOPT_HEADERFUNCTION, pull_job_header_callback) != CURLE_OK)
713 return -EIO;
714
715 if (curl_easy_setopt(j->curl, CURLOPT_HEADERDATA, j) != CURLE_OK)
716 return -EIO;
717
718 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFOFUNCTION, pull_job_progress_callback) != CURLE_OK)
719 return -EIO;
720
721 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFODATA, j) != CURLE_OK)
722 return -EIO;
723
724 if (curl_easy_setopt(j->curl, CURLOPT_NOPROGRESS, 0) != CURLE_OK)
725 return -EIO;
726
727 r = curl_glue_add(j->glue, j->curl);
728 if (r < 0)
729 return r;
730
731 j->state = PULL_JOB_ANALYZING;
732
733 return 0;
734 }