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
);
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");
275 log_info("Acquired %s.", FORMAT_BYTES(j
->written_uncompressed
));
280 pull_job_finish(j
, r
);
283 static int pull_job_write_uncompressed(const void *p
, size_t sz
, void *userdata
) {
284 PullJob
*j
= userdata
;
285 bool too_much
= false;
292 if (j
->written_uncompressed
> UINT64_MAX
- sz
)
293 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
295 if (j
->written_uncompressed
>= j
->uncompressed_max
) {
300 if (j
->written_uncompressed
+ sz
> j
->uncompressed_max
) {
302 sz
= j
->uncompressed_max
- j
->written_uncompressed
; /* since we have the data in memory
303 * already, we might as well write it to
307 if (j
->disk_fd
>= 0) {
309 if (S_ISREG(j
->disk_stat
.st_mode
) && j
->offset
== UINT64_MAX
) {
312 n
= sparse_write(j
->disk_fd
, p
, sz
, 64);
314 return log_error_errno((int) n
, "Failed to write file: %m");
316 return log_error_errno(SYNTHETIC_ERRNO(EIO
), "Short write");
318 r
= loop_write(j
->disk_fd
, p
, sz
, false);
320 return log_error_errno(r
, "Failed to write file: %m");
324 if (j
->disk_fd
< 0 || j
->force_memory
) {
325 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
))
328 memcpy(j
->payload
+ j
->payload_size
, p
, sz
);
329 j
->payload_size
+= sz
;
332 j
->written_uncompressed
+= sz
;
336 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
341 static int pull_job_write_compressed(PullJob
*j
, void *p
, size_t sz
) {
350 if (j
->written_compressed
+ sz
< j
->written_compressed
)
351 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW
), "File too large, overflow");
353 if (j
->written_compressed
+ sz
> j
->compressed_max
)
354 return log_error_errno(SYNTHETIC_ERRNO(EFBIG
), "File overly large, refusing.");
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.");
361 if (j
->checksum_context
)
362 gcry_md_write(j
->checksum_context
, p
, sz
);
364 r
= import_uncompress(&j
->compress
, p
, sz
, pull_job_write_uncompressed
, j
);
368 j
->written_compressed
+= sz
;
373 static int pull_job_open_disk(PullJob
*j
) {
378 if (j
->on_open_disk
) {
379 r
= j
->on_open_disk(j
);
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");
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");
394 if (j
->calc_checksum
) {
395 initialize_libgcrypt(false);
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.");
405 static int pull_job_detect_compression(PullJob
*j
) {
406 _cleanup_free_
uint8_t *stub
= NULL
;
413 r
= import_uncompress_detect(&j
->compress
, j
->payload
, j
->payload_size
);
415 return log_error_errno(r
, "Failed to initialize compressor: %m");
419 log_debug("Stream is compressed: %s", import_compress_type_to_string(j
->compress
.type
));
421 r
= pull_job_open_disk(j
);
425 /* Now, take the payload we read so far, and decompress it */
427 stub_size
= j
->payload_size
;
432 j
->state
= PULL_JOB_RUNNING
;
434 r
= pull_job_write_compressed(j
, stub
, stub_size
);
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
;
451 case PULL_JOB_ANALYZING
:
452 /* Let's first check what it actually is */
454 if (!GREEDY_REALLOC(j
->payload
, j
->payload_size
+ sz
)) {
459 memcpy(j
->payload
+ j
->payload_size
, contents
, sz
);
460 j
->payload_size
+= sz
;
462 r
= pull_job_detect_compression(j
);
468 case PULL_JOB_RUNNING
:
470 r
= pull_job_write_compressed(j
, contents
, sz
);
477 case PULL_JOB_FAILED
:
482 assert_not_reached();
488 pull_job_finish(j
, r
);
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;
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;
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
;
513 if (IN_SET(j
->state
, PULL_JOB_DONE
, PULL_JOB_FAILED
)) {
518 assert(j
->state
== PULL_JOB_ANALYZING
);
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
));
526 if (http_status_ok(status
) || http_status_etag_exists(status
)) {
527 /* Check Etag on OK and etag exists responses. */
529 r
= curl_header_strdup(contents
, sz
, "ETag:", &etag
);
535 free_and_replace(j
->etag
, etag
);
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);
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 */
552 r
= curl_header_strdup(contents
, sz
, "Content-Length:", &length
);
558 (void) safe_atou64(length
, &j
->content_length
);
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.");
566 log_info("Downloading %s for %s.", FORMAT_BYTES(j
->content_length
), j
->url
);
572 r
= curl_header_strdup(contents
, sz
, "Last-Modified:", &last_modified
);
578 (void) curl_parse_http_time(last_modified
, &j
->mtime
);
583 r
= j
->on_header(j
, contents
, sz
);
591 pull_job_finish(j
, r
);
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
;
605 percent
= ((100 * dlnow
) / dltotal
);
606 n
= now(CLOCK_MONOTONIC
);
608 if (n
> j
->last_status_usec
+ USEC_PER_SEC
&&
609 percent
!= j
->progress_percent
&&
612 if (n
- j
->start_usec
> USEC_PER_SEC
&& dlnow
> 0) {
615 done
= n
- j
->start_usec
;
616 left
= (usec_t
) (((double) done
* (double) dltotal
) / dlnow
) - done
;
618 log_info("Got %u%% of %s. %s left at %s/s.",
621 FORMAT_TIMESPAN(left
, USEC_PER_SEC
),
622 FORMAT_BYTES((uint64_t) ((double) dlnow
/ ((double) done
/ (double) USEC_PER_SEC
))));
624 log_info("Got %u%% of %s.", percent
, j
->url
);
626 j
->progress_percent
= percent
;
627 j
->last_status_usec
= n
;
642 _cleanup_(pull_job_unrefp
) PullJob
*j
= NULL
;
643 _cleanup_free_
char *u
= NULL
;
658 .state
= PULL_JOB_INIT
,
660 .close_disk_fd
= true,
661 .userdata
= userdata
,
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 */
668 .offset
= UINT64_MAX
,
677 int pull_job_begin(PullJob
*j
) {
682 if (j
->state
!= PULL_JOB_INIT
)
685 r
= curl_glue_make(&j
->curl
, j
->url
, j
);
689 if (!strv_isempty(j
->old_etags
)) {
690 _cleanup_free_
char *cc
= NULL
, *hdr
= NULL
;
692 cc
= strv_join(j
->old_etags
, ", ");
696 hdr
= strjoin("If-None-Match: ", cc
);
700 if (!j
->request_header
) {
701 j
->request_header
= curl_slist_new(hdr
, NULL
);
702 if (!j
->request_header
)
705 struct curl_slist
*l
;
707 l
= curl_slist_append(j
->request_header
, hdr
);
711 j
->request_header
= l
;
715 if (j
->request_header
) {
716 if (curl_easy_setopt(j
->curl
, CURLOPT_HTTPHEADER
, j
->request_header
) != CURLE_OK
)
720 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEFUNCTION
, pull_job_write_callback
) != CURLE_OK
)
723 if (curl_easy_setopt(j
->curl
, CURLOPT_WRITEDATA
, j
) != CURLE_OK
)
726 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERFUNCTION
, pull_job_header_callback
) != CURLE_OK
)
729 if (curl_easy_setopt(j
->curl
, CURLOPT_HEADERDATA
, j
) != CURLE_OK
)
732 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFOFUNCTION
, pull_job_progress_callback
) != CURLE_OK
)
735 if (curl_easy_setopt(j
->curl
, CURLOPT_XFERINFODATA
, j
) != CURLE_OK
)
738 if (curl_easy_setopt(j
->curl
, CURLOPT_NOPROGRESS
, 0) != CURLE_OK
)
741 r
= curl_glue_add(j
->glue
, j
->curl
);
745 j
->state
= PULL_JOB_ANALYZING
;