registry_apiv2.c 33.6 KB
Newer Older
W
WangFengTu 已提交
1 2
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2020. All rights reserved.
3 4 5 6
 * iSulad licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
W
WangFengTu 已提交
7 8 9
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
10
 * See the Mulan PSL v2 for more details.
W
WangFengTu 已提交
11 12 13 14 15 16 17 18 19 20 21
 * Author: wangfengtu
 * Create: 2020-03-05
 * Description: provide registry api v2 functions
 ******************************************************************************/

#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <fcntl.h>              /* Obtain O_* constant definitions */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <limits.h>
22
#include <sys/utsname.h>
W
WangFengTu 已提交
23

W
WangFengTu 已提交
24
#include "registry_type.h"
W
WangFengTu 已提交
25 26 27 28 29 30 31 32 33
#include "log.h"
#include "buffer.h"
#include "http.h"
#include "registry_apiv2.h"
#include "http_request.h"
#include "utils.h"
#include "parser.h"
#include "mediatype.h"
#include "oci_image_index.h"
34
#include "registry_manifest_list.h"
W
WangFengTu 已提交
35
#include "auths.h"
W
WangFengTu 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

#define DOCKER_API_VERSION_HEADER "Docker-Distribution-API-Version: registry/2.0"
#define MAX_ACCEPT_LEN 128

static int parse_http_header(char *resp_buf, size_t buf_size, struct parsed_http_message *message)
{
    char *real_message = NULL;
    int ret = 0;
    size_t real_len = 0;

    if (resp_buf == NULL || message == NULL) {
        ERROR("Invalid NULL param");
        return -1;
    }

    real_message = strstr(resp_buf, "HTTP/1.1");
    if (real_message == NULL) {
        ERROR("Failed to parse response, the response do not have HTTP/1.1");
        ret = -1;
        goto out;
    }

    real_len = buf_size - (real_message - resp_buf);
    ret = parse_http(real_message, real_len, message, HTTP_RESPONSE);
    if (ret != 0) {
        ERROR("Failed to parse response: %s", real_message);
        ret = -1;
        goto out;
    }

out:

    return ret;
}

static int parse_challenges(pull_descriptor *desc, char *schema, char *params)
{
    challenge c = {0};
    char **kv_strs = NULL;
    char **kv = NULL;
    size_t len = 0;
    size_t i = 0;
    char *value = NULL;
    int ret = -1;

    // Support "Bearer" and "Basic" only.
    if (!strcasecmp(schema, "Bearer")) {
        // params:
        // realm="https://auth.docker.io/token",service="registry.docker.io"
        params = util_trim_space(params);
        kv_strs = util_string_split(params, ',');
        len = util_array_len((const char **)kv_strs);
        for (i = 0; i < len; i++) {
            kv = util_string_split(kv_strs[i], '=');
            if (util_array_len((const char **)kv) != 2) {
                ERROR("Split key/value %s failed, origin string is %s", kv, kv_strs[i]);
                ret = -1;
                goto out;
            }
            value = util_trim_space(kv[1]);
            value = util_trim_quotation(value);
            if (!strcmp(kv[0], "realm")) {
                free(c.realm);
                c.realm = util_strdup_s(value);
            } else if (!strcmp(kv[0], "service")) {
                free(c.service);
                c.service = util_strdup_s(value);
            }
            util_free_array(kv);
            kv = NULL;
        }
    } else if (!strcasecmp(schema, "Basic")) {
        // Do nothing
    } else {
        WARN("Found unsupported schema %s", schema);
        ret = -1;
        goto out;
    }
    c.schema = util_strdup_s(schema);

    for (i = 0; i < CHALLENGE_MAX; i++) {
        // schema == NULL means this challenge have not be used.
        if (desc->challenges[i].schema == NULL) {
            desc->challenges[i] = c;
            return 0;
        }
    }

    WARN("Too many challenges found, keep %s only", CHALLENGE_MAX);
    ret = -1;

out:
    if (ret != 0) {
        free_challenge(&c);
    }
    util_free_array(kv_strs);
    kv_strs = NULL;
    util_free_array(kv);
    kv = NULL;

    return -1;
}

static int parse_auth(pull_descriptor *desc, char *auth)
{
    char *origin_tmp_auth = NULL;
    char *trimmed_auth = NULL;
    int ret = 0;
    char **parts = NULL;

    if (auth == NULL) {
        return -1;
    }

    origin_tmp_auth = util_strdup_s(auth);
    util_trim_newline(origin_tmp_auth);
    trimmed_auth = util_trim_space(origin_tmp_auth);
    parts = util_string_split_multi(trimmed_auth, ' ');
    if (util_array_len((const char **)parts) < 2) {
        ERROR("Split auth failed, auth: %s", trimmed_auth);
        ret = -1;
        goto out;
    }

    // parts[0]: Bearer
    // parts[1]: realm="https://auth.docker.io/token",service="registry.docker.io"
    ret = parse_challenges(desc, parts[0], parts[1]);
    if (ret != 0) {
        ERROR("Parse challenges failed, schema: %s, params: %s", parts[0], parts[1]);
        ret = -1;
        goto out;
    }

out:
    free(origin_tmp_auth);
    origin_tmp_auth = NULL;
    util_free_array(parts);

    return ret;
}

static int parse_auths(pull_descriptor *desc, struct parsed_http_message *m)
{
    int i = 0;
    int ret = 0;

    for (i = 0; i < m->num_headers; i++) {
        if (strcmp(m->headers[i][0], "Www-Authenticate") == 0) {
            ret = parse_auth(desc, (char *)m->headers[i][1]);
            if (ret != 0) {
                WARN("parse auth %s failed", (char *)m->headers[i][1]);
            }
        }
    }

    return ret;
}

static void free_parsed_http_message(struct parsed_http_message **message)
{
    if (message == NULL || *message == NULL) {
        return;
    }
    free((*message)->body);
    (*message)->body = NULL;
    free(*message);
    *message = NULL;
    return;
}

static struct parsed_http_message * get_parsed_message(char *http_head)
{
    int ret = 0;
    struct parsed_http_message *message = NULL;

    message = (struct parsed_http_message *)util_common_calloc_s(sizeof(struct parsed_http_message));
    if (message == NULL) {
        ERROR("out of memory");
        ret = -1;
        goto out;
    }

    ret = parse_http_header(http_head, strlen(http_head), message);
    if (ret != 0) {
        ERROR("parse http header failed");
        ret = -1;
        goto out;
    }

out:
    if (ret != 0) {
        free_parsed_http_message(&message);
    }

    return message;
}

static int parse_ping_header(pull_descriptor *desc, char *http_head)
{
    struct parsed_http_message *message = NULL;
    char *version = NULL;
    int ret = 0;

    if (http_head == NULL) {
        ERROR("Invalid NULL param");
        return -1;
    }

    // Response data:
    // HTTP/1.0 200 Connection established
    // HTTP/1.1 401 Unauthorized
    // Content-Type: application/json
    // Docker-Distribution-Api-Version: registry/2.0
    // Www-Authenticate: Bearer realm="https://auth.docker.io/token",service="registry.docker.io"
    // Date: Mon, 16 Mar 2020 01:16:09 GMT
    // Content-Length: 87
    // Strict-Transport-Security: max-age=31536000
    //
    // {"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
    message = get_parsed_message(http_head);
    if (message == NULL) {
        ERROR("out of memory");
        ret = -1;
        goto out;
    }

    if (message->status_code != StatusUnauthorized && message->status_code != StatusOK) {
        ERROR("registry response invalid status code %d", message->status_code);
        ret = -1;
        goto out;
    }

    version = get_header_value(message, "Docker-Distribution-Api-Version");
    if (version == NULL) {
        ERROR("Docker-Distribution-Api-Version not found in header, registry can not support registry API V2");
        ret = -1;
        goto out;
    }

    if (!strings_contains_word(version, "registry/2.0")) {
        ERROR("Docker-Distribution-Api-Version does not contain registry/2.0, it's value is %s."
              "Registry can not support registry API V2", version);
        ret = -1;
        goto out;
    }

    ret = parse_auths(desc, message);
    if (ret != 0) {
        ERROR("Parse WWW-Authenticate header failed");
        goto out;
    }

out:
    if (ret != 0) {
        ERROR("ping resp=%s", http_head);
    }

    free_parsed_http_message(&message);

    return ret;
}

int registry_pingv2(pull_descriptor *desc, char *protocol)
{
    int ret = 0;
    int sret = 0;
    char *output = NULL;
    char url[PATH_MAX] = { 0 };
    char **headers = NULL;

    if (desc == NULL) {
        ERROR("Invalid NULL param");
        return -1;
    }

    sret = snprintf(url, sizeof(url), "%s://%s/v2/", protocol, desc->host);
    if (sret < 0 || (size_t)sret >= sizeof(url)) {
        ERROR("Failed to sprintf url for ping, host is %s", desc->host);
        ret = -1;
        goto out;
    }

    ret = util_array_append(&headers, DOCKER_API_VERSION_HEADER);
    if (ret != 0) {
        ERROR("Append api version to header failed");
        ret = -1;
        goto out;
    }

    // Sending url
    // https://registry-1.docker.io/v2/
    INFO("sending ping url: %s", url);
    ret = http_request_buf(desc, url, (const char **)headers, &output, HEAD_ONLY);
    if (ret != 0) {
        ERROR("http request failed");
        goto out;
    }
    DEBUG("ping resp=%s", output);

    ret = parse_ping_header(desc, output);
    if (ret != 0) {
        ERROR("parse ping header failed, response: %s", output);
        goto out;
    }

out:
    free(output);
    output = NULL;
    util_free_array(headers);
    headers = NULL;

    return ret;
}

static int registry_ping(pull_descriptor *desc)
{
    int ret = 0;

    if (desc == NULL) {
        ERROR("Invalid NULL param");
        return -1;
    }

    if (desc->already_ping && desc->protocol != NULL) {
        return 0;
    }

    ret = registry_pingv2(desc, "https");
    if (ret == 0) {
        goto out;
    }

    ERROR("ping %s with https failed, try http", desc->host);

    ret = registry_pingv2(desc, "http");
    if (ret != 0) {
        ERROR("ping %s failed", desc->host);
        goto out;
    }

out:

    if (ret == 0) {
        desc->protocol = util_strdup_s("http");
        desc->already_ping = true;
    }

    return ret;
}

static int registry_request(pull_descriptor *desc, char *path, char **custom_headers, char *file, char **output_buffer,
                            resp_data_type type)
{
    int ret = 0;
    int sret = 0;
    char url[PATH_MAX] = { 0 };
    char **headers = NULL;

    if (desc == NULL || path == NULL || (file == NULL && output_buffer == NULL)) {
        ERROR("Invalid NULL param");
        return -1;
    }

    ret = registry_ping(desc);
    if (ret != 0) {
        ERROR("ping failed");
        return -1;
    }

    sret = snprintf(url, sizeof(url), "%s://%s%s", desc->protocol, desc->host, path);
    if (sret < 0 || (size_t)sret >= sizeof(url)) {
        ERROR("Failed to sprintf url, path is %s", path);
        ret = -1;
        goto out;
    }

    headers = str_array_dup((const char **)custom_headers, util_array_len((const char **)custom_headers));
    if (ret != 0) {
        ERROR("duplicate custom headers failed");
        ret = -1;
        goto out;
    }

    ret = util_array_append(&headers, DOCKER_API_VERSION_HEADER);
    if (ret != 0) {
        ERROR("Append api version to header failed");
        ret = -1;
        goto out;
    }

    DEBUG("sending url: %s", url);
    if (output_buffer != NULL) {
        ret = http_request_buf(desc, url, (const char **)headers, output_buffer, type);
        if (ret != 0) {
            ERROR("http request buffer failed, url: %s", url);
            goto out;
        }
        DEBUG("resp=%s", *output_buffer);
    } else {
        ret = http_request_file(desc, url, (const char **)headers, file);
        if (ret != 0) {
            ERROR("http request file failed, url: %s", url);
            goto out;
        }
    }

out:
    util_free_array(headers);
    headers = NULL;

    return ret;
}

static int check_content_type(const char *content_type)
{
    if (content_type == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    if (!strcmp(content_type, DOCKER_MANIFEST_SCHEMA1_JSON) ||
        !strcmp(content_type, DOCKER_MANIFEST_SCHEMA1_PRETTYJWS) ||
        !strcmp(content_type, DOCKER_MANIFEST_SCHEMA2_JSON) ||
        !strcmp(content_type, DOCKER_MANIFEST_SCHEMA2_LIST) ||
        !strcmp(content_type, OCI_MANIFEST_V1_JSON) ||
        !strcmp(content_type, MEDIA_TYPE_APPLICATION_JSON) ||
        !strcmp(content_type, OCI_INDEX_V1_JSON)) {
        return 0;
    }

    return -1;
}

static int parse_manifests_info(char *http_head, char **content_type, char **digest)
{
    int ret = 0;
    struct parsed_http_message *message = NULL;
    char *value = NULL;

    if (http_head == NULL || content_type == NULL || digest == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    // HTTP/1.0 200 Connection established
    //
    // HTTP/1.1 200 OK
    // Content-Length: 948
    // Content-Type: application/vnd.docker.distribution.manifest.v2+json
    // Docker-Content-Digest: sha256:788fa27763db6d69ad3444e8ba72f947df9e7e163bad7c1f5614f8fd27a311c3
    // Docker-Distribution-Api-Version: registry/2.0
    // Etag: "sha256:788fa27763db6d69ad3444e8ba72f947df9e7e163bad7c1f5614f8fd27a311c3"
    // Date: Thu, 27 Jul 2017 09:14:10 GMT
    // Strict-Transport-Security: max-age=31536000
    message = get_parsed_message(http_head);
    if (message == NULL) {
        ERROR("parse http header message for manifests failed, message: %s", http_head);
        ret = -1;
        goto out;
    }

    if (message->status_code != StatusOK) {
        ERROR("registry response invalid status code %d\nresponse:%s", message->status_code, http_head);
        ret = -1;
        goto out;
    }

    value = get_header_value(message, "Content-Type");
    if (value == NULL) {
        ERROR("Get content type from message header failed, response: %s", http_head);
        ret = -1;
        goto out;
    }

    ret = check_content_type(value);
    if (ret != 0) {
        ERROR("Unsupported content type: %s", value);
        goto out;
    }
    *content_type = util_strdup_s(value);

    value = get_header_value(message, "Docker-Content-Digest");
    if (value != NULL) { // No Docker-Content-Digest is also valid
        if (!util_valid_digest(value)) {
            ERROR("Invalid content digest: %s", value);
            goto out;
        }
        *digest = util_strdup_s(value);
    }

out:

    if (ret != 0) {
        free(*content_type);
        *content_type = NULL;
        free(*digest);
        *digest = NULL;
    }

    free_parsed_http_message(&message);

    return ret;
}

static int append_manifests_accepts(char ***custom_headers)
{
    int i = 0;
    int ret = 0;
    int sret = 0;
    char accept[MAX_ACCEPT_LEN] = {0};
    const char *mediatypes[] = {
        DOCKER_MANIFEST_SCHEMA2_JSON,
        DOCKER_MANIFEST_SCHEMA1_PRETTYJWS,
        DOCKER_MANIFEST_SCHEMA1_JSON,
        DOCKER_MANIFEST_SCHEMA2_LIST,
        MEDIA_TYPE_APPLICATION_JSON,
        OCI_MANIFEST_V1_JSON,
        OCI_INDEX_V1_JSON
    };

    for (i = 0; i < sizeof(mediatypes) / sizeof(mediatypes[0]); i++) {
        sret = snprintf(accept, MAX_ACCEPT_LEN, "Accept: %s", mediatypes[i]);
        if (sret < 0 || (size_t)sret >= MAX_ACCEPT_LEN) {
            ERROR("Failed to sprintf accept media type %s", mediatypes[i]);
            ret = -1;
            goto out;
        }

        ret = util_array_append(custom_headers, accept);
        if (ret != 0) {
            ERROR("append accepts failed");
            goto out;
        }
    }

out:

    return ret;
}

static int fetch_manifests_info(pull_descriptor *desc, char **content_type, char **digest)
{
    int ret = 0;
    int sret = 0;
    char *http_head = NULL;
    char **custom_headers = NULL;
    char path[PATH_MAX] = { 0 };

    if (desc == NULL || path == NULL || content_type == NULL || digest == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    ret = append_manifests_accepts(&custom_headers);
    if (ret != 0) {
        ERROR("append accepts failed");
        goto out;
    }

    sret = snprintf(path, sizeof(path), "/v2/%s/manifests/%s", desc->name, desc->tag);
    if (sret < 0 || (size_t)sret >= sizeof(path)) {
        ERROR("Failed to sprintf path for manifest");
        ret = -1;
        goto out;
    }

    ret = registry_request(desc, path, custom_headers, NULL, &http_head, HEAD_ONLY);
    if (ret != 0) {
        ERROR("registry: Get %s failed", path);
        goto out;
    }

    ret = parse_manifests_info(http_head, content_type, digest);
    if (ret != 0) {
        ret = -1;
        goto out;
    }

out:

    free(http_head);
    http_head = NULL;
    util_free_array(custom_headers);
    custom_headers = NULL;

    return ret;
}

static int fetch_data(pull_descriptor *desc, char *path, char *file, char *content_type,
                      char *digest)
{
    int ret = 0;
    int sret = 0;
    char accept[MAX_ELEMENT_SIZE] = {0};
    char **custom_headers = NULL;

    // digest can be NULL
    if (desc == NULL || path == NULL || file == NULL || content_type == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    sret = snprintf(accept, MAX_ACCEPT_LEN, "Accept: %s", content_type);
    if (sret < 0 || (size_t)sret >= MAX_ACCEPT_LEN) {
        ERROR("Failed to sprintf accept media type %s", content_type);
        ret = -1;
        goto out;
    }

    ret = util_array_append(&custom_headers, accept);
    if (ret != 0) {
        ERROR("append accepts failed");
        goto out;
    }

    ret = registry_request(desc, path, custom_headers, file, NULL, BODY_ONLY);
    if (ret != 0) {
        ERROR("registry: Get %s failed", path);
        goto out;
    }

    // If content is signatured, digest is for payload but not fetched data
    if (strcmp(content_type, DOCKER_MANIFEST_SCHEMA1_PRETTYJWS) && digest != NULL) {
        if (!util_valid_digest_file(file, digest)) {
            ERROR("data from %s does not have digest %s", path, digest);
            goto out;
        }
    }

out:
    util_free_array(custom_headers);
    custom_headers = NULL;

    return ret;
}

672
static char *get_cpu_variant()
W
WangFengTu 已提交
673
{
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
    char *variant = NULL;
    char *cpuinfo = NULL;
    char *start_pos = NULL;
    char *end_pos = NULL;

    cpuinfo = util_read_text_file("/proc/cpuinfo");
    if (cpuinfo == NULL) {
        ERROR("read /proc/cpuinfo failed");
        return NULL;
    }

    start_pos = strstr(cpuinfo, "CPU architecture");
    if (start_pos == NULL) {
        ERROR("can not found the key \"CPU architecture\" when try to get cpu variant");
        goto out;
    }
    end_pos = strchr(start_pos, '\n');
    if (end_pos != NULL) {
        *end_pos = 0;
    }
    start_pos = strchr(start_pos, ':');
    if (start_pos == NULL) {
        ERROR("can not found delimiter \":\" when try to get cpu variant");
        goto out;
    }
    util_trim_newline(start_pos);
    start_pos = util_trim_space(start_pos);

    variant = util_strdup_s(start_pos);

out:
    free(cpuinfo);
    cpuinfo = NULL;

    return variant;
W
WangFengTu 已提交
709 710
}

711
static int normalized_host_os_arch(char **host_os, char **host_arch, char **host_variant)
W
WangFengTu 已提交
712 713
{
    int ret = 0;
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    struct utsname uts;
    char *tmp_variant = NULL;

    if (host_os == NULL || host_arch == NULL || host_variant == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    if (uname(&uts) < 0) {
        ERROR("Failed to read host arch and os: %s", strerror(errno));
        ret = -1;
        goto out;
    }

    *host_os = util_strdup_s(uts.sysname);

    if (strcasecmp("i386", uts.machine) == 0) {
        *host_arch = util_strdup_s("386");
    } else if ((strcasecmp("x86_64", uts.machine) == 0)
               || (strcasecmp("x86-64", uts.machine) == 0)) {
        *host_arch = util_strdup_s("amd64");
    } else if (strcasecmp("aarch64", uts.machine) == 0) {
        *host_arch = strdup("arm64");
    } else if ((strcasecmp("armhf", uts.machine) == 0)
               || (strcasecmp("armel", uts.machine) == 0)) {
        *host_arch = strdup("arm");
    } else {
        *host_arch = strdup(uts.machine);
    }

    if (!strcmp(*host_arch, "arm") || !strcmp(*host_arch, "arm64")) {
        *host_variant = get_cpu_variant();
        if (!strcmp(*host_arch, "arm64") && *host_variant != NULL &&
            (!strcmp(*host_variant, "8") || !strcmp(*host_variant, "v8"))) {
            free(*host_variant);
            *host_variant = NULL;
        }
        if (!strcmp(*host_arch, "arm") && *host_variant == NULL) {
            *host_variant = util_strdup_s("v7");
        } else if (!strcmp(*host_arch, "arm") && *host_variant != NULL) {
            tmp_variant = *host_variant;
            *host_variant = NULL;
            if (!strcmp(tmp_variant, "5")) {
                *host_variant = util_strdup_s("v5");
            } else if (!strcmp(tmp_variant, "6")) {
                *host_variant = util_strdup_s("v6");
            } else if (!strcmp(tmp_variant, "7")) {
                *host_variant = util_strdup_s("v7");
            } else if (!strcmp(tmp_variant, "8")) {
                *host_variant = util_strdup_s("v8");
            }
            free(tmp_variant);
            tmp_variant = NULL;
        }
    }

out:
    if (ret != 0) {
        free(*host_os);
        *host_os = NULL;
        free(*host_arch);
        *host_arch = NULL;
        free(*host_variant);
        *host_variant = NULL;
    }

    return ret;
}

static bool is_variant_same(char *variant1, char *variant2)
{
    if (variant1 == NULL && variant2 == NULL) {
        return true;
    }
    if (variant1 == NULL || variant2 == NULL) {
        return false;
    }
    return !strcmp(variant1, variant2);
}

static int select_oci_manifest(oci_image_index *index, char **content_type, char **digest)
{
    size_t i = 0;
    int ret = 0;
W
WangFengTu 已提交
798 799
    char *host_os = NULL;
    char *host_arch = NULL;
800 801 802
    char *host_variant = NULL;
    oci_image_index_manifests_platform *platform = NULL;
    bool found = false;
W
WangFengTu 已提交
803

804
    if (index == NULL || content_type == NULL || digest == NULL) {
W
WangFengTu 已提交
805 806 807 808
        ERROR("Invalid NULL pointer");
        return -1;
    }

809
    ret = normalized_host_os_arch(&host_os, &host_arch, &host_variant);
W
WangFengTu 已提交
810 811 812 813 814
    if (ret != 0) {
        ret = -1;
        goto out;
    }

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
    for (i = 0; i < index->manifests_len; i++) {
        platform = index->manifests[i]->platform;
        if (platform == NULL || platform->architecture == NULL || platform->os == NULL) {
            continue;
        }
        if (!strcmp(platform->architecture, host_arch) && !strcmp(platform->os, host_os) &&
            is_variant_same(host_variant, platform->variant)) {
            free(*content_type);
            *content_type = util_strdup_s(index->manifests[i]->media_type);
            free(*digest);
            *digest = util_strdup_s(index->manifests[i]->digest);
            found = true;
            goto out;
        }
    }

    // Compatiable with manifests which didn't have variant
    for (i = 0; i < index->manifests_len; i++) {
        platform = index->manifests[i]->platform;
        if (platform == NULL || platform->architecture == NULL || platform->os == NULL) {
            continue;
        }
        if (!strcmp(platform->architecture, host_arch) && !strcmp(platform->os, host_os)) {
            free(*content_type);
            *content_type = util_strdup_s(index->manifests[i]->media_type);
            free(*digest);
            *digest = util_strdup_s(index->manifests[i]->digest);
            found = true;
            goto out;
        }
    }
    ret = -1;
    ERROR("Cann't match any manifest, host os %s, host arch %s, host variant %s", host_os, host_arch, host_variant);

out:
    free(host_os);
    host_os = NULL;
    free(host_arch);
    host_arch = NULL;
    free(host_variant);
    host_variant = NULL;

    if (found && (*digest == NULL || *content_type == NULL)) {
        ERROR("Matched manifest have NULL digest or mediatype in manifest, mediatype %s, digest %s",
              *content_type, *digest);
        ret = -1;
    }

    return ret;
}

static int select_docker_manifest(registry_manifest_list *manifests, char **content_type, char **digest)
{
    size_t i = 0;
    int ret = 0;
    char *host_os = NULL;
    char *host_arch = NULL;
    char *host_variant = NULL;
    registry_manifest_list_manifests_platform *platform = NULL;
    bool found = false;

    if (manifests == NULL || content_type == NULL || digest == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    ret = normalized_host_os_arch(&host_os, &host_arch, &host_variant);
    if (ret != 0) {
        ret = -1;
        goto out;
    }

    for (i = 0; i < manifests->manifests_len; i++) {
        platform = manifests->manifests[i]->platform;
        if (platform == NULL || platform->architecture == NULL || platform->os == NULL) {
            continue;
        }
        if (!strcmp(platform->architecture, host_arch) && !strcmp(platform->os, host_os) &&
            is_variant_same(host_variant, platform->variant)) {
            free(*content_type);
            *content_type = util_strdup_s(manifests->manifests[i]->media_type);
            free(*digest);
            *digest = util_strdup_s(manifests->manifests[i]->digest);
            found = true;
            goto out;
        }
    }

    // Compatiable with manifests which didn't have variant
    for (i = 0; i < manifests->manifests_len; i++) {
        platform = manifests->manifests[i]->platform;
        if (platform == NULL || platform->architecture == NULL || platform->os == NULL) {
            continue;
        }
        if (!strcmp(platform->architecture, host_arch) && !strcmp(platform->os, host_os)) {
            free(*content_type);
            *content_type = util_strdup_s(manifests->manifests[i]->media_type);
            free(*digest);
            *digest = util_strdup_s(manifests->manifests[i]->digest);
            found = true;
            goto out;
        }
    }
    ret = -1;
    ERROR("Cann't match any manifest, host os %s, host arch %s, host variant %s", host_os, host_arch, host_variant);

out:
    free(host_os);
    host_os = NULL;
    free(host_arch);
    host_arch = NULL;
    free(host_variant);
    host_variant = NULL;

    if (found && (*digest == NULL || *content_type == NULL)) {
        ERROR("Matched manifest have NULL digest or mediatype in manifest, mediatype %s, digest %s",
              *content_type, *digest);
        ret = -1;
    }

    return ret;
}

static int select_manifest(char *file, char **content_type, char **digest)
{
    int ret = 0;
    oci_image_index *index = NULL;
    registry_manifest_list *manifests = NULL;
    parser_error err = NULL;

    if (file == NULL || content_type == NULL || *content_type == NULL || digest == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

W
WangFengTu 已提交
950 951 952
    if (!strcmp(*content_type, OCI_INDEX_V1_JSON)) {
        index = oci_image_index_parse_file((const char *)file, NULL, &err);
        if (index == NULL) {
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            ERROR("parse oci image index failed: %s", err);
            ret = -1;
            goto out;
        }
        ret = select_oci_manifest(index, content_type, digest);
        if (ret != 0) {
            ERROR("select oci manifest failed");
            ret = -1;
            goto out;
        }
    } else if (!strcmp(*content_type, DOCKER_MANIFEST_SCHEMA2_LIST)) {
        manifests = registry_manifest_list_parse_file((const char *)file, NULL, &err);
        if (manifests == NULL) {
            ERROR("parse docker image manifest list failed: %s", err);
            ret = -1;
            goto out;
        }

        ret = select_docker_manifest(manifests, content_type, digest);
        if (ret != 0) {
            ERROR("select docker manifest failed");
W
WangFengTu 已提交
974 975 976
            ret = -1;
            goto out;
        }
977 978 979 980 981
    } else {
        // This should not happen
        ERROR("Unexpected content type %s", *content_type);
        ret = -1;
        goto out;
W
WangFengTu 已提交
982 983 984 985 986 987 988
    }

out:
    if (index != NULL) {
        free_oci_image_index(index);
        index = NULL;
    }
989 990 991 992 993 994
    if (manifests != NULL) {
        free_registry_manifest_list(manifests);
        manifests = NULL;
    }
    free(err);
    err = NULL;
W
WangFengTu 已提交
995 996 997 998 999 1000 1001 1002 1003

    return ret;
}

static int fetch_manifests_data(pull_descriptor *desc, char *file, char **content_type, char **digest)
{
    int ret = 0;
    int sret = 0;
    char path[PATH_MAX] = { 0 };
1004
    char *manifest_text = NULL;
W
WangFengTu 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

    if (desc == NULL || path == NULL || file == NULL || content_type == NULL || *content_type == NULL ||
        digest == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    if (*digest != NULL) {
        sret = snprintf(path, sizeof(path), "/v2/%s/manifests/%s", desc->name, *digest);
    } else {
        sret = snprintf(path, sizeof(path), "/v2/%s/manifests/%s", desc->name, desc->tag);
    }
    if (sret < 0 || (size_t)sret >= sizeof(path)) {
        ERROR("Failed to sprintf path for manifest");
        ret = -1;
        goto out;
    }

    ret = fetch_data(desc, path, file, *content_type, *digest);
    if (ret != 0) {
        ERROR("registry: Get %s failed", path);
        goto out;
    }

    // If it's manifest list, we must choose the manifest which match machine's architecture to download.
    if (!strcmp(*content_type, DOCKER_MANIFEST_SCHEMA2_LIST) || !strcmp(*content_type, OCI_INDEX_V1_JSON)) {
        ret = select_manifest(file, content_type, digest);
        if (ret != 0) {
1033 1034 1035 1036
            manifest_text = util_read_text_file(file);
            ERROR("select manifest failed, manifests:%s", manifest_text);
            free(manifest_text);
            manifest_text = NULL;
W
WangFengTu 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
            goto out;
        }

        sret = snprintf(path, sizeof(path), "/v2/%s/manifests/%s", desc->name, *digest);
        if (sret < 0 || (size_t)sret >= sizeof(path)) {
            ERROR("Failed to sprintf path for manifest");
            ret = -1;
            goto out;
        }

        ret = fetch_data(desc, path, file, *content_type, *digest);
        if (ret != 0) {
            ERROR("registry: Get %s failed", path);
            goto out;
        }
    }

out:

    return ret;
}

1059
int fetch_manifest(pull_descriptor *desc)
W
WangFengTu 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
{
    int ret = 0;
    int sret = 0;
    char file[PATH_MAX] = { 0 };
    char *content_type = NULL;
    char *digest = NULL;

    if (desc == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    sret = snprintf(file, sizeof(file), "%s/manifests", desc->blobpath);
    if (sret < 0 || (size_t)sret >= sizeof(file)) {
        ERROR("Failed to sprintf file for manifest");
        return -1;
    }

    ret = fetch_manifests_info(desc, &content_type, &digest);
    if (ret != 0) {
        ret = -1;
        goto out;
    }

    ret = fetch_manifests_data(desc, file, &content_type, &digest);
    if (ret != 0) {
        ret = -1;
        goto out;
    }

1090 1091 1092 1093
    desc->manifest.media_type = util_strdup_s(content_type);
    desc->manifest.digest = util_strdup_s(digest);
    desc->manifest.file = util_strdup_s(file);

W
WangFengTu 已提交
1094 1095 1096 1097 1098 1099 1100 1101
out:
    free(content_type);
    content_type = NULL;
    free(digest);
    digest = NULL;

    return ret;
}
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

int fetch_config(pull_descriptor *desc)
{
    int ret = 0;
    int sret = 0;
    char file[PATH_MAX] = { 0 };
    char path[PATH_MAX] = { 0 };

    if (desc == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    sret = snprintf(file, sizeof(file), "%s/config", desc->blobpath);
    if (sret < 0 || (size_t)sret >= sizeof(file)) {
        ERROR("Failed to sprintf file for config");
        return -1;
    }

    sret = snprintf(path, sizeof(path), "/v2/%s/blobs/%s", desc->name, desc->config.digest);
    if (sret < 0 || (size_t)sret >= sizeof(path)) {
        ERROR("Failed to sprintf path for config");
        ret = -1;
        goto out;
    }

    ret = fetch_data(desc, path, file, desc->config.media_type, desc->config.digest);
    if (ret != 0) {
        ERROR("registry: Get %s failed", path);
        goto out;
    }

    desc->config.file = util_strdup_s(file);

out:

    return ret;
}

int fetch_layer(pull_descriptor *desc, size_t index)
{
    int ret = 0;
    int sret = 0;
    char file[PATH_MAX] = { 0 };
    char path[PATH_MAX] = { 0 };
    layer_blob *layer = NULL;

    if (desc == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    if (index >= desc->layers_len) {
        ERROR("Invalid layer index %d, total layer number %d", index, desc->layers_len);
        return -1;
    }

    sret = snprintf(file, sizeof(file), "%s/%d", desc->blobpath, (int)index);
    if (sret < 0 || (size_t)sret >= sizeof(file)) {
        ERROR("Failed to sprintf file for layer %lu", index);
        return -1;
    }

    layer = &desc->layers[index];
    sret = snprintf(path, sizeof(path), "/v2/%s/blobs/%s", desc->name, layer->digest);
    if (sret < 0 || (size_t)sret >= sizeof(path)) {
        ERROR("Failed to sprintf path for layer %d, name %s, digest %s", index, desc->name, layer->digest);
        ret = -1;
        goto out;
    }

    ret = fetch_data(desc, path, file, layer->media_type, layer->digest);
    if (ret != 0) {
        ERROR("registry: Get %s failed", path);
        goto out;
    }

    layer->file = util_strdup_s(file);

out:

    return ret;
}
W
WangFengTu 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

int login_to_registry(pull_descriptor *desc)
{
    int ret = 0;
    int sret = 0;
    char *resp_buffer = NULL;
    char path[PATH_MAX] = { 0 };

    if (desc == NULL) {
        ERROR("Invalid NULL pointer");
        return -1;
    }

    sret = snprintf(path, sizeof(path), "/v2/");
    if (sret < 0 || (size_t)sret >= sizeof(path)) {
        ERROR("Failed to sprintf path for login");
        ret = -1;
        goto out;
    }

    ret = registry_request(desc, path, NULL, NULL, &resp_buffer, HEAD_BODY);
    if (ret != 0) {
        ERROR("registry: Get %s failed, resp: %s", path, resp_buffer);
        goto out;
    }

    ret = auths_save(desc->host, desc->username, desc->password);
    if (ret != 0) {
        ERROR("failed to save auth of host %s, use decrypted key %d", desc->host, desc->use_decrypted_key);
        goto out;
    }
out:

    free(resp_buffer);
    resp_buffer = NULL;

    return ret;
}