]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/import/pull-job.c
import: allow file:// in addition to HTTP(S)
[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 "fs-util.h"
11 #include "gcrypt-util.h"
12 #include "hexdecoct.h"
13 #include "import-util.h"
14 #include "io-util.h"
15 #include "machine-pool.h"
16 #include "parse-util.h"
17 #include "pull-common.h"
18 #include "pull-job.h"
19 #include "string-util.h"
20 #include "strv.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 r = 0;
276
277 finish:
278 pull_job_finish(j, r);
279 }
280
281 static int pull_job_write_uncompressed(const void *p, size_t sz, void *userdata) {
282 PullJob *j = userdata;
283 bool too_much = false;
284 int r;
285
286 assert(j);
287 assert(p);
288 assert(sz > 0);
289
290 if (j->written_uncompressed > UINT64_MAX - sz)
291 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
292
293 if (j->written_uncompressed >= j->uncompressed_max) {
294 too_much = true;
295 goto finish;
296 }
297
298 if (j->written_uncompressed + sz > j->uncompressed_max) {
299 too_much = true;
300 sz = j->uncompressed_max - j->written_uncompressed; /* since we have the data in memory
301 * already, we might as well write it to
302 * disk to the max */
303 }
304
305 if (j->disk_fd >= 0) {
306
307 if (S_ISREG(j->disk_stat.st_mode)) {
308 ssize_t n;
309
310 n = sparse_write(j->disk_fd, p, sz, 64);
311 if (n < 0)
312 return log_error_errno((int) n, "Failed to write file: %m");
313 if ((size_t) n < sz)
314 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write");
315 } else {
316 r = loop_write(j->disk_fd, p, sz, false);
317 if (r < 0)
318 return log_error_errno(r, "Failed to write file: %m");
319 }
320 }
321
322 if (j->disk_fd < 0 || j->force_memory) {
323 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz))
324 return log_oom();
325
326 memcpy(j->payload + j->payload_size, p, sz);
327 j->payload_size += sz;
328 }
329
330 j->written_uncompressed += sz;
331
332 finish:
333 if (too_much)
334 return log_error_errno(SYNTHETIC_ERRNO(EFBIG), "File overly large, refusing.");
335
336 return 0;
337 }
338
339 static int pull_job_write_compressed(PullJob *j, void *p, size_t sz) {
340 int r;
341
342 assert(j);
343 assert(p);
344
345 if (sz <= 0)
346 return 0;
347
348 if (j->written_compressed + sz < j->written_compressed)
349 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
350
351 if (j->written_compressed + sz > j->compressed_max)
352 return log_error_errno(SYNTHETIC_ERRNO(EFBIG), "File overly large, refusing.");
353
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.");
358
359 if (j->checksum_context)
360 gcry_md_write(j->checksum_context, p, sz);
361
362 r = import_uncompress(&j->compress, p, sz, pull_job_write_uncompressed, j);
363 if (r < 0)
364 return r;
365
366 j->written_compressed += sz;
367
368 return 0;
369 }
370
371 static int pull_job_open_disk(PullJob *j) {
372 int r;
373
374 assert(j);
375
376 if (j->on_open_disk) {
377 r = j->on_open_disk(j);
378 if (r < 0)
379 return r;
380 }
381
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");
385
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");
389 }
390 }
391
392 if (j->calc_checksum) {
393 initialize_libgcrypt(false);
394
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.");
398 }
399
400 return 0;
401 }
402
403 static int pull_job_detect_compression(PullJob *j) {
404 _cleanup_free_ uint8_t *stub = NULL;
405 size_t stub_size;
406
407 int r;
408
409 assert(j);
410
411 r = import_uncompress_detect(&j->compress, j->payload, j->payload_size);
412 if (r < 0)
413 return log_error_errno(r, "Failed to initialize compressor: %m");
414 if (r == 0)
415 return 0;
416
417 log_debug("Stream is compressed: %s", import_compress_type_to_string(j->compress.type));
418
419 r = pull_job_open_disk(j);
420 if (r < 0)
421 return r;
422
423 /* Now, take the payload we read so far, and decompress it */
424 stub = j->payload;
425 stub_size = j->payload_size;
426
427 j->payload = NULL;
428 j->payload_size = 0;
429
430 j->state = PULL_JOB_RUNNING;
431
432 r = pull_job_write_compressed(j, stub, stub_size);
433 if (r < 0)
434 return r;
435
436 return 0;
437 }
438
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;
442 int r;
443
444 assert(contents);
445 assert(j);
446
447 switch (j->state) {
448
449 case PULL_JOB_ANALYZING:
450 /* Let's first check what it actually is */
451
452 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz)) {
453 r = log_oom();
454 goto fail;
455 }
456
457 memcpy(j->payload + j->payload_size, contents, sz);
458 j->payload_size += sz;
459
460 r = pull_job_detect_compression(j);
461 if (r < 0)
462 goto fail;
463
464 break;
465
466 case PULL_JOB_RUNNING:
467
468 r = pull_job_write_compressed(j, contents, sz);
469 if (r < 0)
470 goto fail;
471
472 break;
473
474 case PULL_JOB_DONE:
475 case PULL_JOB_FAILED:
476 r = -ESTALE;
477 goto fail;
478
479 default:
480 assert_not_reached();
481 }
482
483 return sz;
484
485 fail:
486 pull_job_finish(j, r);
487 return 0;
488 }
489
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;
493 }
494
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;
498 }
499
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;
504 CURLcode code;
505 long status;
506 int r;
507
508 assert(contents);
509 assert(j);
510
511 if (IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED)) {
512 r = -ESTALE;
513 goto fail;
514 }
515
516 assert(j->state == PULL_JOB_ANALYZING);
517
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));
521 goto fail;
522 }
523
524 if (http_status_ok(status) || http_status_etag_exists(status)) {
525 /* Check Etag on OK and etag exists responses. */
526
527 r = curl_header_strdup(contents, sz, "ETag:", &etag);
528 if (r < 0) {
529 log_oom();
530 goto fail;
531 }
532 if (r > 0) {
533 free_and_replace(j->etag, etag);
534
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);
539 return sz;
540 }
541
542 return sz;
543 }
544 }
545
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 */
548 return sz;
549
550 r = curl_header_strdup(contents, sz, "Content-Length:", &length);
551 if (r < 0) {
552 log_oom();
553 goto fail;
554 }
555 if (r > 0) {
556 (void) safe_atou64(length, &j->content_length);
557
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.");
561 goto fail;
562 }
563
564 log_info("Downloading %s for %s.", FORMAT_BYTES(j->content_length), j->url);
565 }
566
567 return sz;
568 }
569
570 r = curl_header_strdup(contents, sz, "Last-Modified:", &last_modified);
571 if (r < 0) {
572 log_oom();
573 goto fail;
574 }
575 if (r > 0) {
576 (void) curl_parse_http_time(last_modified, &j->mtime);
577 return sz;
578 }
579
580 if (j->on_header) {
581 r = j->on_header(j, contents, sz);
582 if (r < 0)
583 goto fail;
584 }
585
586 return sz;
587
588 fail:
589 pull_job_finish(j, r);
590 return 0;
591 }
592
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;
595 unsigned percent;
596 usec_t n;
597
598 assert(j);
599
600 if (dltotal <= 0)
601 return 0;
602
603 percent = ((100 * dlnow) / dltotal);
604 n = now(CLOCK_MONOTONIC);
605
606 if (n > j->last_status_usec + USEC_PER_SEC &&
607 percent != j->progress_percent &&
608 dlnow < dltotal) {
609
610 if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) {
611 usec_t left, done;
612
613 done = n - j->start_usec;
614 left = (usec_t) (((double) done * (double) dltotal) / dlnow) - done;
615
616 log_info("Got %u%% of %s. %s left at %s/s.",
617 percent,
618 j->url,
619 FORMAT_TIMESPAN(left, USEC_PER_SEC),
620 FORMAT_BYTES((uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC))));
621 } else
622 log_info("Got %u%% of %s.", percent, j->url);
623
624 j->progress_percent = percent;
625 j->last_status_usec = n;
626
627 if (j->on_progress)
628 j->on_progress(j);
629 }
630
631 return 0;
632 }
633
634 int pull_job_new(
635 PullJob **ret,
636 const char *url,
637 CurlGlue *glue,
638 void *userdata) {
639
640 _cleanup_(pull_job_unrefp) PullJob *j = NULL;
641 _cleanup_free_ char *u = NULL;
642
643 assert(url);
644 assert(glue);
645 assert(ret);
646
647 u = strdup(url);
648 if (!u)
649 return -ENOMEM;
650
651 j = new(PullJob, 1);
652 if (!j)
653 return -ENOMEM;
654
655 *j = (PullJob) {
656 .state = PULL_JOB_INIT,
657 .disk_fd = -1,
658 .close_disk_fd = true,
659 .userdata = userdata,
660 .glue = glue,
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 */
665 .url = TAKE_PTR(u),
666 .offset = UINT64_MAX,
667 .sync = true,
668 };
669
670 *ret = TAKE_PTR(j);
671
672 return 0;
673 }
674
675 int pull_job_begin(PullJob *j) {
676 int r;
677
678 assert(j);
679
680 if (j->state != PULL_JOB_INIT)
681 return -EBUSY;
682
683 r = curl_glue_make(&j->curl, j->url, j);
684 if (r < 0)
685 return r;
686
687 if (!strv_isempty(j->old_etags)) {
688 _cleanup_free_ char *cc = NULL, *hdr = NULL;
689
690 cc = strv_join(j->old_etags, ", ");
691 if (!cc)
692 return -ENOMEM;
693
694 hdr = strjoin("If-None-Match: ", cc);
695 if (!hdr)
696 return -ENOMEM;
697
698 if (!j->request_header) {
699 j->request_header = curl_slist_new(hdr, NULL);
700 if (!j->request_header)
701 return -ENOMEM;
702 } else {
703 struct curl_slist *l;
704
705 l = curl_slist_append(j->request_header, hdr);
706 if (!l)
707 return -ENOMEM;
708
709 j->request_header = l;
710 }
711 }
712
713 if (j->request_header) {
714 if (curl_easy_setopt(j->curl, CURLOPT_HTTPHEADER, j->request_header) != CURLE_OK)
715 return -EIO;
716 }
717
718 if (curl_easy_setopt(j->curl, CURLOPT_WRITEFUNCTION, pull_job_write_callback) != CURLE_OK)
719 return -EIO;
720
721 if (curl_easy_setopt(j->curl, CURLOPT_WRITEDATA, j) != CURLE_OK)
722 return -EIO;
723
724 if (curl_easy_setopt(j->curl, CURLOPT_HEADERFUNCTION, pull_job_header_callback) != CURLE_OK)
725 return -EIO;
726
727 if (curl_easy_setopt(j->curl, CURLOPT_HEADERDATA, j) != CURLE_OK)
728 return -EIO;
729
730 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFOFUNCTION, pull_job_progress_callback) != CURLE_OK)
731 return -EIO;
732
733 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFODATA, j) != CURLE_OK)
734 return -EIO;
735
736 if (curl_easy_setopt(j->curl, CURLOPT_NOPROGRESS, 0) != CURLE_OK)
737 return -EIO;
738
739 r = curl_glue_add(j->glue, j->curl);
740 if (r < 0)
741 return r;
742
743 j->state = PULL_JOB_ANALYZING;
744
745 return 0;
746 }