]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/import/pull-job.c
import: use SYNTHETIC_ERRNO in one more place
[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 "gcrypt-util.h"
11 #include "hexdecoct.h"
12 #include "import-util.h"
13 #include "io-util.h"
14 #include "machine-pool.h"
15 #include "parse-util.h"
16 #include "pull-common.h"
17 #include "pull-job.h"
18 #include "string-util.h"
19 #include "strv.h"
20 #include "xattr-util.h"
21
22 PullJob* pull_job_unref(PullJob *j) {
23 if (!j)
24 return NULL;
25
26 curl_glue_remove_and_free(j->glue, j->curl);
27 curl_slist_free_all(j->request_header);
28
29 safe_close(j->disk_fd);
30
31 import_compress_free(&j->compress);
32
33 if (j->checksum_context)
34 gcry_md_close(j->checksum_context);
35
36 free(j->url);
37 free(j->etag);
38 strv_free(j->old_etags);
39 free(j->payload);
40 free(j->checksum);
41
42 return mfree(j);
43 }
44
45 static void pull_job_finish(PullJob *j, int ret) {
46 assert(j);
47
48 if (IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED))
49 return;
50
51 if (ret == 0) {
52 j->state = PULL_JOB_DONE;
53 j->progress_percent = 100;
54 log_info("Download of %s complete.", j->url);
55 } else {
56 j->state = PULL_JOB_FAILED;
57 j->error = ret;
58 }
59
60 if (j->on_finished)
61 j->on_finished(j);
62 }
63
64 static int pull_job_restart(PullJob *j, const char *new_url) {
65 int r;
66
67 assert(j);
68 assert(new_url);
69
70 r = free_and_strdup(&j->url, new_url);
71 if (r < 0)
72 return r;
73
74 j->state = PULL_JOB_INIT;
75 j->error = 0;
76 j->payload = mfree(j->payload);
77 j->payload_size = 0;
78 j->written_compressed = 0;
79 j->written_uncompressed = 0;
80 j->content_length = UINT64_MAX;
81 j->etag = mfree(j->etag);
82 j->etag_exists = false;
83 j->mtime = 0;
84 j->checksum = mfree(j->checksum);
85
86 curl_glue_remove_and_free(j->glue, j->curl);
87 j->curl = NULL;
88
89 curl_slist_free_all(j->request_header);
90 j->request_header = NULL;
91
92 import_compress_free(&j->compress);
93
94 if (j->checksum_context) {
95 gcry_md_close(j->checksum_context);
96 j->checksum_context = NULL;
97 }
98
99 r = pull_job_begin(j);
100 if (r < 0)
101 return r;
102
103 return 0;
104 }
105
106 void pull_job_curl_on_finished(CurlGlue *g, CURL *curl, CURLcode result) {
107 PullJob *j = NULL;
108 CURLcode code;
109 long status;
110 int r;
111
112 if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (char **)&j) != CURLE_OK)
113 return;
114
115 if (!j || IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED))
116 return;
117
118 if (result != CURLE_OK) {
119 log_error("Transfer failed: %s", curl_easy_strerror(result));
120 r = -EIO;
121 goto finish;
122 }
123
124 code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
125 if (code != CURLE_OK) {
126 log_error("Failed to retrieve response code: %s", curl_easy_strerror(code));
127 r = -EIO;
128 goto finish;
129 } else if (status == 304) {
130 log_info("Image already downloaded. Skipping download.");
131 j->etag_exists = true;
132 r = 0;
133 goto finish;
134 } else if (status >= 300) {
135
136 if (status == 404 && j->on_not_found) {
137 _cleanup_free_ char *new_url = NULL;
138
139 /* This resource wasn't found, but the implementor wants to maybe let us know a new URL, query for it. */
140 r = j->on_not_found(j, &new_url);
141 if (r < 0)
142 goto finish;
143
144 if (r > 0) { /* A new url to use */
145 assert(new_url);
146
147 r = pull_job_restart(j, new_url);
148 if (r < 0)
149 goto finish;
150
151 code = curl_easy_getinfo(j->curl, CURLINFO_RESPONSE_CODE, &status);
152 if (code != CURLE_OK) {
153 log_error("Failed to retrieve response code: %s", curl_easy_strerror(code));
154 r = -EIO;
155 goto finish;
156 }
157
158 if (status == 0)
159 return;
160 }
161 }
162
163 log_error("HTTP request to %s failed with code %li.", j->url, status);
164 r = -EIO;
165 goto finish;
166 } else if (status < 200) {
167 log_error("HTTP request to %s finished with unexpected code %li.", j->url, status);
168 r = -EIO;
169 goto finish;
170 }
171
172 if (j->state != PULL_JOB_RUNNING) {
173 log_error("Premature connection termination.");
174 r = -EIO;
175 goto finish;
176 }
177
178 if (j->content_length != UINT64_MAX &&
179 j->content_length != j->written_compressed) {
180 log_error("Download truncated.");
181 r = -EIO;
182 goto finish;
183 }
184
185 if (j->checksum_context) {
186 uint8_t *k;
187
188 k = gcry_md_read(j->checksum_context, GCRY_MD_SHA256);
189 if (!k) {
190 log_error("Failed to get checksum.");
191 r = -EIO;
192 goto finish;
193 }
194
195 j->checksum = hexmem(k, gcry_md_get_algo_dlen(GCRY_MD_SHA256));
196 if (!j->checksum) {
197 r = log_oom();
198 goto finish;
199 }
200
201 log_debug("SHA256 of %s is %s.", j->url, j->checksum);
202 }
203
204 if (j->disk_fd >= 0 && j->allow_sparse) {
205 /* Make sure the file size is right, in case the file was
206 * sparse and we just seeked for the last part */
207
208 if (ftruncate(j->disk_fd, j->written_uncompressed) < 0) {
209 r = log_error_errno(errno, "Failed to truncate file: %m");
210 goto finish;
211 }
212
213 if (j->etag)
214 (void) fsetxattr(j->disk_fd, "user.source_etag", j->etag, strlen(j->etag), 0);
215 if (j->url)
216 (void) fsetxattr(j->disk_fd, "user.source_url", j->url, strlen(j->url), 0);
217
218 if (j->mtime != 0) {
219 struct timespec ut[2];
220
221 timespec_store(&ut[0], j->mtime);
222 ut[1] = ut[0];
223 (void) futimens(j->disk_fd, ut);
224
225 (void) fd_setcrtime(j->disk_fd, j->mtime);
226 }
227 }
228
229 r = 0;
230
231 finish:
232 pull_job_finish(j, r);
233 }
234
235 static int pull_job_write_uncompressed(const void *p, size_t sz, void *userdata) {
236 PullJob *j = userdata;
237 ssize_t n;
238
239 assert(j);
240 assert(p);
241
242 if (sz <= 0)
243 return 0;
244
245 if (j->written_uncompressed + sz < j->written_uncompressed)
246 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW),
247 "File too large, overflow");
248
249 if (j->written_uncompressed + sz > j->uncompressed_max)
250 return log_error_errno(SYNTHETIC_ERRNO(EFBIG),
251 "File overly large, refusing");
252
253 if (j->disk_fd >= 0) {
254
255 if (j->allow_sparse)
256 n = sparse_write(j->disk_fd, p, sz, 64);
257 else {
258 n = write(j->disk_fd, p, sz);
259 if (n < 0)
260 n = -errno;
261 }
262 if (n < 0)
263 return log_error_errno((int) n, "Failed to write file: %m");
264 if ((size_t) n < sz)
265 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write");
266 } else {
267
268 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz))
269 return log_oom();
270
271 memcpy(j->payload + j->payload_size, p, sz);
272 j->payload_size += sz;
273 }
274
275 j->written_uncompressed += sz;
276
277 return 0;
278 }
279
280 static int pull_job_write_compressed(PullJob *j, void *p, size_t sz) {
281 int r;
282
283 assert(j);
284 assert(p);
285
286 if (sz <= 0)
287 return 0;
288
289 if (j->written_compressed + sz < j->written_compressed)
290 return log_error_errno(SYNTHETIC_ERRNO(EOVERFLOW), "File too large, overflow");
291
292 if (j->written_compressed + sz > j->compressed_max)
293 return log_error_errno(SYNTHETIC_ERRNO(EFBIG), "File overly large, refusing.");
294
295 if (j->content_length != UINT64_MAX &&
296 j->written_compressed + sz > j->content_length)
297 return log_error_errno(SYNTHETIC_ERRNO(EFBIG),
298 "Content length incorrect.");
299
300 if (j->checksum_context)
301 gcry_md_write(j->checksum_context, p, sz);
302
303 r = import_uncompress(&j->compress, p, sz, pull_job_write_uncompressed, j);
304 if (r < 0)
305 return r;
306
307 j->written_compressed += sz;
308
309 return 0;
310 }
311
312 static int pull_job_open_disk(PullJob *j) {
313 int r;
314
315 assert(j);
316
317 if (j->on_open_disk) {
318 r = j->on_open_disk(j);
319 if (r < 0)
320 return r;
321 }
322
323 if (j->disk_fd >= 0) {
324 /* Check if we can do sparse files */
325
326 if (lseek(j->disk_fd, SEEK_SET, 0) == 0)
327 j->allow_sparse = true;
328 else {
329 if (errno != ESPIPE)
330 return log_error_errno(errno, "Failed to seek on file descriptor: %m");
331
332 j->allow_sparse = false;
333 }
334 }
335
336 if (j->calc_checksum) {
337 initialize_libgcrypt(false);
338
339 if (gcry_md_open(&j->checksum_context, GCRY_MD_SHA256, 0) != 0)
340 return log_error_errno(SYNTHETIC_ERRNO(EIO),
341 "Failed to initialize hash context.");
342 }
343
344 return 0;
345 }
346
347 static int pull_job_detect_compression(PullJob *j) {
348 _cleanup_free_ uint8_t *stub = NULL;
349 size_t stub_size;
350
351 int r;
352
353 assert(j);
354
355 r = import_uncompress_detect(&j->compress, j->payload, j->payload_size);
356 if (r < 0)
357 return log_error_errno(r, "Failed to initialize compressor: %m");
358 if (r == 0)
359 return 0;
360
361 log_debug("Stream is compressed: %s", import_compress_type_to_string(j->compress.type));
362
363 r = pull_job_open_disk(j);
364 if (r < 0)
365 return r;
366
367 /* Now, take the payload we read so far, and decompress it */
368 stub = j->payload;
369 stub_size = j->payload_size;
370
371 j->payload = NULL;
372 j->payload_size = 0;
373
374 j->state = PULL_JOB_RUNNING;
375
376 r = pull_job_write_compressed(j, stub, stub_size);
377 if (r < 0)
378 return r;
379
380 return 0;
381 }
382
383 static size_t pull_job_write_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
384 PullJob *j = userdata;
385 size_t sz = size * nmemb;
386 int r;
387
388 assert(contents);
389 assert(j);
390
391 switch (j->state) {
392
393 case PULL_JOB_ANALYZING:
394 /* Let's first check what it actually is */
395
396 if (!GREEDY_REALLOC(j->payload, j->payload_size + sz)) {
397 r = log_oom();
398 goto fail;
399 }
400
401 memcpy(j->payload + j->payload_size, contents, sz);
402 j->payload_size += sz;
403
404 r = pull_job_detect_compression(j);
405 if (r < 0)
406 goto fail;
407
408 break;
409
410 case PULL_JOB_RUNNING:
411
412 r = pull_job_write_compressed(j, contents, sz);
413 if (r < 0)
414 goto fail;
415
416 break;
417
418 case PULL_JOB_DONE:
419 case PULL_JOB_FAILED:
420 r = -ESTALE;
421 goto fail;
422
423 default:
424 assert_not_reached("Impossible state.");
425 }
426
427 return sz;
428
429 fail:
430 pull_job_finish(j, r);
431 return 0;
432 }
433
434 static int http_status_ok(CURLcode status) {
435 /* Consider all HTTP status code in the 2xx range as OK */
436 return status >= 200 && status <= 299;
437 }
438
439 static int http_status_etag_exists(CURLcode status) {
440 /* This one is special, it's triggered by our etag mgmt logic */
441 return status == 304;
442 }
443
444 static size_t pull_job_header_callback(void *contents, size_t size, size_t nmemb, void *userdata) {
445 _cleanup_free_ char *length = NULL, *last_modified = NULL, *etag = NULL;
446 size_t sz = size * nmemb;
447 PullJob *j = userdata;
448 CURLcode code;
449 long status;
450 int r;
451
452 assert(contents);
453 assert(j);
454
455 if (IN_SET(j->state, PULL_JOB_DONE, PULL_JOB_FAILED)) {
456 r = -ESTALE;
457 goto fail;
458 }
459
460 assert(j->state == PULL_JOB_ANALYZING);
461
462 code = curl_easy_getinfo(j->curl, CURLINFO_RESPONSE_CODE, &status);
463 if (code != CURLE_OK) {
464 log_error("Failed to retrieve response code: %s", curl_easy_strerror(code));
465 r = -EIO;
466 goto fail;
467 }
468
469 if (http_status_ok(status) || http_status_etag_exists(status)) {
470 /* Check Etag on OK and etag exists responses. */
471
472 r = curl_header_strdup(contents, sz, "ETag:", &etag);
473 if (r < 0) {
474 log_oom();
475 goto fail;
476 }
477 if (r > 0) {
478 free_and_replace(j->etag, etag);
479
480 if (strv_contains(j->old_etags, j->etag)) {
481 log_info("Image already downloaded. Skipping download. (%s)", j->etag);
482 j->etag_exists = true;
483 pull_job_finish(j, 0);
484 return sz;
485 }
486
487 return sz;
488 }
489 }
490
491 if (!http_status_ok(status)) /* Let's ignore the rest here, these requests are probably redirects and
492 * stuff where the headers aren't interesting to us */
493 return sz;
494
495 r = curl_header_strdup(contents, sz, "Content-Length:", &length);
496 if (r < 0) {
497 log_oom();
498 goto fail;
499 }
500 if (r > 0) {
501 (void) safe_atou64(length, &j->content_length);
502
503 if (j->content_length != UINT64_MAX) {
504 if (j->content_length > j->compressed_max) {
505 r = log_error_errno(SYNTHETIC_ERRNO(EFBIG), "Content too large.");
506 goto fail;
507 }
508
509 log_info("Downloading %s for %s.", FORMAT_BYTES(j->content_length), j->url);
510 }
511
512 return sz;
513 }
514
515 r = curl_header_strdup(contents, sz, "Last-Modified:", &last_modified);
516 if (r < 0) {
517 log_oom();
518 goto fail;
519 }
520 if (r > 0) {
521 (void) curl_parse_http_time(last_modified, &j->mtime);
522 return sz;
523 }
524
525 if (j->on_header) {
526 r = j->on_header(j, contents, sz);
527 if (r < 0)
528 goto fail;
529 }
530
531 return sz;
532
533 fail:
534 pull_job_finish(j, r);
535 return 0;
536 }
537
538 static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
539 PullJob *j = userdata;
540 unsigned percent;
541 usec_t n;
542
543 assert(j);
544
545 if (dltotal <= 0)
546 return 0;
547
548 percent = ((100 * dlnow) / dltotal);
549 n = now(CLOCK_MONOTONIC);
550
551 if (n > j->last_status_usec + USEC_PER_SEC &&
552 percent != j->progress_percent &&
553 dlnow < dltotal) {
554
555 if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) {
556 usec_t left, done;
557
558 done = n - j->start_usec;
559 left = (usec_t) (((double) done * (double) dltotal) / dlnow) - done;
560
561 log_info("Got %u%% of %s. %s left at %s/s.",
562 percent,
563 j->url,
564 FORMAT_TIMESPAN(left, USEC_PER_SEC),
565 FORMAT_BYTES((uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC))));
566 } else
567 log_info("Got %u%% of %s.", percent, j->url);
568
569 j->progress_percent = percent;
570 j->last_status_usec = n;
571
572 if (j->on_progress)
573 j->on_progress(j);
574 }
575
576 return 0;
577 }
578
579 int pull_job_new(PullJob **ret, const char *url, CurlGlue *glue, void *userdata) {
580 _cleanup_(pull_job_unrefp) PullJob *j = NULL;
581 _cleanup_free_ char *u = NULL;
582
583 assert(url);
584 assert(glue);
585 assert(ret);
586
587 u = strdup(url);
588 if (!u)
589 return -ENOMEM;
590
591 j = new(PullJob, 1);
592 if (!j)
593 return -ENOMEM;
594
595 *j = (PullJob) {
596 .state = PULL_JOB_INIT,
597 .disk_fd = -1,
598 .userdata = userdata,
599 .glue = glue,
600 .content_length = UINT64_MAX,
601 .start_usec = now(CLOCK_MONOTONIC),
602 .compressed_max = 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
603 .uncompressed_max = 64LLU * 1024LLU * 1024LLU * 1024LLU, /* 64GB safety limit */
604 .url = TAKE_PTR(u),
605 };
606
607 *ret = TAKE_PTR(j);
608
609 return 0;
610 }
611
612 int pull_job_begin(PullJob *j) {
613 int r;
614
615 assert(j);
616
617 if (j->state != PULL_JOB_INIT)
618 return -EBUSY;
619
620 r = curl_glue_make(&j->curl, j->url, j);
621 if (r < 0)
622 return r;
623
624 if (!strv_isempty(j->old_etags)) {
625 _cleanup_free_ char *cc = NULL, *hdr = NULL;
626
627 cc = strv_join(j->old_etags, ", ");
628 if (!cc)
629 return -ENOMEM;
630
631 hdr = strjoin("If-None-Match: ", cc);
632 if (!hdr)
633 return -ENOMEM;
634
635 if (!j->request_header) {
636 j->request_header = curl_slist_new(hdr, NULL);
637 if (!j->request_header)
638 return -ENOMEM;
639 } else {
640 struct curl_slist *l;
641
642 l = curl_slist_append(j->request_header, hdr);
643 if (!l)
644 return -ENOMEM;
645
646 j->request_header = l;
647 }
648 }
649
650 if (j->request_header) {
651 if (curl_easy_setopt(j->curl, CURLOPT_HTTPHEADER, j->request_header) != CURLE_OK)
652 return -EIO;
653 }
654
655 if (curl_easy_setopt(j->curl, CURLOPT_WRITEFUNCTION, pull_job_write_callback) != CURLE_OK)
656 return -EIO;
657
658 if (curl_easy_setopt(j->curl, CURLOPT_WRITEDATA, j) != CURLE_OK)
659 return -EIO;
660
661 if (curl_easy_setopt(j->curl, CURLOPT_HEADERFUNCTION, pull_job_header_callback) != CURLE_OK)
662 return -EIO;
663
664 if (curl_easy_setopt(j->curl, CURLOPT_HEADERDATA, j) != CURLE_OK)
665 return -EIO;
666
667 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFOFUNCTION, pull_job_progress_callback) != CURLE_OK)
668 return -EIO;
669
670 if (curl_easy_setopt(j->curl, CURLOPT_XFERINFODATA, j) != CURLE_OK)
671 return -EIO;
672
673 if (curl_easy_setopt(j->curl, CURLOPT_NOPROGRESS, 0) != CURLE_OK)
674 return -EIO;
675
676 r = curl_glue_add(j->glue, j->curl);
677 if (r < 0)
678 return r;
679
680 j->state = PULL_JOB_ANALYZING;
681
682 return 0;
683 }