1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include "alloc-util.h"
9 #include "format-util.h"
10 #include "gcrypt-util.h"
11 #include "hexdecoct.h"
12 #include "import-util.h"
14 #include "machine-pool.h"
15 #include "parse-util.h"
16 #include "pull-common.h"
18 #include "string-util.h"
20 #include "sync-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
);
46 EVP_MD_CTX_free(j
->checksum_ctx
);
48 gcry_md_close(j
->checksum_ctx
);
53 strv_free(j
->old_etags
);
60 static void pull_job_finish(PullJob
*j
, int ret
) {
63 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
))
67 j
->state
= PULL_JOB_DONE
;
68 j
->progress_percent
= 100;
69 log_info("Download of %s complete.", j
->url
);
71 j
->state
= PULL_JOB_FAILED
;
79 static int pull_job_restart(PullJob
*j
, const char *new_url
) {
85 r
= free_and_strdup(&j
->url
, new_url
);
89 j
->state
= PULL_JOB_INIT
;
91 j
->payload
= mfree(j
->payload
);
93 j
->written_compressed
= 0;
94 j
->written_uncompressed
= 0;
95 j
->content_length
= UINT64_MAX
;
96 j
->etag
= mfree(j
->etag
);
97 j
->etag_exists
= false;
99 j
->checksum
= mfree(j
->checksum
);
101 curl_glue_remove_and_free(j
->glue
, j
->curl
);
104 curl_slist_free_all(j
->request_header
);
105 j
->request_header
= NULL
;
107 import_compress_free(&j
->compress
);
109 if (j
->checksum_ctx
) {
111 EVP_MD_CTX_free(j
->checksum_ctx
);
113 gcry_md_close(j
->checksum_ctx
);
115 j
->checksum_ctx
= NULL
;
118 r
= pull_job_begin(j
);
125 void pull_job_curl_on_finished(CurlGlue
*g
, CURL
*curl
, CURLcode result
) {
131 if (curl_easy_getinfo(curl
, CURLINFO_PRIVATE
, (char **)&j
) != CURLE_OK
)
134 if (!j
|| IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
))
137 if (result
!= CURLE_OK
) {
138 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Transfer failed: %s", curl_easy_strerror(result
));
142 code
= curl_easy_getinfo(curl
, CURLINFO_SCHEME
, &scheme
);
143 if (code
!= CURLE_OK
|| !scheme
) {
144 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to retrieve URL scheme.");
148 if (STRCASE_IN_SET(scheme
, "HTTP", "HTTPS")) {
151 code
= curl_easy_getinfo(curl
, CURLINFO_RESPONSE_CODE
, &status
);
152 if (code
!= CURLE_OK
) {
153 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to retrieve response code: %s", curl_easy_strerror(code
));
158 log_info("Image already downloaded. Skipping download.");
159 j
->etag_exists
= true;
162 } else if (status
>= 300) {
164 if (status
== 404 && j
->on_not_found
) {
165 _cleanup_free_
char *new_url
= NULL
;
167 /* This resource wasn't found, but the implementor wants to maybe let us know a new URL, query for it. */
168 r
= j
->on_not_found(j
, &new_url
);
172 if (r
> 0) { /* A new url to use */
175 r
= pull_job_restart(j
, new_url
);
179 code
= curl_easy_getinfo(j
->curl
, CURLINFO_RESPONSE_CODE
, &status
);
180 if (code
!= CURLE_OK
) {
181 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to retrieve response code: %s", curl_easy_strerror(code
));
191 status
== 404 ? SYNTHETIC_ERRNO(ENOMEDIUM
) : SYNTHETIC_ERRNO(EIO
), /* Make the most common error recognizable */
192 "HTTP request to %s failed with code %li.", j
->url
, status
);
194 } else if (status
< 200) {
195 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "HTTP request to %s finished with unexpected code %li.", j
->url
, status
);
200 if (j
->state
!= PULL_JOB_RUNNING
) {
201 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Premature connection termination.");
205 if (j
->content_length
!= UINT64_MAX
&&
206 j
->content_length
!= j
->written_compressed
) {
207 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Download truncated.");
211 if (j
->checksum_ctx
) {
212 unsigned checksum_len
;
214 uint8_t k
[EVP_MAX_MD_SIZE
];
216 r
= EVP_DigestFinal_ex(j
->checksum_ctx
, k
, &checksum_len
);
218 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to get checksum.");
221 assert(checksum_len
<= sizeof k
);
225 k
= gcry_md_read(j
->checksum_ctx
, GCRY_MD_SHA256
);
227 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to get checksum.");
231 checksum_len
= gcry_md_get_algo_dlen(GCRY_MD_SHA256
);
234 j
->checksum
= hexmem(k
, checksum_len
);
240 log_debug("SHA256 of %s is %s.", j
->url
, j
->checksum
);
243 /* Do a couple of finishing disk operations, but only if we are the sole owner of the file (i.e. no
244 * offset is specified, which indicates we only own the file partially) */
246 if (j
->disk_fd
>= 0) {
248 if (S_ISREG(j
->disk_stat
.st_mode
)) {
250 if (j
->offset
== UINT64_MAX
) {
252 if (j
->written_compressed
> 0) {
253 /* Make sure the file size is right, in case the file was sparse and
254 * we just moved to the last part. */
255 if (ftruncate(j
->disk_fd
, j
->written_uncompressed
) < 0) {
256 r
= log_error_errno(errno
, "Failed to truncate file: %m");
262 (void) fsetxattr(j
->disk_fd
, "user.source_etag", j
->etag
, strlen(j
->etag
), 0);
264 (void) fsetxattr(j
->disk_fd
, "user.source_url", j
->url
, strlen(j
->url
), 0);
269 timespec_store(&ut
, j
->mtime
);
271 if (futimens(j
->disk_fd
, (struct timespec
[]) { ut
, ut
}) < 0)
272 log_debug_errno(errno
, "Failed to adjust atime/mtime of created image, ignoring: %m");
274 r
= fd_setcrtime(j
->disk_fd
, j
->mtime
);
276 log_debug_errno(r
, "Failed to adjust crtime of created image, ignoring: %m");
281 r
= fsync_full(j
->disk_fd
);
283 log_error_errno(r
, "Failed to synchronize file to disk: %m");
288 } else if (S_ISBLK(j
->disk_stat
.st_mode
) && j
->sync
) {
290 if (fsync(j
->disk_fd
) < 0) {
291 r
= log_error_errno(errno
, "Failed to synchronize block device: %m");
297 log_info("Acquired %s.", FORMAT_BYTES(j
->written_uncompressed
));
302 pull_job_finish(j
, r
);
305 static int pull_job_write_uncompressed(const void *p
, size_t sz
, void *userdata
) {
306 PullJob
*j
= ASSERT_PTR(userdata
);
307 bool too_much
= false;
313 if (j
->written_uncompressed
> UINT64_MAX
- sz
)
314 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
316 if (j
->written_uncompressed
>= j
->uncompressed_max
) {
321 if (j
->written_uncompressed
+ sz
> j
->uncompressed_max
) {
323 sz
= j
->uncompressed_max
- j
->written_uncompressed
; /* since we have the data in memory
324 * already, we might as well write it to
328 if (j
->disk_fd
>= 0) {
330 if (S_ISREG(j
->disk_stat
.st_mode
) && j
->offset
== UINT64_MAX
) {
333 n
= sparse_write(j
->disk_fd
, p
, sz
, 64);
335 return log_error_errno((int) n
, "Failed to write file: %m");
337 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write");
339 r
= loop_write(j
->disk_fd
, p
, sz
);
341 return log_error_errno(r
, "Failed to write file: %m");
345 if (j
->disk_fd
< 0 || j
->force_memory
) {
346 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
))
349 memcpy(j
->payload
+ j
->payload_size
, p
, sz
);
350 j
->payload_size
+= sz
;
353 j
->written_uncompressed
+= sz
;
357 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
362 static int pull_job_write_compressed(PullJob
*j
, void *p
, size_t sz
) {
371 if (j
->written_compressed
+ sz
< j
->written_compressed
)
372 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
374 if (j
->written_compressed
+ sz
> j
->compressed_max
)
375 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
377 if (j
->content_length
!= UINT64_MAX
&&
378 j
->written_compressed
+ sz
> j
->content_length
)
379 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
),
380 "Content length incorrect.");
382 if (j
->checksum_ctx
) {
384 r
= EVP_DigestUpdate(j
->checksum_ctx
, p
, sz
);
386 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
387 "Could not hash chunk.");
389 gcry_md_write(j
->checksum_ctx
, p
, sz
);
393 r
= import_uncompress(&j
->compress
, p
, sz
, pull_job_write_uncompressed
, j
);
397 j
->written_compressed
+= sz
;
402 static int pull_job_open_disk(PullJob
*j
) {
407 if (j
->on_open_disk
) {
408 r
= j
->on_open_disk(j
);
413 if (j
->disk_fd
>= 0) {
414 if (fstat(j
->disk_fd
, &j
->disk_stat
) < 0)
415 return log_error_errno(errno
, "Failed to stat disk file: %m");
417 if (j
->offset
!= UINT64_MAX
) {
418 if (lseek(j
->disk_fd
, j
->offset
, SEEK_SET
) < 0)
419 return log_error_errno(errno
, "Failed to seek on file descriptor: %m");
423 if (j
->calc_checksum
) {
425 j
->checksum_ctx
= EVP_MD_CTX_new();
426 if (!j
->checksum_ctx
)
429 r
= EVP_DigestInit_ex(j
->checksum_ctx
, EVP_sha256(), NULL
);
431 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
432 "Failed to initialize hash context.");
434 initialize_libgcrypt(false);
436 if (gcry_md_open(&j
->checksum_ctx
, GCRY_MD_SHA256
, 0) != 0)
437 return log_error_errno(SYNTHETIC_ERRNO(EIO
),
438 "Failed to initialize hash context.");
445 static int pull_job_detect_compression(PullJob
*j
) {
446 _cleanup_free_
uint8_t *stub
= NULL
;
453 r
= import_uncompress_detect(&j
->compress
, j
->payload
, j
->payload_size
);
455 return log_error_errno(r
, "Failed to initialize compressor: %m");
459 log_debug("Stream is compressed: %s", import_compress_type_to_string(j
->compress
.type
));
461 r
= pull_job_open_disk(j
);
465 /* Now, take the payload we read so far, and decompress it */
467 stub_size
= j
->payload_size
;
472 j
->state
= PULL_JOB_RUNNING
;
474 r
= pull_job_write_compressed(j
, stub
, stub_size
);
481 static size_t pull_job_write_callback(void *contents
, size_t size
, size_t nmemb
, void *userdata
) {
482 PullJob
*j
= ASSERT_PTR(userdata
);
483 size_t sz
= size
* nmemb
;
490 case PULL_JOB_ANALYZING
:
491 /* Let's first check what it actually is */
493 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
)) {
498 memcpy(j
->payload
+ j
->payload_size
, contents
, sz
);
499 j
->payload_size
+= sz
;
501 r
= pull_job_detect_compression(j
);
507 case PULL_JOB_RUNNING
:
509 r
= pull_job_write_compressed(j
, contents
, sz
);
516 case PULL_JOB_FAILED
:
521 assert_not_reached();
527 pull_job_finish(j
, r
);
531 static int http_status_ok(CURLcode status
) {
532 /* Consider all HTTP status code in the 2xx range as OK */
533 return status
>= 200 && status
<= 299;
536 static int http_status_etag_exists(CURLcode status
) {
537 /* This one is special, it's triggered by our etag mgmt logic */
538 return status
== 304;
541 static size_t pull_job_header_callback(void *contents
, size_t size
, size_t nmemb
, void *userdata
) {
542 _cleanup_free_
char *length
= NULL
, *last_modified
= NULL
, *etag
= NULL
;
543 size_t sz
= size
* nmemb
;
544 PullJob
*j
= ASSERT_PTR(userdata
);
551 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
)) {
556 assert(j
->state
== PULL_JOB_ANALYZING
);
558 code
= curl_easy_getinfo(j
->curl
, CURLINFO_RESPONSE_CODE
, &status
);
559 if (code
!= CURLE_OK
) {
560 r
= log_error_errno(SYNTHETIC_ERRNO(EIO
), "Failed to retrieve response code: %s", curl_easy_strerror(code
));
564 if (http_status_ok(status
) || http_status_etag_exists(status
)) {
565 /* Check Etag on OK and etag exists responses. */
567 r
= curl_header_strdup(contents
, sz
, "ETag:", &etag
);
573 free_and_replace(j
->etag
, etag
);
575 if (strv_contains(j
->old_etags
, j
->etag
)) {
576 log_info("Image already downloaded. Skipping download. (%s)", j
->etag
);
577 j
->etag_exists
= true;
578 pull_job_finish(j
, 0);
586 if (!http_status_ok(status
)) /* Let's ignore the rest here, these requests are probably redirects and
587 * stuff where the headers aren't interesting to us */
590 r
= curl_header_strdup(contents
, sz
, "Content-Length:", &length
);
596 (void) safe_atou64(length
, &j
->content_length
);
598 if (j
->content_length
!= UINT64_MAX
) {
599 if (j
->content_length
> j
->compressed_max
) {
600 r
= log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "Content too large.");
604 log_info("Downloading %s for %s.", FORMAT_BYTES(j
->content_length
), j
->url
);
610 r
= curl_header_strdup(contents
, sz
, "Last-Modified:", &last_modified
);
616 (void) curl_parse_http_time(last_modified
, &j
->mtime
);
621 r
= j
->on_header(j
, contents
, sz
);
629 pull_job_finish(j
, r
);
633 static int pull_job_progress_callback(void *userdata
, curl_off_t dltotal
, curl_off_t dlnow
, curl_off_t ultotal
, curl_off_t ulnow
) {
634 PullJob
*j
= ASSERT_PTR(userdata
);
641 percent
= ((100 * dlnow
) / dltotal
);
642 n
= now(CLOCK_MONOTONIC
);
644 if (n
> j
->last_status_usec
+ USEC_PER_SEC
&&
645 percent
!= j
->progress_percent
&&
648 if (n
- j
->start_usec
> USEC_PER_SEC
&& dlnow
> 0) {
651 done
= n
- j
->start_usec
;
652 left
= (usec_t
) (((double) done
* (double) dltotal
) / dlnow
) - done
;
654 log_info("Got %u%% of %s. %s left at %s/s.",
657 FORMAT_TIMESPAN(left
, USEC_PER_SEC
),
658 FORMAT_BYTES((uint64_t) ((double) dlnow
/ ((double) done
/ (double) USEC_PER_SEC
))));
660 log_info("Got %u%% of %s.", percent
, j
->url
);
662 j
->progress_percent
= percent
;
663 j
->last_status_usec
= n
;
678 _cleanup_(pull_job_unrefp
) PullJob
*j
= NULL
;
679 _cleanup_free_
char *u
= NULL
;
694 .state
= PULL_JOB_INIT
,
696 .close_disk_fd
= true,
697 .userdata
= userdata
,
699 .content_length
= UINT64_MAX
,
700 .start_usec
= now(CLOCK_MONOTONIC
),
701 .compressed_max
= 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
702 .uncompressed_max
= 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
704 .offset
= UINT64_MAX
,
713 int pull_job_begin(PullJob
*j
) {
718 if (j
->state
!= PULL_JOB_INIT
)
721 r
= curl_glue_make(&j
->curl
, j
->url
, j
);
725 if (!strv_isempty(j
->old_etags
)) {
726 _cleanup_free_
char *cc
= NULL
, *hdr
= NULL
;
728 cc
= strv_join(j
->old_etags
, ", ");
732 hdr
= strjoin("If-None-Match: ", cc
);
736 if (!j
->request_header
) {
737 j
->request_header
= curl_slist_new(hdr
, NULL
);
738 if (!j
->request_header
)
741 struct curl_slist
*l
;
743 l
= curl_slist_append(j
->request_header
, hdr
);
747 j
->request_header
= l
;
751 if (j
->request_header
) {
752 if (curl_easy_setopt(j
->curl
, CURLOPT_HTTPHEADER
, j
->request_header
) != CURLE_OK
)
756 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEFUNCTION
, pull_job_write_callback
) != CURLE_OK
)
759 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEDATA
, j
) != CURLE_OK
)
762 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERFUNCTION
, pull_job_header_callback
) != CURLE_OK
)
765 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERDATA
, j
) != CURLE_OK
)
768 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFOFUNCTION
, pull_job_progress_callback
) != CURLE_OK
)
771 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFODATA
, j
) != CURLE_OK
)
774 if (curl_easy_setopt(j
->curl
, CURLOPT_NOPROGRESS
, 0) != CURLE_OK
)
777 r
= curl_glue_add(j
->glue
, j
->curl
);
781 j
->state
= PULL_JOB_ANALYZING
;