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