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_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
));
140 if (IN_SET(protocol
, CURLPROTO_HTTP
, CURLPROTO_HTTPS
)) {
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
));
150 log_info("Image already downloaded. Skipping download.");
151 j
->etag_exists
= true;
154 } else if (status
>= 300) {
156 if (status
== 404 && j
->on_not_found
) {
157 _cleanup_free_
char *new_url
= NULL
;
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
);
164 if (r
> 0) { /* A new url to use */
167 r
= pull_job_restart(j
, new_url
);
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
));
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
);
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
);
192 if (j
->state
!= PULL_JOB_RUNNING
) {
193 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Premature connection termination.");
197 if (j
->content_length
!= UINT64_MAX
&&
198 j
->content_length
!= j
->written_compressed
) {
199 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Download truncated.");
203 if (j
->checksum_context
) {
206 k
= gcry_md_read(j
->checksum_context
, GCRY_MD_SHA256
);
208 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to get checksum.");
212 j
->checksum
= hexmem(k
, gcry_md_get_algo_dlen(GCRY_MD_SHA256
));
218 log_debug("SHA256 of %s is %s.", j
->url
, j
->checksum
);
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) */
224 if (j
->disk_fd
>= 0) {
226 if (S_ISREG(j
->disk_stat
.st_mode
)) {
228 if (j
->offset
== UINT64_MAX
) {
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");
240 (void) fsetxattr(j
->disk_fd
, "user.source_etag", j
->etag
, strlen(j
->etag
), 0);
242 (void) fsetxattr(j
->disk_fd
, "user.source_url", j
->url
, strlen(j
->url
), 0);
247 timespec_store(&ut
, j
->mtime
);
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");
252 r
= fd_setcrtime(j
->disk_fd
, j
->mtime
);
254 log_debug_errno(r
, "Failed to adjust crtime of created image, ignoring: %m");
259 r
= fsync_full(j
->disk_fd
);
261 log_error_errno(r
, "Failed to synchronize file to disk: %m");
266 } else if (S_ISBLK(j
->disk_stat
.st_mode
) && j
->sync
) {
268 if (fsync(j
->disk_fd
) < 0) {
269 r
= log_error_errno(errno
, "Failed to synchronize block device: %m");
278 pull_job_finish(j
, r
);
281 static int pull_job_write_uncompressed(const void *p
, size_t sz
, void *userdata
) {
282 PullJob
*j
= userdata
;
283 bool too_much
= false;
290 if (j
->written_uncompressed
> UINT64_MAX
- sz
)
291 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
293 if (j
->written_uncompressed
>= j
->uncompressed_max
) {
298 if (j
->written_uncompressed
+ sz
> j
->uncompressed_max
) {
300 sz
= j
->uncompressed_max
- j
->written_uncompressed
; /* since we have the data in memory
301 * already, we might as well write it to
305 if (j
->disk_fd
>= 0) {
307 if (S_ISREG(j
->disk_stat
.st_mode
)) {
310 n
= sparse_write(j
->disk_fd
, p
, sz
, 64);
312 return log_error_errno((int) n
, "Failed to write file: %m");
314 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write");
316 r
= loop_write(j
->disk_fd
, p
, sz
, false);
318 return log_error_errno(r
, "Failed to write file: %m");
322 if (j
->disk_fd
< 0 || j
->force_memory
) {
323 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
))
326 memcpy(j
->payload
+ j
->payload_size
, p
, sz
);
327 j
->payload_size
+= sz
;
330 j
->written_uncompressed
+= sz
;
334 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
339 static int pull_job_write_compressed(PullJob
*j
, void *p
, size_t sz
) {
348 if (j
->written_compressed
+ sz
< j
->written_compressed
)
349 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
351 if (j
->written_compressed
+ sz
> j
->compressed_max
)
352 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
354 if (j
->content_length
!= UINT64_MAX
&&
355 j
->written_compressed
+ sz
> j
->content_length
)
356 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
),
357 "Content length incorrect.");
359 if (j
->checksum_context
)
360 gcry_md_write(j
->checksum_context
, p
, sz
);
362 r
= import_uncompress(&j
->compress
, p
, sz
, pull_job_write_uncompressed
, j
);
366 j
->written_compressed
+= sz
;
371 static int pull_job_open_disk(PullJob
*j
) {
376 if (j
->on_open_disk
) {
377 r
= j
->on_open_disk(j
);
382 if (j
->disk_fd
>= 0) {
383 if (fstat(j
->disk_fd
, &j
->disk_stat
) < 0)
384 return log_error_errno(errno
, "Failed to stat disk file: %m");
386 if (j
->offset
!= UINT64_MAX
) {
387 if (lseek(j
->disk_fd
, j
->offset
, SEEK_SET
) == (off_t
) -1)
388 return log_error_errno(errno
, "Failed to seek on file descriptor: %m");
392 if (j
->calc_checksum
) {
393 initialize_libgcrypt(false);
395 if (gcry_md_open(&j
->checksum_context
, GCRY_MD_SHA256
, 0) != 0)
396 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
397 "Failed to initialize hash context.");
403 static int pull_job_detect_compression(PullJob
*j
) {
404 _cleanup_free_
uint8_t *stub
= NULL
;
411 r
= import_uncompress_detect(&j
->compress
, j
->payload
, j
->payload_size
);
413 return log_error_errno(r
, "Failed to initialize compressor: %m");
417 log_debug("Stream is compressed: %s", import_compress_type_to_string(j
->compress
.type
));
419 r
= pull_job_open_disk(j
);
423 /* Now, take the payload we read so far, and decompress it */
425 stub_size
= j
->payload_size
;
430 j
->state
= PULL_JOB_RUNNING
;
432 r
= pull_job_write_compressed(j
, stub
, stub_size
);
439 static size_t pull_job_write_callback(void *contents
, size_t size
, size_t nmemb
, void *userdata
) {
440 PullJob
*j
= userdata
;
441 size_t sz
= size
* nmemb
;
449 case PULL_JOB_ANALYZING
:
450 /* Let's first check what it actually is */
452 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
)) {
457 memcpy(j
->payload
+ j
->payload_size
, contents
, sz
);
458 j
->payload_size
+= sz
;
460 r
= pull_job_detect_compression(j
);
466 case PULL_JOB_RUNNING
:
468 r
= pull_job_write_compressed(j
, contents
, sz
);
475 case PULL_JOB_FAILED
:
480 assert_not_reached();
486 pull_job_finish(j
, r
);
490 static int http_status_ok(CURLcode status
) {
491 /* Consider all HTTP status code in the 2xx range as OK */
492 return status
>= 200 && status
<= 299;
495 static int http_status_etag_exists(CURLcode status
) {
496 /* This one is special, it's triggered by our etag mgmt logic */
497 return status
== 304;
500 static size_t pull_job_header_callback(void *contents
, size_t size
, size_t nmemb
, void *userdata
) {
501 _cleanup_free_
char *length
= NULL
, *last_modified
= NULL
, *etag
= NULL
;
502 size_t sz
= size
* nmemb
;
503 PullJob
*j
= userdata
;
511 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
)) {
516 assert(j
->state
== PULL_JOB_ANALYZING
);
518 code
= curl_easy_getinfo(j
->curl
, CURLINFO_RESPONSE_CODE
, &status
);
519 if (code
!= CURLE_OK
) {
520 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to retrieve response code: %s", curl_easy_strerror(code
));
524 if (http_status_ok(status
) || http_status_etag_exists(status
)) {
525 /* Check Etag on OK and etag exists responses. */
527 r
= curl_header_strdup(contents
, sz
, "ETag:", &etag
);
533 free_and_replace(j
->etag
, etag
);
535 if (strv_contains(j
->old_etags
, j
->etag
)) {
536 log_info("Image already downloaded. Skipping download. (%s)", j
->etag
);
537 j
->etag_exists
= true;
538 pull_job_finish(j
, 0);
546 if (!http_status_ok(status
)) /* Let's ignore the rest here, these requests are probably redirects and
547 * stuff where the headers aren't interesting to us */
550 r
= curl_header_strdup(contents
, sz
, "Content-Length:", &length
);
556 (void) safe_atou64(length
, &j
->content_length
);
558 if (j
->content_length
!= UINT64_MAX
) {
559 if (j
->content_length
> j
->compressed_max
) {
560 r
= log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "Content too large.");
564 log_info("Downloading %s for %s.", FORMAT_BYTES(j
->content_length
), j
->url
);
570 r
= curl_header_strdup(contents
, sz
, "Last-Modified:", &last_modified
);
576 (void) curl_parse_http_time(last_modified
, &j
->mtime
);
581 r
= j
->on_header(j
, contents
, sz
);
589 pull_job_finish(j
, r
);
593 static int pull_job_progress_callback(void *userdata
, curl_off_t dltotal
, curl_off_t dlnow
, curl_off_t ultotal
, curl_off_t ulnow
) {
594 PullJob
*j
= userdata
;
603 percent
= ((100 * dlnow
) / dltotal
);
604 n
= now(CLOCK_MONOTONIC
);
606 if (n
> j
->last_status_usec
+ USEC_PER_SEC
&&
607 percent
!= j
->progress_percent
&&
610 if (n
- j
->start_usec
> USEC_PER_SEC
&& dlnow
> 0) {
613 done
= n
- j
->start_usec
;
614 left
= (usec_t
) (((double) done
* (double) dltotal
) / dlnow
) - done
;
616 log_info("Got %u%% of %s. %s left at %s/s.",
619 FORMAT_TIMESPAN(left
, USEC_PER_SEC
),
620 FORMAT_BYTES((uint64_t) ((double) dlnow
/ ((double) done
/ (double) USEC_PER_SEC
))));
622 log_info("Got %u%% of %s.", percent
, j
->url
);
624 j
->progress_percent
= percent
;
625 j
->last_status_usec
= n
;
640 _cleanup_(pull_job_unrefp
) PullJob
*j
= NULL
;
641 _cleanup_free_
char *u
= NULL
;
656 .state
= PULL_JOB_INIT
,
658 .close_disk_fd
= true,
659 .userdata
= userdata
,
661 .content_length
= UINT64_MAX
,
662 .start_usec
= now(CLOCK_MONOTONIC
),
663 .compressed_max
= 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
664 .uncompressed_max
= 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
666 .offset
= UINT64_MAX
,
675 int pull_job_begin(PullJob
*j
) {
680 if (j
->state
!= PULL_JOB_INIT
)
683 r
= curl_glue_make(&j
->curl
, j
->url
, j
);
687 if (!strv_isempty(j
->old_etags
)) {
688 _cleanup_free_
char *cc
= NULL
, *hdr
= NULL
;
690 cc
= strv_join(j
->old_etags
, ", ");
694 hdr
= strjoin("If-None-Match: ", cc
);
698 if (!j
->request_header
) {
699 j
->request_header
= curl_slist_new(hdr
, NULL
);
700 if (!j
->request_header
)
703 struct curl_slist
*l
;
705 l
= curl_slist_append(j
->request_header
, hdr
);
709 j
->request_header
= l
;
713 if (j
->request_header
) {
714 if (curl_easy_setopt(j
->curl
, CURLOPT_HTTPHEADER
, j
->request_header
) != CURLE_OK
)
718 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEFUNCTION
, pull_job_write_callback
) != CURLE_OK
)
721 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEDATA
, j
) != CURLE_OK
)
724 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERFUNCTION
, pull_job_header_callback
) != CURLE_OK
)
727 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERDATA
, j
) != CURLE_OK
)
730 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFOFUNCTION
, pull_job_progress_callback
) != CURLE_OK
)
733 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFODATA
, j
) != CURLE_OK
)
736 if (curl_easy_setopt(j
->curl
, CURLOPT_NOPROGRESS
, 0) != CURLE_OK
)
739 r
= curl_glue_add(j
->glue
, j
->curl
);
743 j
->state
= PULL_JOB_ANALYZING
;