Debian Codegraph @

src/import/pull-oci.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "sd-event.h"
6 #include "sd-json.h"
7 #include "sd-varlink.h"
8
9 #include "alloc-util.h"
10 #include "architecture.h"
11 #include "btrfs-util.h"
12 #include "cleanup-util.h"
13 #include "curl-util.h"
14 #include "dissect-image.h"
15 #include "errno-util.h"
16 #include "escape.h"
17 #include "extract-word.h"
18 #include "fd-util.h"
19 #include "fs-util.h"
20 #include "hexdecoct.h"
21 #include "install-file.h"
22 #include "io-util.h"
23 #include "json-util.h"
24 #include "mkdir.h"
25 #include "oci-util.h"
26 #include "ordered-set.h"
27 #include "path-util.h"
28 #include "pidref.h"
29 #include "process-util.h"
30 #include "pull-common.h"
31 #include "pull-oci.h"
32 #include "rm-rf.h"
33 #include "set.h"
34 #include "sha256.h"
35 #include "signal-util.h"
36 #include "stat-util.h"
37 #include "string-util.h"
38 #include "strv.h"
39 #include "tmpfile-util.h"
40
41 #define LAYER_MAX 4096U
42 #define ACTIVE_LAYERS_MAX 5U
43
44 typedef enum OciProgress {
45 OCI_DOWNLOADING_MANIFEST,
46 OCI_DOWNLOADING_LAYERS,
47 OCI_FINALIZING,
48 OCI_COPYING,
49 } OciProgress;
50
51 typedef struct OciPull {
52 sd_event *event;
53 CurlGlue *glue;
54
55 ImportFlags flags;
56 char *image_root;
57
58 char *protocol;
59 char *repository;
60 char *image;
61 char *tag;
62
63 PullJob *manifest_job;
64 PullJob *bearer_token_job;
65 PullJob *config_job;
66 OrderedSet *queued_layer_jobs;
67 Set *active_layer_jobs, *done_layer_jobs;
68
69 OciPullFinished on_finished;
70 void *userdata;
71
72 bool refuse_index; /* if true, refuse processing an OCI index, because we already processed one */
73
74 char *bearer_token;
75
76 char *local;
77
78 struct iovec *layer_digests;
79 size_t n_layers;
80
81 struct iovec config;
82 int userns_fd;
83 } OciPull;
84
85 typedef struct OciLayerState {
86 OciPull *pull;
87
88 PidRef tar_pid;
89 char *temp_path;
90 char *final_path;
91
92 int tree_fd;
93 } OciLayerState;
94
95 static void oci_pull_job_on_finished_layer(PullJob *j);
96 static void oci_pull_job_on_finished_manifest(PullJob *j);
97 static void oci_pull_job_on_finished_config(PullJob *j);
98 static int oci_pull_work(OciPull *i);
99
100 static OciLayerState* oci_layer_state_free(OciLayerState *st) {
101 if (!st)
102 return NULL;
103
104 pidref_done_sigkill_wait(&st->tar_pid);
105
106 if (st->temp_path) {
107 import_remove_tree(
108 st->temp_path,
109 st->pull ? &st->pull->userns_fd : NULL,
110 st->pull ? st->pull->flags : 0);
111 free(st->temp_path);
112 }
113 free(st->final_path);
114
115 safe_close(st->tree_fd);
116
117 return mfree(st);
118 }
119
120 DEFINE_TRIVIAL_CLEANUP_FUNC(OciLayerState*, oci_layer_state_free);
121
122 OciPull* oci_pull_unref(OciPull *i) {
123 if (!i)
124 return NULL;
125
126 pull_job_unref(i->manifest_job);
127 pull_job_unref(i->bearer_token_job);
128 pull_job_unref(i->config_job);
129 ordered_set_free(i->queued_layer_jobs);
130 set_free(i->active_layer_jobs);
131 set_free(i->done_layer_jobs);
132
133 curl_glue_unref(i->glue);
134 sd_event_unref(i->event);
135
136 free(i->protocol);
137 free(i->repository);
138 free(i->image);
139 free(i->tag);
140
141 free(i->image_root);
142 free(i->local);
143 free(i->bearer_token);
144
145 iovec_done(&i->config);
146
147 iovec_done_many_and_free(i->layer_digests, i->n_layers);
148
149 safe_close(i->userns_fd);
150
151 return mfree(i);
152 }
153
154 int oci_pull_new(
155 OciPull **ret,
156 sd_event *event,
157 const char *image_root,
158 OciPullFinished on_finished,
159 void *userdata) {
160
161 int r;
162
163 assert(image_root);
164 assert(ret);
165
166 _cleanup_free_ char *root = strdup(image_root);
167 if (!root)
168 return -ENOMEM;
169
170 _cleanup_(sd_event_unrefp) sd_event *e = NULL;
171 if (event)
172 e = sd_event_ref(event);
173 else {
174 r = sd_event_default(&e);
175 if (r < 0)
176 return r;
177 }
178
179 _cleanup_(curl_glue_unrefp) CurlGlue *g = NULL;
180 r = curl_glue_new(&g, e);
181 if (r < 0)
182 return r;
183
184 _cleanup_(oci_pull_unrefp) OciPull *i = NULL;
185 i = new(OciPull, 1);
186 if (!i)
187 return -ENOMEM;
188
189 *i = (OciPull) {
190 .on_finished = on_finished,
191 .userdata = userdata,
192 .image_root = TAKE_PTR(root),
193 .event = TAKE_PTR(e),
194 .glue = TAKE_PTR(g),
195 .userns_fd = -EBADF,
196 };
197
198 *ret = TAKE_PTR(i);
199
200 return 0;
201 }
202
203 static int pull_job_payload_as_json_object(PullJob *j, sd_json_variant **ret) {
204 int r;
205
206 assert(j);
207 assert(ret);
208
209 /* The PullJob logic implicitly NUL terminates */
210 assert(((char*) j->payload.iov_base)[j->payload.iov_len] == 0);
211
212 if (memchr(j->payload.iov_base, 0, j->payload.iov_len))
213 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded NUL byte in JSON data, refusing.");
214
215 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
216 unsigned line = 0, column = 0;
217 r = sd_json_parse((char*) j->payload.iov_base, SD_JSON_PARSE_MUST_BE_OBJECT, &v, &line, &column);
218 if (r < 0)
219 return log_error_errno(r, "Failed to parse JSON at position %u:%u: %m", line, column);
220
221 if (DEBUG_LOGGING)
222 sd_json_variant_dump(v, SD_JSON_FORMAT_COLOR_AUTO|SD_JSON_FORMAT_PRETTY_AUTO, /* f= */ NULL, /* prefix= */ NULL);
223
224 *ret = TAKE_PTR(v);
225 return 0;
226 }
227
228 typedef struct OciIndexEntry {
229 char *media_type;
230 struct iovec digest;
231 uint64_t size;
232 char **url;
233 char *os;
234 char *architecture;
235 char *variant;
236 } OciIndexEntry;
237
238 static void oci_index_entry_done(OciIndexEntry *entry) {
239 assert(entry);
240
241 entry->media_type = mfree(entry->media_type);
242 iovec_done(&entry->digest);
243 entry->url = strv_free(entry->url);
244 entry->os = mfree(entry->os);
245 entry->architecture = mfree(entry->architecture);
246 entry->variant = mfree(entry->variant);
247 }
248
249 static bool oci_index_entry_match(OciIndexEntry *entry) {
250 assert(entry);
251
252 if (entry->os && !streq(entry->os, "linux"))
253 return false;
254
255 if (entry->architecture && go_arch_from_string(entry->architecture) != native_architecture())
256 return false;
257
258 return true;
259 }
260
261 static int json_dispatch_oci_digest(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
262 struct iovec *field = ASSERT_PTR(userdata);
263 int r;
264
265 assert(variant);
266
267 const char *s = NULL;
268 r = sd_json_dispatch_const_string(name, variant, flags, &s);
269 if (r < 0)
270 return r;
271
272 const char *h = startswith(s, "sha256:");
273 if (!h)
274 return json_log(variant, flags, SYNTHETIC_ERRNO(EOPNOTSUPP), "Unsupported hash algorithm used in '%s', refusing.", s);
275
276 _cleanup_(iovec_done) struct iovec d = {};
277 r = unhexmem(h, &d.iov_base, &d.iov_len);
278 if (r < 0)
279 return json_log(variant, flags, r, "Failed to decode hash '%s', refusing.", s);
280 if (d.iov_len != SHA256_DIGEST_SIZE)
281 return json_log(variant, flags, SYNTHETIC_ERRNO(EINVAL), "Hash '%s' has wrong size, refusing.", s);
282
283 iovec_done(field);
284 *field = TAKE_STRUCT(d);
285
286 return 0;
287 }
288
289 static int json_dispatch_oci_platform(const char *name, sd_json_variant *variant, sd_json_dispatch_flags_t flags, void *userdata) {
290 OciIndexEntry *entry = ASSERT_PTR(userdata);
291
292 assert(variant);
293
294 static const struct sd_json_dispatch_field table[] = {
295 { "os", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciIndexEntry, os), 0 },
296 { "architecture", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciIndexEntry, architecture), 0 },
297 { "variant", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciIndexEntry, variant), 0 },
298 {}
299 };
300
301 return sd_json_dispatch(variant, table, flags|SD_JSON_ALLOW_EXTENSIONS, entry);
302 }
303
304 static int json_dispatch_oci_index_entry(sd_json_variant *v, OciIndexEntry *entry) {
305 int r;
306
307 assert(v);
308 assert(entry);
309
310 static const struct sd_json_dispatch_field dispatch_table[] = {
311 { "mediaType", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciIndexEntry, media_type), SD_JSON_MANDATORY },
312 { "digest", SD_JSON_VARIANT_STRING, json_dispatch_oci_digest, offsetof(OciIndexEntry, digest), SD_JSON_MANDATORY },
313 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(OciIndexEntry, size), SD_JSON_MANDATORY },
314 { "urls", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(OciIndexEntry, url), 0 },
315 { "platform", SD_JSON_VARIANT_OBJECT, json_dispatch_oci_platform, 0, 0 },
316 {}
317 };
318
319 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, entry);
320 if (r < 0)
321 return r;
322
323 if (!streq_ptr(entry->media_type, "application/vnd.oci.image.manifest.v1+json")) {
324 json_log(v, SD_JSON_LOG, /* error= */ 0, "Unexpected manifest index entry with media type '%s', skipping.", entry->media_type);
325 return 0;
326 }
327
328 return 1;
329 }
330
331 static int oci_pull_redirect_manifest(OciPull *i, const OciIndexEntry *entry) {
332 int r;
333
334 assert(i);
335 assert(entry);
336
337 /* We acquired an index already and found the right manifest to select, hence let's acquire that one
338 * now */
339
340 _cleanup_free_ char *p = oci_digest_string(&entry->digest);
341 if (!p)
342 return -ENOMEM;
343
344 _cleanup_free_ char *url = NULL;
345 r = oci_make_manifest_url(i->protocol, i->repository, i->image, p, &url);
346 if (r < 0)
347 return r;
348
349 _cleanup_(pull_job_unrefp) PullJob *j = NULL;
350 r = pull_job_new(&j, url, i->glue, i);
351 if (r < 0)
352 return r;
353
354 r = pull_job_set_accept(
355 j,
356 STRV_MAKE("application/vnd.oci.image.manifest.v1+json"));
357 if (r < 0)
358 return r;
359
360 if (i->bearer_token) {
361 r = pull_job_set_bearer_token(j, i->bearer_token);
362 if (r < 0)
363 return r;
364 }
365
366 j->on_finished = oci_pull_job_on_finished_manifest;
367 j->calc_checksum = true;
368 if (!iovec_memdup(&entry->digest, &j->checksum))
369 return -ENOMEM;
370
371 j->description = strjoin("Image Manifest (", url, ")");
372 if (!j->description)
373 return -ENOMEM;
374
375 r = pull_job_begin(j);
376 if (r < 0)
377 return r;
378
379 free_and_replace_full(i->manifest_job, j, pull_job_unref);
380 return 0;
381 }
382
383 static int oci_pull_process_index(OciPull *i, PullJob *j) {
384 int r;
385
386 assert(i);
387 assert(j);
388
389 /* Processes a just downloaded OCI image index, as per:
390 *
391 * https://github.com/opencontainers/image-spec/blob/main/image-index.md */
392
393 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
394 r = pull_job_payload_as_json_object(j, &v);
395 if (r < 0)
396 return r;
397
398 struct {
399 unsigned schema_version;
400 const char *media_type;
401 sd_json_variant *manifests;
402 } index_data = {
403 .schema_version = UINT_MAX,
404 };
405
406 static const struct sd_json_dispatch_field dispatch_table[] = {
407 { "schemaVersion", SD_JSON_VARIANT_INTEGER, sd_json_dispatch_uint, voffsetof(index_data, schema_version), SD_JSON_MANDATORY },
408 { "mediaType", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(index_data, media_type), 0 },
409 { "manifests", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_variant_noref, voffsetof(index_data, manifests), SD_JSON_MANDATORY },
410 {}
411 };
412
413 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, &index_data);
414 if (r < 0)
415 return r;
416
417 if (index_data.schema_version != 2)
418 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "OCI image index has unsupported schema version %u, refusing.", index_data.schema_version);
419 if (index_data.media_type && !streq(index_data.media_type, "application/vnd.oci.image.index.v1+json"))
420 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "OCI image index has unexpected media type '%s', refusing.", index_data.media_type);
421
422 sd_json_variant *m;
423 JSON_VARIANT_ARRAY_FOREACH(m, index_data.manifests) {
424 _cleanup_(oci_index_entry_done) OciIndexEntry entry = {
425 .size = UINT64_MAX,
426 };
427
428 r = json_dispatch_oci_index_entry(m, &entry);
429 if (r < 0)
430 return r;
431 if (r == 0) /* skip? */
432 continue;
433
434 if (!oci_index_entry_match(&entry))
435 continue;
436
437 r = oci_pull_redirect_manifest(i, &entry);
438 if (r < 0)
439 return r;
440
441 return 1; /* continue */
442 }
443
444 return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No suitable OCI image manifest found for local system.");
445 }
446
447 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(pull_job_hash_ops, void, trivial_hash_func, trivial_compare_func, PullJob, pull_job_unref);
448
449 static int oci_pull_job_on_open_disk(PullJob *j) {
450 int r;
451
452 assert(j);
453
454 OciLayerState *st = ASSERT_PTR(j->userdata);
455 OciPull *i = st->pull;
456
457 if (!st->temp_path) {
458 r = tempfn_random_child(i->image_root, "oci", &st->temp_path);
459 if (r < 0)
460 return log_oom();
461 }
462
463 (void) mkdir_parents_label(st->temp_path, 0700);
464
465 if (FLAGS_SET(i->flags, IMPORT_FOREIGN_UID)) {
466 r = import_make_foreign_userns(&i->userns_fd);
467 if (r < 0)
468 return r;
469
470 _cleanup_(sd_varlink_unrefp) sd_varlink *mountfsd_link = NULL;
471 r = mountfsd_connect(&mountfsd_link);
472 if (r < 0)
473 return log_error_errno(r, "Failed to connect to mountfsd: %m");
474
475 _cleanup_close_ int directory_fd = -EBADF;
476 r = mountfsd_make_directory(
477 mountfsd_link,
478 st->temp_path,
479 MODE_INVALID,
480 /* flags= */ 0,
481 &directory_fd);
482 if (r < 0)
483 return log_error_errno(r, "Failed to make directory via mountfsd: %m");
484
485 r = mountfsd_mount_directory_fd(
486 mountfsd_link,
487 directory_fd,
488 i->userns_fd,
489 DISSECT_IMAGE_FOREIGN_UID,
490 &st->tree_fd);
491 if (r < 0)
492 return log_error_errno(r, "Failed to mount directory via mountfsd: %m");
493 } else {
494 if (i->flags & IMPORT_BTRFS_SUBVOL)
495 r = btrfs_subvol_make_fallback(AT_FDCWD, st->temp_path, 0755);
496 else
497 r = RET_NERRNO(mkdir(st->temp_path, 0755));
498 if (r < 0)
499 return log_error_errno(r, "Failed to create directory/subvolume %s: %m", st->temp_path);
500
501 if (r > 0 && (i->flags & IMPORT_BTRFS_QUOTA)) { /* actually btrfs subvol */
502 (void) import_assign_pool_quota_and_warn(i->image_root);
503 (void) import_assign_pool_quota_and_warn(st->temp_path);
504 }
505
506 st->tree_fd = open(st->temp_path, O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW);
507 if (st->tree_fd < 0)
508 return log_error_errno(errno, "Failed to open '%s': %m", st->temp_path);
509 }
510
511 j->disk_fd = import_fork_tar_x(st->tree_fd, i->userns_fd, &st->tar_pid);
512 if (j->disk_fd < 0)
513 return j->disk_fd;
514
515 return 0;
516 }
517
518 static void oci_layer_state_free_wrapper(void *p) {
519 oci_layer_state_free(p);
520 }
521
522 typedef struct OciManifestLayer {
523 char *media_type;
524 struct iovec digest;
525 uint64_t size;
526 } OciManifestLayer;
527
528 static void oci_manifest_layer_done(OciManifestLayer *layer) {
529 assert(layer);
530
531 layer->media_type = mfree(layer->media_type);
532 iovec_done(&layer->digest);
533 }
534
535 static int oci_layer_dirname_for_digest(struct iovec *iovec, char **ret) {
536 assert(iovec);
537 assert(ret);
538
539 _cleanup_free_ char *h = oci_digest_string(iovec);
540 if (!h)
541 return log_oom();
542
543 _cleanup_free_ char *fn = strjoin(".oci-", h);
544 if (!fn)
545 return log_oom();
546
547 *ret = TAKE_PTR(fn);
548 return 0;
549 }
550
551 static int oci_pull_queue_layer(OciPull *i, OciManifestLayer *layer) {
552 int r;
553
554 assert(i);
555 assert(layer);
556
557 _cleanup_free_ char *url = NULL;
558 r = oci_make_blob_url(i->protocol, i->repository, i->image, &layer->digest, &url);
559 if (r < 0)
560 return r;
561
562 _cleanup_free_ char *fn = NULL;
563 r = oci_layer_dirname_for_digest(&layer->digest, &fn);
564 if (r < 0)
565 return r;
566
567 _cleanup_free_ char *final_path = path_join(i->image_root, fn);
568 if (!final_path)
569 return log_oom();
570
571 r = is_dir(final_path, /* follow= */ true);
572 if (r < 0) {
573 if (r != -ENOENT)
574 return log_error_errno(r, "Failed to determine if directory '%s' exists: %m", final_path);
575 } else {
576 log_debug("Layer '%s' already exists, skipping download.", final_path);
577 return 0;
578 }
579
580 _cleanup_(oci_layer_state_freep) OciLayerState *st = new(OciLayerState, 1);
581 if (!st)
582 return -ENOMEM;
583
584 *st = (OciLayerState) {
585 .pull = i,
586 .tar_pid = PIDREF_NULL,
587 .tree_fd = -EBADF,
588 .final_path = TAKE_PTR(final_path),
589 };
590
591 /* Set up */
592 _cleanup_(pull_job_unrefp) PullJob *j = NULL;
593 r = pull_job_new(&j, url, i->glue, st);
594 if (r < 0)
595 return r;
596
597 j->free_userdata = oci_layer_state_free_wrapper;
598 TAKE_PTR(st);
599
600 r = pull_job_set_accept(j, STRV_MAKE(layer->media_type));
601 if (r < 0)
602 return r;
603
604 if (i->bearer_token) {
605 r = pull_job_set_bearer_token(j, i->bearer_token);
606 if (r < 0)
607 return r;
608 }
609
610 j->on_finished = oci_pull_job_on_finished_layer;
611 j->on_open_disk = oci_pull_job_on_open_disk;
612 j->expected_content_length = layer->size;
613 j->calc_checksum = true;
614 if (!iovec_memdup(&layer->digest, &j->expected_checksum))
615 return -ENOMEM;
616
617 r = ordered_set_ensure_put(&i->queued_layer_jobs, &pull_job_hash_ops, j);
618 if (r < 0)
619 return r;
620
621 TAKE_PTR(j);
622 return 0;
623 }
624
625 static int json_dispatch_oci_manifest_layer(sd_json_variant *v, OciManifestLayer *layer) {
626 int r;
627
628 assert(v);
629 assert(layer);
630
631 static const struct sd_json_dispatch_field dispatch_table[] = {
632 { "mediaType", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciManifestLayer, media_type), SD_JSON_MANDATORY },
633 { "digest", SD_JSON_VARIANT_STRING, json_dispatch_oci_digest, offsetof(OciManifestLayer, digest), SD_JSON_MANDATORY },
634 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(OciManifestLayer, size), SD_JSON_MANDATORY },
635 {}
636 };
637
638 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, layer);
639 if (r < 0)
640 return r;
641
642 if (!STR_IN_SET(layer->media_type,
643 "application/vnd.oci.image.layer.v1.tar",
644 "application/vnd.oci.image.layer.v1.tar+gzip",
645 "application/vnd.oci.image.layer.v1.tar+zstd")) {
646 json_log(v, SD_JSON_LOG, /* error= */ 0, "Unexpected manifest layer with media type '%s', skipping.", layer->media_type);
647 return 0;
648 }
649
650 return 1;
651 }
652
653 typedef struct OciManifestConfig {
654 char *media_type;
655 struct iovec digest;
656 uint64_t size;
657 struct iovec data;
658 } OciManifestConfig;
659
660 static void oci_manifest_config_done(OciManifestConfig *config) {
661 assert(config);
662
663 config->media_type = mfree(config->media_type);
664 iovec_done(&config->digest);
665 iovec_done(&config->data);
666 }
667
668 static int oci_pull_fetch_config(OciPull *i, OciManifestConfig *config) {
669 int r;
670
671 assert(i);
672 assert(config);
673
674 if (i->config_job)
675 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Two configs requested, refusing.");
676
677 _cleanup_free_ char *url = NULL;
678 r = oci_make_blob_url(i->protocol, i->repository, i->image, &config->digest, &url);
679 if (r < 0)
680 return r;
681
682 _cleanup_free_ char *h = oci_digest_string(&config->digest);
683 if (!h)
684 return log_oom();
685
686 r = pull_job_new(&i->config_job, url, i->glue, i);
687 if (r < 0)
688 return r;
689
690 r = pull_job_set_accept(i->config_job, STRV_MAKE(config->media_type));
691 if (r < 0)
692 return r;
693
694 if (i->bearer_token) {
695 r = pull_job_set_bearer_token(i->config_job, i->bearer_token);
696 if (r < 0)
697 return r;
698 }
699
700 i->config_job->on_finished = oci_pull_job_on_finished_config;
701 i->config_job->expected_content_length = config->size;
702 i->config_job->calc_checksum = true;
703 if (!iovec_memdup(&config->digest, &i->config_job->expected_checksum))
704 return log_oom();
705
706 i->config_job->description = strjoin("Image configuration (", url, ")");
707
708 r = pull_job_begin(i->config_job);
709 if (r < 0)
710 return r;
711
712 return 0;
713 }
714
715 static int json_dispatch_oci_manifest_config(sd_json_variant *v, OciManifestConfig *config) {
716 int r;
717
718 assert(v);
719 assert(config);
720
721 static const struct sd_json_dispatch_field dispatch_table[] = {
722 { "mediaType", SD_JSON_VARIANT_STRING, sd_json_dispatch_string, offsetof(OciManifestConfig, media_type), SD_JSON_MANDATORY },
723 { "digest", SD_JSON_VARIANT_STRING, json_dispatch_oci_digest, offsetof(OciManifestConfig, digest), SD_JSON_MANDATORY },
724 { "size", SD_JSON_VARIANT_UNSIGNED, sd_json_dispatch_uint64, offsetof(OciManifestConfig, size), SD_JSON_MANDATORY },
725 { "data", SD_JSON_VARIANT_STRING, json_dispatch_unbase64_iovec, offsetof(OciManifestConfig, data), 0 },
726 {}
727 };
728
729 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, config);
730 if (r < 0)
731 return r;
732
733 if (!STR_IN_SET(config->media_type, "application/vnd.oci.image.config.v1+json")) {
734 json_log(v, SD_JSON_LOG, /* error= */ 0, "Unexpected manifest config with media type '%s', skipping.", config->media_type);
735 return 0;
736 }
737
738 if (iovec_is_set(&config->data)) {
739 if (config->data.iov_len != config->size)
740 return json_log(v, SD_JSON_LOG, SYNTHETIC_ERRNO(EBADMSG), "Manifest config size mismatch.");
741
742 uint8_t h[SHA256_DIGEST_SIZE];
743 if (memcmp_nn(sha256_direct(config->data.iov_base, config->data.iov_len, h), SHA256_DIGEST_SIZE,
744 config->digest.iov_base, config->digest.iov_len) != 0)
745 return json_log(v, SD_JSON_LOG, SYNTHETIC_ERRNO(EBADMSG), "Manifest data size mismatch.");
746 }
747
748 return 1;
749 }
750
751 static int oci_pull_fetch_layers(OciPull *i) {
752 int r;
753
754 assert(i);
755
756 while (set_size(i->active_layer_jobs) < ACTIVE_LAYERS_MAX) {
757 _cleanup_(pull_job_unrefp) PullJob *j = ordered_set_steal_first(i->queued_layer_jobs);
758 if (!j)
759 return 0;
760
761 r = pull_job_begin(j);
762 if (r < 0)
763 return r;
764
765 r = set_ensure_put(&i->active_layer_jobs, &pull_job_hash_ops, j);
766 if (r < 0)
767 return r;
768
769 TAKE_PTR(j);
770 }
771
772 return 0;
773 }
774
775 static int oci_pull_process_manifest(OciPull *i, PullJob *j) {
776 int r;
777
778 assert(i);
779 assert(j);
780
781 /* Processes a just downloaded OCI image manifest, as per:
782 *
783 * https://github.com/opencontainers/image-spec/blob/main/manifest.md */
784
785 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
786 r = pull_job_payload_as_json_object(j, &v);
787 if (r < 0)
788 return r;
789
790 struct {
791 unsigned schema_version;
792 const char *media_type;
793 sd_json_variant *config;
794 sd_json_variant *layers;
795 } manifest_data = {
796 .schema_version = UINT_MAX,
797 };
798
799 static const struct sd_json_dispatch_field dispatch_table[] = {
800 { "schemaVersion", SD_JSON_VARIANT_INTEGER, sd_json_dispatch_uint, voffsetof(manifest_data, schema_version), SD_JSON_MANDATORY },
801 { "mediaType", SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string, voffsetof(manifest_data, media_type), 0 },
802 { "config", SD_JSON_VARIANT_OBJECT, sd_json_dispatch_variant_noref, voffsetof(manifest_data, config), 0 },
803 { "layers", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_variant_noref, voffsetof(manifest_data, layers), SD_JSON_MANDATORY },
804 {}
805 };
806
807 r = sd_json_dispatch(v, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, &manifest_data);
808 if (r < 0)
809 return r;
810
811 if (manifest_data.schema_version != 2)
812 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "OCI image manifest has unsupported schema version %u, refusing.", manifest_data.schema_version);
813 if (manifest_data.media_type && !streq(manifest_data.media_type, "application/vnd.oci.image.manifest.v1+json"))
814 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "OCI image manifest has unexpected media type '%s', refusing.", manifest_data.media_type);
815
816 if (manifest_data.config) {
817 _cleanup_(oci_manifest_config_done) OciManifestConfig config = {
818 .size = UINT64_MAX,
819 };
820
821 r = json_dispatch_oci_manifest_config(manifest_data.config, &config);
822 if (r < 0)
823 return r;
824
825 if (iovec_is_set(&config.data)) {
826 iovec_done(&i->config);
827 i->config = TAKE_STRUCT(config.data);
828 } else {
829 r = oci_pull_fetch_config(i, &config);
830 if (r < 0)
831 return r;
832 }
833 }
834
835 sd_json_variant *m;
836 JSON_VARIANT_ARRAY_FOREACH(m, manifest_data.layers) {
837 _cleanup_(oci_manifest_layer_done) OciManifestLayer layer = {
838 .size = UINT64_MAX,
839 };
840
841 r = json_dispatch_oci_manifest_layer(m, &layer);
842 if (r < 0)
843 return r;
844 if (r == 0) /* skip? */
845 continue;
846
847 if (i->n_layers >= LAYER_MAX)
848 return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "Too many layers in manifest (> %zu), refusing.", i->n_layers);
849
850 if (!GREEDY_REALLOC(i->layer_digests, i->n_layers + 1))
851 return log_oom();
852
853 if (!iovec_memdup(&layer.digest, i->layer_digests + i->n_layers))
854 return log_oom();
855
856 i->n_layers++;
857
858 r = oci_pull_queue_layer(i, &layer);
859 if (r < 0)
860 return r;
861 }
862
863 if (i->n_layers == 0)
864 return log_error_errno(SYNTHETIC_ERRNO(EPROTO), "Manifest has no recognized file system layers, refusing.");
865
866 assert(i->n_layers >= ordered_set_size(i->queued_layer_jobs));
867 size_t present_layers = i->n_layers - ordered_set_size(i->queued_layer_jobs);
868
869 log_info("Image %s/%s:%s has %zu layers, %zu already present.", i->repository, i->image, i->tag, i->n_layers, present_layers);
870
871 /* Assign nice descriptions that indicate which layer we are talking of here */
872 PullJob *q;
873 size_t k = 0;
874 ORDERED_SET_FOREACH(q, i->queued_layer_jobs) {
875 _cleanup_free_ char *d = NULL;
876
877 if (asprintf(&d, "Layer %zu/%zu (%s)", present_layers + k + 1, i->n_layers, q->url) < 0)
878 return log_oom();
879
880 free_and_replace(q->description, d);
881 k++;
882 }
883
884 return oci_pull_work(i);
885 }
886
887 static bool oci_pull_is_done(OciPull *i) {
888 assert(i);
889 assert(i->manifest_job);
890
891 if (!PULL_JOB_IS_COMPLETE(i->manifest_job) ||
892 (i->bearer_token_job && !PULL_JOB_IS_COMPLETE(i->bearer_token_job)) ||
893 (i->config_job && !PULL_JOB_IS_COMPLETE(i->config_job)))
894 return false;
895
896 return ordered_set_isempty(i->queued_layer_jobs) &&
897 set_isempty(i->active_layer_jobs);
898 }
899
900 typedef struct OciConfiguration {
901 char *user;
902 char **env;
903 char **entrypoint;
904 char **cmd;
905 char *working_dir;
906 int stop_signal;
907 } OciConfiguration;
908
909 static void oci_configuration_done(OciConfiguration *c) {
910 assert(c);
911
912 c->user = mfree(c->user);
913 c->env = strv_free(c->env);
914 c->entrypoint = strv_free(c->entrypoint);
915 c->cmd = strv_free(c->cmd);
916 c->working_dir = mfree(c->working_dir);
917 }
918
919 static int print_pair_escaped(FILE *f, const char *field, const char *value) {
920 assert(f);
921 assert(field);
922 assert(value);
923
924 _cleanup_free_ char *escaped = cescape(value);
925 if (!escaped)
926 return log_oom();
927
928 fputs(field, f);
929 fputc('=', f);
930 fputs(escaped, f);
931 fputc('\n', f);
932
933 return 0;
934 }
935
936 static int dispatch_unsupported(const char *name, sd_json_variant *v, sd_json_dispatch_flags_t flags, void *userdata) {
937 assert(v);
938 json_log(v, flags|SD_JSON_WARNING, /* error= */ 0, "OCI image specification field '%s' cannot be be translated to any corresponding .nspawn setting, skipping.", name);
939 return 0;
940 }
941
942 static int oci_pull_save_nspawn_settings(OciPull *i) {
943 int r;
944
945 assert(i);
946 assert(iovec_is_set(&i->config));
947
948 /* This translates the image spec "configuration" object into native .nspawn files for consumption by
949 * systemd-nspawn. It's vaguely related to
950 * https://github.com/opencontainers/image-spec/blob/v1.1.1/conversion.md except of course we don't
951 * translate to the OCI runtime spec here but rather to .nspawn knobs. */
952
953 /* The PullJob logic implicitly NUL terminates */
954 assert(((char*) i->config.iov_base)[i->config.iov_len] == 0);
955
956 if (memchr(i->config.iov_base, 0, i->config.iov_len))
957 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Embedded NUL by in JSON config data, refusing.");
958
959 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
960 unsigned line = 0, column = 0;
961 r = sd_json_parse((char*) i->config.iov_base, SD_JSON_PARSE_MUST_BE_OBJECT, &v, &line, &column);
962 if (r < 0)
963 return log_error_errno(r, "Failed to parse JSON config data at position %u:%u: %m", line, column);
964
965 sd_json_variant *config = sd_json_variant_by_key(v, "config");
966
967 _cleanup_(oci_configuration_done) OciConfiguration config_data = {
968 .stop_signal = SIGTERM,
969 };
970 static const struct sd_json_dispatch_field dispatch_table[] = {
971 { "User", SD_JSON_VARIANT_STRING, json_dispatch_user_group_name, offsetof(OciConfiguration, user), 0 },
972 { "Env", SD_JSON_VARIANT_ARRAY, json_dispatch_strv_environment, offsetof(OciConfiguration, env), 0 },
973 { "Entrypoint", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(OciConfiguration, entrypoint), 0 },
974 { "Cmd", SD_JSON_VARIANT_ARRAY, sd_json_dispatch_strv, offsetof(OciConfiguration, cmd), 0 },
975 { "WorkingDir", SD_JSON_VARIANT_STRING, json_dispatch_path, offsetof(OciConfiguration, working_dir), 0 },
976 { "StopSignal", SD_JSON_VARIANT_STRING, sd_json_dispatch_signal, offsetof(OciConfiguration, stop_signal), 0 },
977
978 /* Currently unsupported fields that the OCI image spec defines but we cannot convert into
979 * .nspawn settings just yet. */
980 { "ExposedPorts", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
981 { "Volumes", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
982 { "Labels", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
983 { "ArgsEscaped", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
984 { "Memory", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
985 { "MemorySwap", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
986 { "CpuShares", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
987 { "Healthcheck", _SD_JSON_VARIANT_TYPE_INVALID, dispatch_unsupported, 0, 0 },
988 {}
989 };
990
991 r = sd_json_dispatch(config, dispatch_table, SD_JSON_ALLOW_EXTENSIONS|SD_JSON_LOG, &config_data);
992 if (r < 0)
993 return r;
994
995 _cleanup_free_ char *fn = strjoin(i->local, ".nspawn");
996 if (!fn)
997 return log_oom();
998
999 _cleanup_free_ char *j = path_join(i->image_root, fn);
1000 if (!j)
1001 return log_oom();
1002
1003 _cleanup_fclose_ FILE *f = NULL;
1004 _cleanup_(unlink_and_freep) char *tmpfile = NULL;
1005 r = fopen_tmpfile_linkable(j, O_WRONLY|O_CLOEXEC, &tmpfile, &f);
1006 if (r < 0)
1007 return log_error_errno(r, "Failed to create '%s': %m", j);
1008
1009 fprintf(f,
1010 "# Generated from OCI configuration object\n"
1011 "[Exec]\n"
1012 "Boot=no\n"
1013 "KillSignal=%s\n",
1014 signal_to_string(config_data.stop_signal));
1015
1016 if (config_data.user && !STR_IN_SET(config_data.user, "root", "0")) {
1017 r = print_pair_escaped(f, "User", config_data.user);
1018 if (r < 0)
1019 return r;
1020 }
1021
1022 if (config_data.working_dir && !path_equal(config_data.working_dir, "/")) {
1023 r = print_pair_escaped(f, "WorkingDirectory", config_data.working_dir);
1024 if (r < 0)
1025 return r;
1026 }
1027
1028 STRV_FOREACH(e, config_data.env) {
1029 r = print_pair_escaped(f, "Environment", *e);
1030 if (r < 0)
1031 return r;
1032 }
1033
1034 _cleanup_strv_free_ char **cmdline = strv_copy(config_data.entrypoint);
1035 if (!cmdline)
1036 return log_oom();
1037 if (strv_extend_strv(&cmdline, config_data.cmd, /* filter_duplicates= */ false) < 0)
1038 return log_oom();
1039
1040 if (!strv_isempty(cmdline)) {
1041 _cleanup_free_ char *ej = NULL;
1042
1043 STRV_FOREACH(z, cmdline) {
1044 _cleanup_free_ char *q = NULL;
1045 const char *a;
1046
1047 if (isempty(*z))
1048 a = "\"\"";
1049 else if (!in_charset(*z, ALPHANUMERICAL "=+-_/;.:,;")) {
1050 _cleanup_free_ char *e = shell_escape(*z, "\"");
1051 if (!e)
1052 return log_oom();
1053
1054 q = strjoin("\"", e, "\"");
1055 if (!q)
1056 return log_oom();
1057
1058 a = q;
1059 } else
1060 a = *z;
1061
1062 if (!strextend_with_separator(&ej, " ", a))
1063 return log_oom();
1064 }
1065
1066 fprintf(f, "Parameters=%s\n", ej);
1067 }
1068
1069 r = flink_tmpfile(f, tmpfile, j, LINK_TMPFILE_REPLACE);
1070 if (r < 0)
1071 return log_error_errno(r, "Failed to move '%s' into place: %m", j);
1072
1073 log_info("systemd-nspawn settings file written to '%s'.", j);
1074 return 0;
1075 }
1076
1077 static int oci_pull_save_oci_config(OciPull *i) {
1078 int r;
1079
1080 assert(i);
1081 assert(iovec_is_set(&i->config));
1082
1083 _cleanup_free_ char *fn = strjoin(i->local, ".oci-config");
1084 if (!fn)
1085 return log_oom();
1086
1087 _cleanup_free_ char *j = path_join(i->image_root, fn);
1088 if (!j)
1089 return log_oom();
1090
1091 _cleanup_close_ int fd = -EBADF;
1092 _cleanup_(unlink_and_freep) char *tmpfile = NULL;
1093 fd = open_tmpfile_linkable(j, O_WRONLY|O_CLOEXEC, &tmpfile);
1094 if (fd < 0)
1095 return log_error_errno(fd, "Failed to create '%s': %m", j);
1096
1097 r = loop_write(fd, i->config.iov_base, i->config.iov_len);
1098 if (r < 0)
1099 return log_error_errno(r, "Failed to write '%s': %m", j);
1100
1101 r = link_tmpfile(fd, tmpfile, j, LINK_TMPFILE_REPLACE);
1102 if (r < 0)
1103 return log_error_errno(r, "Failed to move '%s' into place: %m", j);
1104
1105 log_info("OCI config written to '%s'.", j);
1106 return 0;
1107 }
1108
1109 static int oci_pull_save_mstack(OciPull *i) {
1110 int r;
1111
1112 assert(i);
1113
1114 _cleanup_free_ char *dn = strjoin(i->local, ".mstack");
1115 if (!dn)
1116 return log_oom();
1117
1118 _cleanup_free_ char *j = path_join(i->image_root, dn);
1119 if (!j)
1120 return log_oom();
1121
1122 log_notice("Creating '%s'", j);
1123
1124 _cleanup_free_ char *_jt = NULL;
1125 r = tempfn_random(j, "oci", &_jt);
1126 if (r < 0)
1127 return log_oom();
1128
1129 _cleanup_close_ int dir_fd = xopenat(AT_FDCWD, _jt, O_DIRECTORY|O_CREAT|O_CLOEXEC);
1130 if (dir_fd < 0)
1131 return log_error_errno(dir_fd, "Failed to create '%s': %m", j);
1132
1133 _cleanup_(rm_rf_physical_and_freep) char *jt = TAKE_PTR(_jt);
1134 for (size_t k = 0; k < i->n_layers; k++) {
1135 _cleanup_free_ char *sl = NULL;
1136 if (asprintf(&sl, "layer@%zu", k) < 0)
1137 return log_oom();
1138
1139 _cleanup_free_ char *ldn = NULL;
1140 if (oci_layer_dirname_for_digest(i->layer_digests + k, &ldn) < 0)
1141 return log_oom();
1142
1143 _cleanup_free_ char *with_dot_dot = path_join("..", ldn);
1144 if (!with_dot_dot)
1145 return log_oom();
1146
1147 if (symlinkat(with_dot_dot, dir_fd, sl) < 0)
1148 return log_error_errno(errno, "Failed to make symlink for layer '%s': %m", sl);
1149 }
1150
1151 if (!FLAGS_SET(i->flags, IMPORT_READ_ONLY)) {
1152 /* If this shall be a mutable container let's also create an "rw" layer, that will become
1153 * the upper layer in the overlayfs stack. */
1154
1155 if (FLAGS_SET(i->flags, IMPORT_FOREIGN_UID)) {
1156 r = import_make_foreign_userns(&i->userns_fd);
1157 if (r < 0)
1158 return r;
1159
1160 r = mountfsd_make_directory_fd(
1161 /* vl= */ NULL,
1162 dir_fd,
1163 "rw",
1164 0755,
1165 /* flags= */ 0,
1166 /* ret_directory_fd= */ NULL);
1167 if (r < 0)
1168 return r;
1169 } else {
1170 _cleanup_close_ int rw_fd = open_mkdir_at(dir_fd, "rw", O_EXCL|O_CLOEXEC, 0755);
1171 if (rw_fd < 0)
1172 return log_error_errno(rw_fd, "Failed to create 'rw' layer: %m");
1173 }
1174 }
1175
1176 if (rename(jt, j) < 0)
1177 return log_error_errno(errno, "Failed to move '%s' into place: %m", j);
1178
1179 jt = mfree(jt); /* Disarm rm_rf_physical_and_free() */
1180
1181 log_info("Mount stack written to '%s'.", j);
1182 return 0;
1183 }
1184
1185 static int oci_pull_make_local(OciPull *i) {
1186 int r;
1187
1188 assert(i);
1189 assert(oci_pull_is_done(i));
1190
1191 r = oci_pull_save_mstack(i);
1192 if (r < 0)
1193 return r;
1194
1195 if (!iovec_is_set(&i->config) ||
1196 iovec_equal(&i->config, &IOVEC_MAKE_STRING("{}")))
1197 log_info("Image has no configuration, not saving.");
1198 else {
1199 r = oci_pull_save_nspawn_settings(i);
1200 if (r < 0)
1201 return r;
1202
1203 r = oci_pull_save_oci_config(i);
1204 if (r < 0)
1205 return r;
1206 }
1207
1208 return 0;
1209 }
1210
1211 static int oci_pull_work(OciPull *i) {
1212 int r;
1213
1214 assert(i);
1215
1216 r = oci_pull_fetch_layers(i);
1217 if (r < 0)
1218 return r;
1219
1220 if (!oci_pull_is_done(i))
1221 return 1; /* continue */
1222
1223 r = oci_pull_make_local(i);
1224 if (r < 0)
1225 return r;
1226
1227 log_info("Everything done.");
1228 return 0; /* done */
1229 }
1230
1231 static void oci_pull_finish(OciPull *i, int r) {
1232 assert(i);
1233
1234 if (i->on_finished)
1235 i->on_finished(i, r, i->userdata);
1236 else
1237 sd_event_exit(i->event, r);
1238 }
1239
1240 static void oci_pull_job_on_finished_layer(PullJob *j) {
1241 int r;
1242
1243 assert(j);
1244
1245 OciLayerState *st = ASSERT_PTR(j->userdata);
1246 OciPull *i = st->pull;
1247
1248 if (j->error != 0) {
1249 r = log_error_errno(j->error, "Failed to retrieve layer file: %m");
1250 goto finish;
1251 }
1252
1253 pull_job_close_disk_fd(j);
1254
1255 if (pidref_is_set(&st->tar_pid)) {
1256 r = pidref_wait_for_terminate_and_check("tar", &st->tar_pid, WAIT_LOG);
1257 if (r < 0)
1258 goto finish;
1259
1260 pidref_done(&st->tar_pid);
1261 if (r != EXIT_SUCCESS) {
1262 r = -EIO;
1263 goto finish;
1264 }
1265 }
1266
1267 assert(st->temp_path);
1268 assert(st->final_path);
1269
1270 r = install_file(AT_FDCWD, st->temp_path,
1271 AT_FDCWD, st->final_path,
1272 INSTALL_READ_ONLY|INSTALL_GRACEFUL);
1273 if (r < 0) {
1274 log_error_errno(r, "Failed to rename final image name to %s: %m", st->final_path);
1275 goto finish;
1276 }
1277
1278 st->temp_path = mfree(st->temp_path);
1279
1280 r = set_ensure_put(&i->done_layer_jobs, &pull_job_hash_ops, j);
1281 if (r < 0) {
1282 log_oom();
1283 goto finish;
1284 }
1285
1286 assert(set_remove(i->active_layer_jobs, j) == j);
1287
1288 r = oci_pull_work(i);
1289 if (r <= 0)
1290 goto finish;
1291
1292 return;
1293
1294 finish:
1295 oci_pull_finish(i, r);
1296 }
1297
1298 static void oci_pull_job_on_finished_config(PullJob *j) {
1299 int r;
1300
1301 assert(j);
1302 OciPull *i = ASSERT_PTR(j->userdata);
1303 assert(i->config_job == j);
1304
1305 if (j->error != 0) {
1306 if (j->error == -ENOMEDIUM) /* HTTP 404 */
1307 r = log_error_errno(j->error, "Failed to retrieve config object. (Wrong URL?)");
1308 else
1309 r = log_error_errno(j->error, "Failed to retrieve config object: %m");
1310 goto finish;
1311 }
1312
1313 iovec_done(&i->config);
1314 i->config = TAKE_STRUCT(j->payload);
1315
1316 r = oci_pull_work(i);
1317 if (r <= 0)
1318 goto finish;
1319
1320 return;
1321
1322 finish:
1323 oci_pull_finish(i, r);
1324 }
1325
1326 static void oci_pull_job_on_finished_bearer_token(PullJob *j) {
1327 int r;
1328
1329 assert(j);
1330 OciPull *i = ASSERT_PTR(j->userdata);
1331 assert(i->bearer_token_job == j);
1332
1333 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
1334
1335 if (j->error != 0) {
1336 if (j->error == -ENOMEDIUM) /* HTTP 404 */
1337 r = log_error_errno(j->error, "Failed to retrieve bearer token. (Wrong URL?)");
1338 else
1339 r = log_error_errno(j->error, "Failed to retrieve bearer token: %m");
1340 goto finish;
1341 }
1342
1343 r = pull_job_payload_as_json_object(j, &v);
1344 if (r < 0)
1345 goto finish;
1346
1347 sd_json_variant *tv = sd_json_variant_by_key(v, "token");
1348 if (!tv) {
1349 r = log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Bearer token lacks 'token' field.");
1350 goto finish;
1351 }
1352
1353 if (!sd_json_variant_is_string(tv)) {
1354 r = log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "'token' field of bearer token is not a string.");
1355 goto finish;
1356 }
1357
1358 r = free_and_strdup_warn(&i->bearer_token, sd_json_variant_string(tv));
1359 if (r < 0)
1360 goto finish;
1361
1362 assert(i->manifest_job);
1363 r = pull_job_set_bearer_token(i->manifest_job, i->bearer_token);
1364 if (r < 0) {
1365 log_error_errno(r, "Failed to set bearer token on manifest job: %m");
1366 goto finish;
1367 }
1368
1369 r = pull_job_restart(i->manifest_job, /* new_url= */ NULL);
1370 if (r < 0)
1371 goto finish;
1372
1373 return;
1374
1375 finish:
1376 oci_pull_finish(i, r);
1377 }
1378
1379 static int make_bearer_token_url(const char *realm, const char *service, const char *scope, char **ret) {
1380 assert(realm);
1381 assert(service);
1382 assert(scope);
1383 assert(ret);
1384
1385 _cleanup_free_ char *rs = urlescape(service);
1386 if (!rs)
1387 return -ENOMEM;
1388
1389 _cleanup_free_ char *ss = urlescape(scope);
1390 if (!ss)
1391 return -ENOMEM;
1392
1393 _cleanup_free_ char *url = strjoin(realm, "?service=", rs, "&scope=", ss);
1394 if (!url)
1395 return -ENOMEM;
1396
1397 *ret = TAKE_PTR(url);
1398 return 0;
1399 }
1400
1401 static int oci_pull_process_authentication_challenge(OciPull *i, const char *challenge) {
1402 int r;
1403
1404 assert(i);
1405 assert(challenge);
1406
1407 /* We only know what to do with the bearer token challenge */
1408 const char *e = startswith_no_case(challenge, "bearer ");
1409 if (!e)
1410 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Authentication mechanism not recognized, cannot authenticate.");
1411
1412 if (i->bearer_token_job)
1413 return log_error_errno(SYNTHETIC_ERRNO(EBUSY), "Two bearer token challenges requested, refusing.");
1414
1415 e += strspn(e, WHITESPACE);
1416
1417 _cleanup_strv_free_ char **l = NULL;
1418 r = strv_split_full(&l, e, ",", EXTRACT_KEEP_QUOTE);
1419 if (r < 0)
1420 return log_error_errno(r, "Failed to split bearer token parameters: %m");
1421
1422 _cleanup_free_ char *realm = NULL, *scope = NULL, *service = NULL;
1423 struct {
1424 const char *name;
1425 char **value;
1426 } fields[] = {
1427 { "realm=\"", &realm },
1428 { "scope=\"", &scope },
1429 { "service=\"", &service },
1430 };
1431
1432 STRV_FOREACH(k, l) {
1433 bool found = false;
1434
1435 FOREACH_ELEMENT(f, fields) {
1436 const char *v = startswith_no_case(*k, f->name);
1437 if (!v)
1438 continue;
1439
1440 const char *q = endswith(v,"\"");
1441 if (!q) {
1442 log_warning("Field isn't quoted properly: %s", *k);
1443 continue;
1444 }
1445
1446 _cleanup_free_ char *s = strndup(v, q - v);
1447 if (!s)
1448 return log_oom();
1449
1450 free_and_replace(*f->value, s);
1451 found = true;
1452 break;
1453 }
1454
1455 if (!found)
1456 log_debug("Ignoring bearer token challenge field: %s", *k);
1457 }
1458
1459 if (!realm || !service || !scope)
1460 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Incomplete bearer token fields");
1461
1462 if (!startswith_no_case(realm, "https://"))
1463 return log_error_errno(SYNTHETIC_ERRNO(ENOKEY), "Authentication realm is not an URL, don't know how to proceed.");
1464
1465 _cleanup_free_ char *url = NULL;
1466 r = make_bearer_token_url(realm, service, scope, &url);
1467 if (r < 0)
1468 return log_error_errno(r, "Failed to make bearer token URL: %m");
1469
1470 r = pull_job_new(&i->bearer_token_job, url, i->glue, i);
1471 if (r < 0)
1472 return r;
1473
1474 i->bearer_token_job->on_finished = oci_pull_job_on_finished_bearer_token;
1475 i->bearer_token_job->description = strjoin("Bearer token (", url, ")");
1476
1477 r = pull_job_begin(i->bearer_token_job);
1478 if (r < 0)
1479 return r;
1480
1481 return 1; /* continue running */
1482 }
1483
1484 static void oci_pull_job_on_finished_manifest(PullJob *j) {
1485 int r;
1486
1487 assert(j);
1488 OciPull *i = ASSERT_PTR(j->userdata);
1489 assert(i->manifest_job == j);
1490
1491 if (j->error != 0) {
1492 if (j->error == -ENOMEDIUM) /* HTTP 404 */
1493 r = log_error_errno(j->error, "Failed to retrieve manifest/index file. (Wrong URL?)");
1494 else if (j->error == -ENOKEY) { /* HTTP 401 - Need authentication */
1495
1496 if (j->authentication_challenge) {
1497 r = oci_pull_process_authentication_challenge(i, j->authentication_challenge);
1498 if (r > 0)
1499 return;
1500
1501 goto finish;
1502 } else
1503 r = log_error_errno(j->error, "Failed to retrieve manifest/index file. (Needing authentication.)");
1504 } else
1505 r = log_error_errno(j->error, "Failed to retrieve manifest/index file: %m");
1506 goto finish;
1507 }
1508
1509 /* If we have no content type, let's assume it's a manifest, not an index. This can happen in case we
1510 * operate with file:// URLs, which in turn is really useful for testing purposes, to mock an OCI
1511 * registry without having to set up an HTTP service. */
1512 if (streq_ptr(j->content_type, "application/vnd.oci.image.manifest.v1+json") ||
1513 !j->content_type) {
1514 r = oci_pull_process_manifest(i, j);
1515 if (r <= 0)
1516 goto finish;
1517
1518 return;
1519 }
1520
1521 if (streq_ptr(j->content_type, "application/vnd.oci.image.index.v1+json")) {
1522
1523 if (i->refuse_index) {
1524 r = log_error_errno(SYNTHETIC_ERRNO(EPROTO), "Already processed an OCI index, refusing to process another one.");
1525 goto finish;
1526 }
1527
1528 /* For now do not allow nested indexes */
1529 i->refuse_index = true;
1530
1531 r = oci_pull_process_index(i, j);
1532 if (r <= 0)
1533 goto finish;
1534
1535 return;
1536 }
1537
1538 r = log_error_errno(SYNTHETIC_ERRNO(EPROTO), "Unexpected content type '%s', refusing.", strna(j->content_type));
1539
1540 finish:
1541 oci_pull_finish(i, r);
1542 }
1543
1544 int oci_pull_start(
1545 OciPull *i,
1546 const char *ref,
1547 const char *local,
1548 ImportFlags flags) {
1549
1550 int r;
1551
1552 assert(i);
1553 assert(ref);
1554
1555 r = oci_ref_parse(ref, &i->repository, &i->image, &i->tag);
1556 if (r < 0)
1557 return r;
1558
1559 r = oci_ref_normalize(&i->protocol, &i->repository, &i->image, &i->tag);
1560 if (r < 0)
1561 return r;
1562
1563 if (local && !pull_validate_local(local, flags))
1564 return -EINVAL;
1565
1566 if (i->manifest_job)
1567 return -EBUSY;
1568
1569 r = free_and_strdup(&i->local, local);
1570 if (r < 0)
1571 return r;
1572
1573 i->flags = flags;
1574
1575 _cleanup_free_ char *url = NULL;
1576 r = oci_make_manifest_url(i->protocol, i->repository, i->image, i->tag, &url);
1577 if (r < 0)
1578 return r;
1579
1580 /* Set up */
1581 r = pull_job_new(&i->manifest_job, url, i->glue, i);
1582 if (r < 0)
1583 return r;
1584
1585 if (i->bearer_token) {
1586 r = pull_job_set_bearer_token(i->manifest_job, i->bearer_token);
1587 if (r < 0)
1588 return r;
1589 }
1590
1591 r = pull_job_set_accept(
1592 i->manifest_job,
1593 STRV_MAKE("application/vnd.oci.image.manifest.v1+json",
1594 "application/vnd.oci.image.index.v1+json"));
1595 if (r < 0)
1596 return r;
1597
1598 i->manifest_job->on_finished = oci_pull_job_on_finished_manifest;
1599 i->manifest_job->description = strjoin("Image Index (", url, ")");
1600 if (!i->manifest_job->description)
1601 return -ENOMEM;
1602
1603 return pull_job_begin(i->manifest_job);
1604 }