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