1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "alloc-util.h"
9 #include "format-util.h"
11 #include "gcrypt-util.h"
12 #include "hexdecoct.h"
13 #include "import-util.h"
15 #include "machine-pool.h"
16 #include "parse-util.h"
17 #include "pull-common.h"
19 #include "string-util.h"
21 #include "xattr-util.h"
23 void pull_job_close_disk_fd(PullJob
*j
) {
28 safe_close(j
->disk_fd
);
33 PullJob
* pull_job_unref(PullJob
*j
) {
37 pull_job_close_disk_fd(j
);
39 curl_glue_remove_and_free(j
->glue
, j
->curl
);
40 curl_slist_free_all(j
->request_header
);
42 import_compress_free(&j
->compress
);
44 if (j
->checksum_context
)
45 gcry_md_close(j
->checksum_context
);
49 strv_free(j
->old_etags
);
56 static void pull_job_finish(PullJob
*j
, int ret
) {
59 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
))
63 j
->state
= PULL_JOB_DONE
;
64 j
->progress_percent
= 100;
65 log_info("Download of %s complete.", j
->url
);
67 j
->state
= PULL_JOB_FAILED
;
75 static int pull_job_restart(PullJob
*j
, const char *new_url
) {
81 r
= free_and_strdup(&j
->url
, new_url
);
85 j
->state
= PULL_JOB_INIT
;
87 j
->payload
= mfree(j
->payload
);
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;
95 j
->checksum
= mfree(j
->checksum
);
97 curl_glue_remove_and_free(j
->glue
, j
->curl
);
100 curl_slist_free_all(j
->request_header
);
101 j
->request_header
= NULL
;
103 import_compress_free(&j
->compress
);
105 if (j
->checksum_context
) {
106 gcry_md_close(j
->checksum_context
);
107 j
->checksum_context
= NULL
;
110 r
= pull_job_begin(j
);
117 void pull_job_curl_on_finished(CurlGlue
*g
, CURL
*curl
, CURLcode result
) {
123 if (curl_easy_getinfo(curl
, CURLINFO_PRIVATE
, (char **)&j
) != CURLE_OK
)
126 if (!j
|| IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
))
129 if (result
!= CURLE_OK
) {
130 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Transfer failed: %s", curl_easy_strerror(result
));
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
));
138 } else if (status
== 304) {
139 log_info("Image already downloaded. Skipping download.");
140 j
->etag_exists
= true;
143 } else if (status
>= 300) {
145 if (status
== 404 && j
->on_not_found
) {
146 _cleanup_free_
char *new_url
= NULL
;
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
);
153 if (r
> 0) { /* A new url to use */
156 r
= pull_job_restart(j
, new_url
);
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
));
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
);
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
);
180 if (j
->state
!= PULL_JOB_RUNNING
) {
181 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Premature connection termination.");
185 if (j
->content_length
!= UINT64_MAX
&&
186 j
->content_length
!= j
->written_compressed
) {
187 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Download truncated.");
191 if (j
->checksum_context
) {
194 k
= gcry_md_read(j
->checksum_context
, GCRY_MD_SHA256
);
196 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to get checksum.");
200 j
->checksum
= hexmem(k
, gcry_md_get_algo_dlen(GCRY_MD_SHA256
));
206 log_debug("SHA256 of %s is %s.", j
->url
, j
->checksum
);
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) */
212 if (j
->disk_fd
>= 0) {
214 if (S_ISREG(j
->disk_stat
.st_mode
)) {
216 if (j
->offset
== UINT64_MAX
) {
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");
228 (void) fsetxattr(j
->disk_fd
, "user.source_etag", j
->etag
, strlen(j
->etag
), 0);
230 (void) fsetxattr(j
->disk_fd
, "user.source_url", j
->url
, strlen(j
->url
), 0);
235 timespec_store(&ut
, j
->mtime
);
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");
240 r
= fd_setcrtime(j
->disk_fd
, j
->mtime
);
242 log_debug_errno(r
, "Failed to adjust crtime of created image, ignoring: %m");
247 r
= fsync_full(j
->disk_fd
);
249 log_error_errno(r
, "Failed to synchronize file to disk: %m");
254 } else if (S_ISBLK(j
->disk_stat
.st_mode
) && j
->sync
) {
256 if (fsync(j
->disk_fd
) < 0) {
257 r
= log_error_errno(errno
, "Failed to synchronize block device: %m");
266 pull_job_finish(j
, r
);
269 static int pull_job_write_uncompressed(const void *p
, size_t sz
, void *userdata
) {
270 PullJob
*j
= userdata
;
271 bool too_much
= false;
278 if (j
->written_uncompressed
> UINT64_MAX
- sz
)
279 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
281 if (j
->written_uncompressed
>= j
->uncompressed_max
) {
286 if (j
->written_uncompressed
+ sz
> j
->uncompressed_max
) {
288 sz
= j
->uncompressed_max
- j
->written_uncompressed
; /* since we have the data in memory
289 * already, we might as well write it to
293 if (j
->disk_fd
>= 0) {
295 if (S_ISREG(j
->disk_stat
.st_mode
)) {
298 n
= sparse_write(j
->disk_fd
, p
, sz
, 64);
300 return log_error_errno((int) n
, "Failed to write file: %m");
302 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write");
304 r
= loop_write(j
->disk_fd
, p
, sz
, false);
306 return log_error_errno(r
, "Failed to write file: %m");
310 if (j
->disk_fd
< 0 || j
->force_memory
) {
311 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
))
314 memcpy(j
->payload
+ j
->payload_size
, p
, sz
);
315 j
->payload_size
+= sz
;
318 j
->written_uncompressed
+= sz
;
322 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
327 static int pull_job_write_compressed(PullJob
*j
, void *p
, size_t sz
) {
336 if (j
->written_compressed
+ sz
< j
->written_compressed
)
337 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
339 if (j
->written_compressed
+ sz
> j
->compressed_max
)
340 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
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.");
347 if (j
->checksum_context
)
348 gcry_md_write(j
->checksum_context
, p
, sz
);
350 r
= import_uncompress(&j
->compress
, p
, sz
, pull_job_write_uncompressed
, j
);
354 j
->written_compressed
+= sz
;
359 static int pull_job_open_disk(PullJob
*j
) {
364 if (j
->on_open_disk
) {
365 r
= j
->on_open_disk(j
);
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");
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");
380 if (j
->calc_checksum
) {
381 initialize_libgcrypt(false);
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.");
391 static int pull_job_detect_compression(PullJob
*j
) {
392 _cleanup_free_
uint8_t *stub
= NULL
;
399 r
= import_uncompress_detect(&j
->compress
, j
->payload
, j
->payload_size
);
401 return log_error_errno(r
, "Failed to initialize compressor: %m");
405 log_debug("Stream is compressed: %s", import_compress_type_to_string(j
->compress
.type
));
407 r
= pull_job_open_disk(j
);
411 /* Now, take the payload we read so far, and decompress it */
413 stub_size
= j
->payload_size
;
418 j
->state
= PULL_JOB_RUNNING
;
420 r
= pull_job_write_compressed(j
, stub
, stub_size
);
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
;
437 case PULL_JOB_ANALYZING
:
438 /* Let's first check what it actually is */
440 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
)) {
445 memcpy(j
->payload
+ j
->payload_size
, contents
, sz
);
446 j
->payload_size
+= sz
;
448 r
= pull_job_detect_compression(j
);
454 case PULL_JOB_RUNNING
:
456 r
= pull_job_write_compressed(j
, contents
, sz
);
463 case PULL_JOB_FAILED
:
468 assert_not_reached();
474 pull_job_finish(j
, r
);
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;
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;
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
;
499 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
)) {
504 assert(j
->state
== PULL_JOB_ANALYZING
);
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
));
512 if (http_status_ok(status
) || http_status_etag_exists(status
)) {
513 /* Check Etag on OK and etag exists responses. */
515 r
= curl_header_strdup(contents
, sz
, "ETag:", &etag
);
521 free_and_replace(j
->etag
, etag
);
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);
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 */
538 r
= curl_header_strdup(contents
, sz
, "Content-Length:", &length
);
544 (void) safe_atou64(length
, &j
->content_length
);
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.");
552 log_info("Downloading %s for %s.", FORMAT_BYTES(j
->content_length
), j
->url
);
558 r
= curl_header_strdup(contents
, sz
, "Last-Modified:", &last_modified
);
564 (void) curl_parse_http_time(last_modified
, &j
->mtime
);
569 r
= j
->on_header(j
, contents
, sz
);
577 pull_job_finish(j
, r
);
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
;
591 percent
= ((100 * dlnow
) / dltotal
);
592 n
= now(CLOCK_MONOTONIC
);
594 if (n
> j
->last_status_usec
+ USEC_PER_SEC
&&
595 percent
!= j
->progress_percent
&&
598 if (n
- j
->start_usec
> USEC_PER_SEC
&& dlnow
> 0) {
601 done
= n
- j
->start_usec
;
602 left
= (usec_t
) (((double) done
* (double) dltotal
) / dlnow
) - done
;
604 log_info("Got %u%% of %s. %s left at %s/s.",
607 FORMAT_TIMESPAN(left
, USEC_PER_SEC
),
608 FORMAT_BYTES((uint64_t) ((double) dlnow
/ ((double) done
/ (double) USEC_PER_SEC
))));
610 log_info("Got %u%% of %s.", percent
, j
->url
);
612 j
->progress_percent
= percent
;
613 j
->last_status_usec
= n
;
628 _cleanup_(pull_job_unrefp
) PullJob
*j
= NULL
;
629 _cleanup_free_
char *u
= NULL
;
644 .state
= PULL_JOB_INIT
,
646 .close_disk_fd
= true,
647 .userdata
= userdata
,
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 */
654 .offset
= UINT64_MAX
,
663 int pull_job_begin(PullJob
*j
) {
668 if (j
->state
!= PULL_JOB_INIT
)
671 r
= curl_glue_make(&j
->curl
, j
->url
, j
);
675 if (!strv_isempty(j
->old_etags
)) {
676 _cleanup_free_
char *cc
= NULL
, *hdr
= NULL
;
678 cc
= strv_join(j
->old_etags
, ", ");
682 hdr
= strjoin("If-None-Match: ", cc
);
686 if (!j
->request_header
) {
687 j
->request_header
= curl_slist_new(hdr
, NULL
);
688 if (!j
->request_header
)
691 struct curl_slist
*l
;
693 l
= curl_slist_append(j
->request_header
, hdr
);
697 j
->request_header
= l
;
701 if (j
->request_header
) {
702 if (curl_easy_setopt(j
->curl
, CURLOPT_HTTPHEADER
, j
->request_header
) != CURLE_OK
)
706 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEFUNCTION
, pull_job_write_callback
) != CURLE_OK
)
709 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEDATA
, j
) != CURLE_OK
)
712 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERFUNCTION
, pull_job_header_callback
) != CURLE_OK
)
715 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERDATA
, j
) != CURLE_OK
)
718 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFOFUNCTION
, pull_job_progress_callback
) != CURLE_OK
)
721 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFODATA
, j
) != CURLE_OK
)
724 if (curl_easy_setopt(j
->curl
, CURLOPT_NOPROGRESS
, 0) != CURLE_OK
)
727 r
= curl_glue_add(j
->glue
, j
->curl
);
731 j
->state
= PULL_JOB_ANALYZING
;