utils.c 34.1 KB
Newer Older
O
overweight 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 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
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. All rights reserved.
 * iSulad licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 *     http://license.coscl.org.cn/MulanPSL
 * 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.
 * See the Mulan PSL v1 for more details.
 * Author: tanyifeng
 * Create: 2018-11-1
 * Description: provide container utils functions
 *******************************************************************************/

#define _GNU_SOURCE
#include <errno.h>
#include <grp.h>
#include <execinfo.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <ctype.h>
#include <limits.h>
#include <regex.h>
#include <dirent.h>
#include <fcntl.h>
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <securec.h>
#include <termios.h>

#include "utils.h"
#include "log.h"
#include "json_common.h"

int mem_realloc(void **newptr, size_t newsize, void *oldptr, size_t oldsize)
{
    void *tmp = NULL;
    int nret = 0;

    if (newptr == NULL || newsize == 0) {
        goto err_out;
    }

    tmp = util_common_calloc_s(newsize);
    if (tmp == NULL) {
        ERROR("Failed to malloc memory");
        goto err_out;
    }

    if (oldptr != NULL) {
        nret = memcpy_s(tmp, newsize, oldptr, (newsize < oldsize) ? newsize : oldsize);
        if (nret != EOK) {
            ERROR("Failed to memcpy memory");
            free(tmp);
            goto err_out;
        }

        if (memset_s(oldptr, oldsize, 0, oldsize) != EOK) {
            ERROR("Failed to memset memory");
            free(tmp);
            goto err_out;
        }

        free(oldptr);
    }

    *newptr = tmp;
    return 0;

err_out:
    return -1;
}

static int util_read_pipe(int pipe_fd, char **out_buf, size_t *out_buf_size, size_t *out_real_size)
{
    int ret = 0;
    char *tmp = NULL;
    char *buffer = *out_buf;
    size_t old_size = *out_buf_size;
    size_t real_size = *out_real_size;
    size_t new_size = 0;
    ssize_t read_size = 0;

    if (buffer == NULL) {
        new_size = PIPE_BUF + 1;
        buffer = util_common_calloc_s(new_size);
        if (buffer == NULL) {
            ERROR("Memory out");
            ret = -1;
            goto out;
        }
        *out_buf_size = new_size;
        *out_buf = buffer;
        *out_real_size = 0;
    } else {
        if (old_size - real_size < PIPE_BUF + 1) {
            if (old_size > (SIZE_MAX - PIPE_BUF) - 1) {
                ERROR("Memory out");
                ret = -1;
                goto out;
            }

            new_size = old_size + PIPE_BUF + 1;
            ret = mem_realloc((void *)(&tmp), new_size, (void *)buffer, old_size);
            if (ret != 0) {
                ERROR("Memory out");
                ret = -1;
                goto out;
            }
            buffer = tmp;
            *out_buf_size = new_size;
            *out_buf = buffer;
        }
    }

    read_size = util_read_nointr(pipe_fd, buffer + real_size, PIPE_BUF);
    if (read_size > 0) {
        *out_real_size = real_size + (size_t)read_size;
        ret = 0;
        goto out;
    } else if (read_size < 0 && errno == EAGAIN) {
        ret = 0;
        goto out;
    } else {
        ret = -1;
        goto out;
    }

out:
    return ret;
}

#ifndef PR_SET_MM
#define PR_SET_MM 35
#endif

#ifndef PR_SET_MM_MAP
#define PR_SET_MM_MAP 14
#endif

static bool util_dir_skip_current(const struct dirent *pdirent)
{
    if (strcmp(pdirent->d_name, ".") == 0) {
        return true;
    }

    if (strcmp(pdirent->d_name, "..") == 0) {
        return true;
    }
    return false;
}

static bool util_is_std_fileno(int fd)
{
    return fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO;
}

int util_check_inherited(bool closeall, int fd_to_ignore)
{
    struct dirent *pdirent = NULL;
    int fd, fddir;
    DIR *directory = NULL;

restart:
    directory = opendir("/proc/self/fd");
    if (directory == NULL) {
        WARN("Failed to open directory: %m.");
        return -1;
    }

    fddir = dirfd(directory);
    pdirent = readdir(directory);
    for (; pdirent != NULL; pdirent = readdir(directory)) {
        if (util_dir_skip_current(pdirent)) {
            continue;
        }

        if (util_safe_int(pdirent->d_name, &fd) < 0) {
            continue;
        }

        if (util_is_std_fileno(fd) || fd == fddir || fd == fd_to_ignore) {
            continue;
        }

        if (closeall) {
            if (fd >= 0) {
                close(fd);
                fd = -1;
            }
            if (directory != NULL) {
                closedir(directory);
                directory = NULL;
            }
            goto restart;
        }
    }

    closedir(directory);
    return 0;
}

static int sig_num(const char *sig)
{
    int n;

    if (util_safe_int(sig, &n) < 0) {
        return -1;
    }

    return n;
}

int util_sig_parse(const char *sig_name)
{
    size_t n;
    const struct signame signames[] = SIGNAL_MAP_DEFAULT;

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

    if (isdigit(*sig_name)) {
        return sig_num(sig_name);
    } else if (strncasecmp(sig_name, "sig", 3) == 0) {
        sig_name += 3;
        for (n = 0; n < sizeof(signames) / sizeof(signames[0]); n++) {
            if (strcasecmp(signames[n].name, sig_name) == 0) {
                return signames[n].num;
            }
        }
    } else {
        for (n = 0; n < sizeof(signames) / sizeof(signames[0]); n++) {
            if (strcasecmp(signames[n].name, sig_name) == 0) {
                return signames[n].num;
            }
        }
    }

    return -1;
}

bool util_check_signal_valid(int sig)
{
    size_t i;
    const struct signame signames[] = SIGNAL_MAP_DEFAULT;

    for (i = 0; i < sizeof(signames) / sizeof(signames[0]); i++) {
        if (signames[i].num == sig) {
            return true;
        }
    }

    return false;
}

D
dogsheng 已提交
269 270 271 272 273 274 275 276 277 278 279 280
void *util_smart_calloc_s(size_t unit_size, size_t count)
{
    if (unit_size == 0) {
        return NULL;
    }

    if (count > (MAX_MEMORY_SIZE / unit_size)) {
        return NULL;
    }

    return calloc(count, unit_size);
}
O
overweight 已提交
281 282 283

void *util_common_calloc_s(size_t size)
{
D
dogsheng 已提交
284
    if (size == 0 || size > MAX_MEMORY_SIZE) {
O
overweight 已提交
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 672 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 709 710 711 712 713 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 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 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 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 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 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 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 1090 1091 1092 1093 1094
        return NULL;
    }

    return calloc((size_t)1, size);
}

char *util_strdup_s(const char *src)
{
    char *dst = NULL;

    if (src == NULL) {
        return NULL;
    }

    dst = strdup(src);
    if (dst == NULL) {
        abort();
    }

    return dst;
}

int wait_for_pid(pid_t pid)
{
    int st;
    int nret = 0;

rep:
    nret = waitpid(pid, &st, 0);
    if (nret == -1) {
        if (errno == EINTR) {
            goto rep;
        }
        return -1;
    }
    if (nret != pid) {
        goto rep;
    }
    if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) {
        return -1;
    }
    return 0;
}

int wait_for_pid_status(pid_t pid)
{
    int st;
    int nret = 0;
rep:
    nret = waitpid(pid, &st, 0);
    if (nret == -1) {
        if (errno == EINTR) {
            goto rep;
        }
        return -1;
    }

    if (nret != pid) {
        goto rep;
    }
    return st;
}

/*
 * if errmsg contain with 'not found'/'no such' error, set exit_code 127
 * if errmsg contain with 'permission denied' error, set exit_code 126
 */
void util_contain_errmsg(const char *errmsg, int *exit_code)
{
    if (errmsg == NULL || exit_code == NULL) {
        return;
    }

    if (strcasestr(errmsg, "executable file not found") || strcasestr(errmsg, "no such file or directory") ||
        strcasestr(errmsg, "system cannot find the file specified")) {
        *exit_code = 127;
    } else if (strcasestr(errmsg, "permission denied")) {
        *exit_code = 126;
    } else if (strcasestr(errmsg, "not a directory")) {
        *exit_code = 127;
    }

    return;
}

char *util_short_digest(const char *digest)
{
#define SHORT_DIGEST_LEN 12
    char short_digest[SHORT_DIGEST_LEN + 1] = { 0 };
    size_t start_pos = 0;

    if (digest == NULL) {
        return NULL;
    }
    if (!util_valid_digest(digest)) {
        ERROR("invalid digest %s", digest);
        return NULL;
    }

    if (strstr(digest, SHA256_PREFIX) == digest) {
        start_pos = strlen(SHA256_PREFIX);
    }

    if (memcpy_s(short_digest, sizeof(short_digest), digest + start_pos, SHORT_DIGEST_LEN) != EOK) {
        ERROR("Failed to memcpy memory");
        return NULL;
    }

    short_digest[SHORT_DIGEST_LEN] = 0;

    return util_strdup_s(short_digest);
}

char *util_full_digest(const char *digest)
{
    int nret = 0;
    char full_digest[PATH_MAX] = { 0 };

    if (digest == NULL) {
        ERROR("invalid NULL digest");
        return NULL;
    }

    nret = sprintf_s(full_digest, sizeof(full_digest), "%s%s", SHA256_PREFIX, digest);
    if (nret < 0) {
        ERROR("digest too long failed");
        return NULL;
    }

    return util_strdup_s(full_digest);
}

/* util_stat2proc() makes sure it can handle arbitrary executable file basenames
 * for `cmd', i.e. those with embedded whitespace or embedded ')'s.
 * Such names confuse %s (see scanf(3)), so the string is split and %39c
 * is used instead. (except for embedded ')' "(%[^)]c)" would work.
 */
proc_t *util_stat2proc(const char *s, size_t len)
{
    int num;
    proc_t *p = NULL;
    char *tmp = NULL;

    if (s == NULL) {
        return NULL;
    }
    if (len == 0) {
        return NULL;
    }

    tmp = strrchr(s, ')'); /* split into "PID (cmd" and "<rest>" */
    if (tmp == NULL) {
        return NULL;
    }
    *tmp = '\0'; /* replace trailing ')' with NUL */

    p = util_common_calloc_s(sizeof(proc_t));
    if (p == NULL) {
        return NULL;
    }

    /* parse these two strings separately, skipping the leading "(". */
    /* comm[16] in kernel */
    num = sscanf_s(s, "%d (%15c", &p->pid, p->cmd, 16);
    if (num != 2) {
        ERROR("Call sscanf error: %s", errno ? strerror(errno) : "");
        free(p);
        return NULL;
    }
    num = sscanf_s(tmp + 2, /* skip space after ')' too */
                   "%c "
                   "%d %d %d %d %d "
                   "%lu %lu %lu %lu %lu "
                   "%Lu %Lu %Lu %Lu " /* utime stime cutime cstime */
                   "%ld %ld %ld %ld "
                   "%Lu ", /* start_time */
                   &p->state, 1, &p->ppid, &p->pgrp, &p->session, &p->tty, &p->tpgid, &p->flags, &p->min_flt,
                   &p->cmin_flt, &p->maj_flt, &p->cmaj_flt, &p->utime, &p->stime, &p->cutime, &p->cstime, &p->priority,
                   &p->nice, &p->timeout, &p->it_real_value, &p->start_time);
    if (num != 20) { // max arg to read
        ERROR("Call sscanf error: %s", errno ? strerror(errno) : "");
        free(p);
        return NULL;
    }

    if (p->tty == 0) {
        p->tty = -1; /* the old notty val, update elsewhere bef. moving to 0 */
    }
    return p;
}

bool util_process_alive(pid_t pid, unsigned long long start_time)
{
    int sret = 0;
    bool alive = true;
    proc_t *pid_info = NULL;
    char filename[PATH_MAX] = { 0 };
    char sbuf[1024] = { 0 }; /* bufs for stat */

    if (pid == 0) {
        return false;
    }

    sret = kill(pid, 0);
    if (sret < 0 && errno == ESRCH) {
        return false;
    }

    sret = sprintf_s(filename, sizeof(filename), "/proc/%d/stat", pid);
    if (sret < 0 || (unsigned int)sret >= sizeof(filename)) {
        ERROR("Failed to sprintf filename");
        goto out;
    }

    if ((util_file2str(filename, sbuf, sizeof(sbuf))) == -1) {
        ERROR("Failed to read pidfile %s", filename);
        alive = false;
        goto out;
    }

    pid_info = util_stat2proc(sbuf, sizeof(sbuf));
    if (pid_info == NULL) {
        ERROR("Failed to get proc stat info");
        alive = false;
        goto out;
    }

    if (start_time != pid_info->start_time) {
        alive = false;
    }
out:
    free(pid_info);
    return alive;
}

static void set_stderr_buf(char **stderr_buf, const char *format, ...)
{
    int ret = 0;
    char errbuf[BUFSIZ + 1] = { 0 };
    char *jerr = NULL;

    UTIL_FREE_AND_SET_NULL(*stderr_buf);

    va_list argp;
    va_start(argp, format);

    ret = vsprintf_s(errbuf, BUFSIZ, format, argp);
    va_end(argp);
    if (ret < 0) {
        return;
    }

    *stderr_buf = json_marshal_string(errbuf, strlen(errbuf), NULL, &jerr);
    if (*stderr_buf == NULL) {
        *stderr_buf = util_strdup_s(errbuf);
    }
    free(jerr);
}

static int open_devnull(void)
{
    int fd = util_open("/dev/null", O_RDWR, 0);
    if (fd < 0) {
        ERROR("Can't open /dev/null");
    }

    return fd;
}

static int null_stdin(void)
{
    int ret = -1;
    int fd = -1;

    fd = open_devnull();
    if (fd >= 0) {
        ret = dup2(fd, STDIN_FILENO);
        close(fd);
        if (ret < 0) {
            return -1;
        }
    }

    return ret;
}

static inline bool deal_with_result_of_waitpid_nomsg(char **stderr_msg, size_t errmsg_len)
{
    if (*stderr_msg == NULL || strlen(*stderr_msg) == 0 || errmsg_len == 0) {
        return true;
    }
    return false;
}

static bool deal_with_result_of_waitpid(int status, char **stderr_msg, size_t errmsg_len)
{
    int signal;
    bool nomsg = false;

    if (stderr_msg == NULL) {
        ERROR("Invalid arguments");
        return false;
    }

    nomsg = deal_with_result_of_waitpid_nomsg(stderr_msg, errmsg_len);

    if (status < 0) {
        if (nomsg) {
            set_stderr_buf(stderr_msg, "Failed to wait exec cmd process");
        }
        return false;
    }

    if (WIFEXITED(status)) {
        if (WEXITSTATUS(status) == 0) {
            return true;
        }
        if (nomsg) {
            set_stderr_buf(stderr_msg, "Command exit with status: %d", WEXITSTATUS(status));
        }
    } else if (WIFSIGNALED((unsigned int)status)) {
        signal = WTERMSIG(status);
        if (nomsg) {
            set_stderr_buf(stderr_msg, "Command exit with signal: %d", signal);
        }
    } else if (WIFSTOPPED(status)) {
        signal = WSTOPSIG(status);
        if (nomsg) {
            set_stderr_buf(stderr_msg, "Command stop with signal: %d", signal);
        }
    } else {
        if (nomsg) {
            set_stderr_buf(stderr_msg, "Command exit with unknown status: %d", status);
        }
    }

    return false;
}

static void marshal_stderr_msg(char **buffer, size_t *real_size)
{
    char *jerr = NULL;
    char *tmp_err = NULL;
    char *stderr_buffer = *buffer;
    size_t stderr_real_size = *real_size;

    if (stderr_buffer != NULL && strlen(stderr_buffer) > 0 && stderr_real_size > 0) {
        tmp_err = json_marshal_string(stderr_buffer, strlen(stderr_buffer), NULL, &jerr);
        if (tmp_err != NULL) {
            free(stderr_buffer);
            *buffer = tmp_err;
            *real_size = strlen(tmp_err);
        }
        free(jerr);
    }
}

bool util_exec_top_cmd(exec_top_func_t cb_func, char **args, const char *pid_args, size_t args_len, char **stdout_msg,
                       char **stderr_msg)
{
    bool ret = false;
    char *stdout_buffer = NULL;
    char *stderr_buffer = NULL;
    size_t stdout_buf_size = 0;
    size_t stderr_buf_size = 0;
    size_t stdout_real_size = 0;
    size_t stderr_real_size = 0;
    int stdout_close_flag = 0;
    int stderr_close_flag = 0;
    int err_fd[2] = { -1, -1 };
    int out_fd[2] = { -1, -1 };
    pid_t pid = 0;
    int status = 0;

    if (pipe2(err_fd, O_CLOEXEC | O_NONBLOCK) != 0) {
        ERROR("Failed to create pipe");
        set_stderr_buf(&stderr_buffer, "Failed to create pipe");
        goto out;
    }
    if (pipe2(out_fd, O_CLOEXEC | O_NONBLOCK) != 0) {
        ERROR("Failed to create pipe");
        set_stderr_buf(&stderr_buffer, "Failed to create pipe");
        close(err_fd[0]);
        close(err_fd[1]);
        goto out;
    }

    pid = fork();
    if (pid == (pid_t) - 1) {
        ERROR("Failed to fork()");
        set_stderr_buf(&stderr_buffer, "Failed to fork()");
        close(err_fd[0]);
        close(err_fd[1]);
        close(out_fd[0]);
        close(out_fd[1]);
        goto out;
    }

    if (pid == (pid_t)0) {
        int nret = 0;
        nret = null_stdin();
        if (nret < 0) {
            WARN("Failed to set stdin to /dev/null");
        }

        // child process, dup2 out_fd[1] to stdout
        close(out_fd[0]);
        dup2(out_fd[1], STDOUT_FILENO);

        // child process, dup2 err_fd[1] to stderr
        close(err_fd[0]);
        dup2(err_fd[1], STDERR_FILENO);

        /* become session leader */
        nret = setsid();
        if (nret < 0) {
            COMMAND_ERROR("Failed to set process %d as group leader", getpid());
        }

        cb_func(args, pid_args, args_len);
    }

    close(err_fd[1]);
    close(out_fd[1]);

    for (;;) {
        if (stdout_close_flag == 0) {
            stdout_close_flag = util_read_pipe(out_fd[0], &stdout_buffer, &stdout_buf_size, &stdout_real_size);
        }
        if (stderr_close_flag == 0) {
            stderr_close_flag = util_read_pipe(err_fd[0], &stderr_buffer, &stderr_buf_size, &stderr_real_size);
        }
        if (stdout_close_flag != 0 && stderr_close_flag != 0) {
            break;
        }
        usleep_nointerupt(1000);
    }

    marshal_stderr_msg(&stderr_buffer, &stderr_real_size);

    status = wait_for_pid_status(pid);

    ret = deal_with_result_of_waitpid(status, &stderr_buffer, stderr_real_size);

    close(err_fd[0]);
    close(out_fd[0]);
out:
    *stdout_msg = stdout_buffer;
    *stderr_msg = stderr_buffer;
    return ret;
}

static void close_pipes_fd(int *pipes, size_t pipe_size)
{
    size_t i = 0;

    for (i = 0; i < pipe_size; i++) {
        if (pipes[i] >= 0) {
            close(pipes[i]);
            pipes[i] = -1;
        }
    }
}

bool util_exec_cmd(exec_func_t cb_func, void *args, const char *stdin_msg, char **stdout_msg, char **stderr_msg)
{
    bool ret = false;
    char *stdout_buffer = NULL;
    char *stderr_buffer = NULL;
    size_t stdout_buf_size = 0;
    size_t stderr_buf_size = 0;
    size_t stdout_real_size = 0;
    size_t stderr_real_size = 0;
    int stdout_close_flag = 0;
    int stderr_close_flag = 0;
    int err_fd[2] = { -1, -1 };
    int out_fd[2] = { -1, -1 };
    int in_fd[2] = {-1, -1};
    pid_t pid = 0;
    int status = 0;

    if (pipe2(in_fd, O_CLOEXEC | O_NONBLOCK) != 0) {
        ERROR("Failed to create stdin pipe");
        set_stderr_buf(&stderr_buffer, "Failed to create stdin pipe");
        goto out;
    }

    if (pipe2(err_fd, O_CLOEXEC | O_NONBLOCK) != 0) {
        ERROR("Failed to create pipe");
        set_stderr_buf(&stderr_buffer, "Failed to create pipe");
        close_pipes_fd(in_fd, 2);
        goto out;
    }
    if (pipe2(out_fd, O_CLOEXEC | O_NONBLOCK) != 0) {
        ERROR("Failed to create pipe");
        set_stderr_buf(&stderr_buffer, "Failed to create pipe");
        close_pipes_fd(in_fd, 2);
        close_pipes_fd(err_fd, 2);
        goto out;
    }

    pid = fork();
    if (pid == (pid_t) - 1) {
        ERROR("Failed to fork()");
        set_stderr_buf(&stderr_buffer, "Failed to fork()");
        close_pipes_fd(in_fd, 2);
        close_pipes_fd(err_fd, 2);
        close_pipes_fd(out_fd, 2);
        goto out;
    }

    if (pid == (pid_t)0) {
        int nret = 0;

        close(in_fd[1]);
        if (in_fd[0] != STDIN_FILENO) {
            dup2(in_fd[0], STDIN_FILENO);
        } else {
            if (fcntl(in_fd[0], F_SETFD, 0) != 0) {
                fprintf(stderr, "Failed to remove FD_CLOEXEC from fd.");
                exit(127);
            }
        }
        close(in_fd[0]);

        // child process, dup2 out_fd[1] to stdout
        close(out_fd[0]);
        dup2(out_fd[1], STDOUT_FILENO);

        // child process, dup2 err_fd[1] to stderr
        close(err_fd[0]);
        dup2(err_fd[1], STDERR_FILENO);

        /* become session leader */
        nret = setsid();
        if (nret < 0) {
            COMMAND_ERROR("Failed to set process %d as group leader", getpid());
        }

        cb_func(args);
    }

    /* parent */
    close(err_fd[1]);
    err_fd[1] = -1;
    close(out_fd[1]);
    out_fd[1] = -1;

    close(in_fd[0]);
    in_fd[0] = -1;
    if (stdin_msg != NULL) {
        size_t len = strlen(stdin_msg);
        if (util_write_nointr(in_fd[1], stdin_msg, len) != len) {
            WARN("Write instr: %s failed", stdin_msg);
        }
    }
    close(in_fd[1]);
    in_fd[1] = -1;

    for (;;) {
        if (stdout_close_flag == 0) {
            stdout_close_flag = util_read_pipe(out_fd[0], &stdout_buffer, &stdout_buf_size, &stdout_real_size);
        }
        if (stderr_close_flag == 0) {
            stderr_close_flag = util_read_pipe(err_fd[0], &stderr_buffer, &stderr_buf_size, &stderr_real_size);
        }
        if (stdout_close_flag != 0 && stderr_close_flag != 0) {
            break;
        }
        usleep_nointerupt(1000);
    }

    marshal_stderr_msg(&stderr_buffer, &stderr_real_size);

    status = wait_for_pid_status(pid);

    ret = deal_with_result_of_waitpid(status, &stderr_buffer, stderr_real_size);

    close(err_fd[0]);
    close(out_fd[0]);
out:
    *stdout_msg = stdout_buffer;
    *stderr_msg = stderr_buffer;
    return ret;
}

char **get_backtrace(void)
{
#define BACKTRACE_SIZE 16
    int addr_cnts;
    void *buffer[BACKTRACE_SIZE];
    char **syms = NULL;

    addr_cnts = backtrace(buffer, BACKTRACE_SIZE);
    if (addr_cnts <= 0) {
        return NULL;
    }

    syms = backtrace_symbols(buffer, addr_cnts);
    if (syms == NULL) {
        return NULL;
    }

    return syms;
}

static long long get_time_unit(int unit)
{
    long long u[255] = { 0 };

    u['M'] = Time_Milli;
    u['s'] = Time_Second;
    u['m'] = Time_Minute;
    u['h'] = Time_Hour;

    return u[unit];
}

static int get_time_ns(long long *pns, long long unit)
{
    if (unit == 0) {
        return -1;
    }

    if (INT64_MAX / *pns >= unit) {
        *pns *= unit;
        return 0;
    }

    return -1;
}

int util_parse_time_str_to_nanoseconds(const char *value, int64_t *nanoseconds)
{
    int ret = 0;
    long long tmp = 0;
    char unit = 0;
    size_t len = 0;
    char *num_str = NULL;

    if (value == NULL || nanoseconds == NULL) {
        return -1;
    }

    if (util_reg_match("^([0-9]+)+(ms|s|m|h)$", value) != 0) {
        return -1;
    }
    num_str = util_strdup_s(value);
    len = strlen(value);

    if (strstr(value, "ms") == NULL) {
        unit = *(value + len - 1);
        *(num_str + len - 1) = '\0';
    } else {
        unit = 'M';
        *(num_str + len - 2) = '\0';
    }
    ret = util_safe_llong(num_str, &tmp);
    if (ret < 0) {
        ERROR("Illegal unsigned integer: %s", num_str);
        ret = -1;
        goto out;
    }
    if (tmp == 0) {
        goto out;
    }

    ret = get_time_ns(&tmp, get_time_unit(unit));
    if (ret != 0) {
        ERROR("failed get nano seconds for %s", num_str);
    }
    *nanoseconds = (int64_t)tmp;

out:
    free(num_str);
    return ret;
}

/* isulad: get starttime of process pid */
proc_t *util_get_process_proc_info(pid_t pid)
{
    int sret = 0;
    proc_t *pid_info = NULL;
    char filename[PATH_MAX] = { 0 };
    char sbuf[1024] = { 0 }; /* bufs for stat */

    sret = sprintf_s(filename, sizeof(filename), "/proc/%d/stat", pid);
    if (sret < 0 || (unsigned int)sret >= sizeof(filename)) {
        ERROR("Failed to sprintf filename");
        goto out;
    }

    if ((util_file2str(filename, sbuf, sizeof(sbuf))) == -1) {
        ERROR("Failed to read pidfile %s", filename);
        goto out;
    }

    pid_info = util_stat2proc(sbuf, sizeof(sbuf));
    if (pid_info == NULL) {
        ERROR("Failed to get proc stat info");
        goto out;
    }

out:
    return pid_info;
}

int util_env_set_val(char ***penv, const size_t *penv_len, const char *key, size_t key_len, const char *newkv)
{
    size_t i = 0;
    char **env = NULL;
    size_t env_len = 0;

    if (penv == NULL || penv_len == NULL || key == NULL || newkv == NULL) {
        return -1;
    }

    env = *penv;
    env_len = *penv_len;

    for (i = 0; i < env_len; i++) {
        size_t elen = strlen(env[i]);
        if (key_len < elen && (strncmp(key, env[i], key_len) == 0) && (env[i][key_len] == '=')) {
            free(env[i]);
            env[i] = util_strdup_s(newkv);
            if (env[i] == NULL) {
                ERROR("out of memory");
                return -1;
            }
            return 0;
        }
    }

    /* can not find key env, return error. */
    return -1;
}

int util_env_insert(char ***penv, size_t *penv_len, const char *key, size_t key_len, const char *newkv)
{
    char **env = NULL;
    size_t env_len = 0;
    char **temp = NULL;
    int ret = 0;

    if (penv == NULL || penv_len == NULL || key == NULL || newkv == NULL) {
        return -1;
    }

    if (util_env_set_val(penv, penv_len, key, key_len, newkv) == 0) {
        return 0;
    }

    env = *penv;
    env_len = *penv_len;

    if (env_len > (SIZE_MAX / sizeof(char *)) - 1) {
        ERROR("Failed to realloc memory for envionment variables");
        return -1;
    }

    ret = mem_realloc((void **)(&temp), (env_len + 1) * sizeof(char *), env, env_len * sizeof(char *));
    if (ret != 0) {
        ERROR("Failed to realloc memory for envionment variables");
        return -1;
    }

    env = temp;
    env[env_len] = util_strdup_s(newkv);
    env_len++;

    *penv = env;
    *penv_len = env_len;
    return 0;
}

char *util_env_get_val(char **env, size_t env_len, const char *key, size_t key_len)
{
    size_t i = 0;

    if (key == NULL || env == NULL) {
        return NULL;
    }

    for (i = 0; i < env_len; i++) {
        size_t elen = strlen(env[i]);
        if (key_len < elen && !strncmp(key, env[i], key_len) && env[i][key_len] == '=') {
            return util_strdup_s(env[i] + key_len + 1);
        }
    }

    return NULL;
}

int util_parse_user_remap(const char *user_remap, unsigned int *host_uid, unsigned int *host_gid,
                          unsigned int *size)
{
    int ret = 0;
    size_t args_len = 0;
    char **items = NULL;

    if (user_remap == NULL || host_uid == NULL || host_gid == NULL || size == NULL) {
        COMMAND_ERROR("Out of memory");
        return -1;
    }
    items = util_string_split(user_remap, ':');
    if (items == NULL) {
        COMMAND_ERROR("split user remap '%s' failed", user_remap);
        ret = -1;
        goto out;
    }
Z
zhuchunyi 已提交
1095
    args_len = util_array_len((const char **)items);
O
overweight 已提交
1096 1097 1098 1099 1100 1101 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 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 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363

    switch (args_len) {
        case 3:
            ret = util_safe_uint(items[0], host_uid);
            if (ret) {
                COMMAND_ERROR("Invalid host uid for '%s', uid must be unsigned int", user_remap);
                break;
            }
            ret = util_safe_uint(items[1], host_gid);
            if (ret) {
                COMMAND_ERROR("Invalid host gid for '%s', gid must be unsigned int", user_remap);
                break;
            }
            ret = util_safe_uint(items[2], size);
            if (ret) {
                COMMAND_ERROR("Invalid id offset for '%s', offset must be unsigned int", user_remap);
                break;
            }
            if (*size > MAX_ID_OFFSET || *size == 0) {
                COMMAND_ERROR("Invalid id offset for '%s', offset must be greater than 0 and less than %d", user_remap,
                              MAX_ID_OFFSET);
                ret = -1;
                break;
            }
            break;
        default:
            COMMAND_ERROR("Invalid user remap specification '%s'. unsupported format", user_remap);
            ret = -1;
            break;
    }

out:
    util_free_array(items);
    return ret;
}

char *util_str_token(char **input, const char *delimiter)
{
    char *str = NULL;
    char *delimiter_found = NULL;
    char *tok = NULL;
    size_t tok_length = 0;

    if (input == NULL || delimiter == NULL) {
        return NULL;
    }

    str = *input;

    if (str == NULL) {
        return NULL;
    }
    delimiter_found = strstr(str, delimiter);
    if (delimiter_found != NULL) {
        tok_length = delimiter_found - str;
    } else {
        tok_length = strlen(str);
    }
    tok = strndup(str, tok_length);
    if (tok == NULL) {
        ERROR("strndup failed");
        return NULL;
    }
    *input = delimiter_found != NULL ? delimiter_found + strlen(delimiter) : NULL;
    return tok;
}

bool pid_max_kernel_namespaced()
{
    bool ret = false;
    FILE *fp = NULL;
    char *pline = NULL;
    size_t length = 0;

    fp = util_fopen("/proc/kallsyms", "r");
    if (fp == NULL) {
        SYSERROR("Failed to open /proc/kallsyms");
        return ret;
    }
    while (getline(&pline, &length, fp) != -1) {
        if (strstr(pline, "proc_dointvec_pidmax") != NULL) {
            ret = true;
            goto out;
        }
    }
out:
    fclose(fp);
    free(pline);
    return ret;
}

bool check_sysctl_valid(const char *sysctl_key)
{
    size_t i = 0;
    size_t full_keys_len = 0;
    size_t key_prefixes_len = 0;
    const char *sysctl_full_keys[] = {
        "kernel.msgmax", "kernel.msgmnb", "kernel.msgmni", "kernel.sem",
        "kernel.shmall", "kernel.shmmax", "kernel.shmmni", "kernel.shm_rmid_forced"
    };
    const char *sysctl_key_prefixes[] = { "net.", "fs.mqueue." };

    if (sysctl_key == NULL) {
        return false;
    }

    full_keys_len = sizeof(sysctl_full_keys) / sizeof(char *);
    key_prefixes_len = sizeof(sysctl_key_prefixes) / sizeof(char *);

    for (i = 0; i < full_keys_len; i++) {
        if (strcmp(sysctl_full_keys[i], sysctl_key) == 0) {
            return true;
        }
    }
    for (i = 0; i < key_prefixes_len; i++) {
        if (strncmp(sysctl_key_prefixes[i], sysctl_key, strlen(sysctl_key_prefixes[i])) == 0) {
            return true;
        }
    }
    return false;
}

void free_sensitive_string(char *str)
{
    if (!util_valid_str(str)) {
        goto out;
    }

    if (memset_s(str, strlen(str), 0, strlen(str)) != EOK) {
        ERROR("Failed to memset sensitive string memory");
    }

out:
    free(str);
}

void memset_sensitive_string(char *str)
{
    if (!util_valid_str(str)) {
        return;
    }

    if (memset_s(str, strlen(str), 0, strlen(str)) != EOK) {
        ERROR("Failed to memset sensitive string memory");
    }
}

static char *get_mtpoint(const char *line)
{
    int i;
    const char *tmp = NULL;
    char *pend = NULL;
    char *sret = NULL;
    size_t len;

    if (line == NULL) {
        goto err_out;
    }

    tmp = line;

    for (i = 0; i < 4; i++) {
        tmp = strchr(tmp, ' ');
        if (tmp == NULL) {
            goto err_out;
        }
        tmp++;
    }
    pend = strchr(tmp, ' ');
    if ((pend == NULL) || pend == tmp) {
        goto err_out;
    }

    /* stuck a \0 after the mountpoint */
    len = (size_t)(pend - tmp);
    sret = util_common_calloc_s(len + 1);
    if (sret == NULL) {
        goto err_out;
    }
    if (memcpy_s(sret, len + 1, tmp, len) != EOK) {
        free(sret);
        sret = NULL;
        goto err_out;
    }
    sret[len] = '\0';

err_out:
    return sret;
}

bool detect_mount(const char *path)
{
    FILE *fp = NULL;
    char *line = NULL;
    char *mountpoint = NULL;
    size_t length = 0;
    bool bret = false;

    fp = util_fopen("/proc/self/mountinfo", "r");
    if (fp == NULL) {
        ERROR("Failed opening /proc/self/mountinfo");
        return false;
    }

    while (getline(&line, &length, fp) != -1) {
        mountpoint = get_mtpoint(line);
        if (mountpoint == NULL) {
            INFO("Error reading mountinfo: bad line '%s'", line);
            continue;
        }
        if (strcmp(mountpoint, path) == 0) {
            free(mountpoint);
            bret = true;
            goto out;
        }
        free(mountpoint);
    }
out:
    fclose(fp);
    free(line);
    return bret;
}

static int set_echo_back(bool echo_back)
{
    struct termios old, new;

    if (tcgetattr(STDIN_FILENO, &old)) {
        ERROR("get tc attribute failed: %s\n", strerror(errno));
        return -1;
    }

    new = old;

    if (echo_back) {
        new.c_lflag |= ECHO | ICANON;
    } else {
        new.c_lflag &= ~(ECHO | ICANON);
    }

    if (tcsetattr(STDIN_FILENO, TCSANOW, &new)) {
        ERROR("set tc attribute failed: %s\n", strerror(errno));
        return -1;
    }

    return 0;
}

int util_input_notty(char *buf, size_t maxlen)
{
    size_t i = 0;
    int ret = 0;

    for (i = 0; i < maxlen; i++) {
        int c = getchar();
        if (c == EOF || c == '\n') {
            break;
        }
        if (c < 0) {
            ret = -1;
            break;
        }
        buf[i] = (char) c;
    }

    return ret ? ret : (int)i;
}

Z
zhuchunyi 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
int util_input_readall(char *buf, size_t maxlen)
{
    size_t i = 0;
    int ret = 0;

    for (;;) {
        int c = getchar();
        if (c == EOF) {
            break;
        }
        if (c < 0) {
            ret = -1;
            break;
        }
        // Skip chars larger than maxlen
        if (i + 1 >= maxlen) {
            continue;
        }
        buf[i] = (char) c;
        i++;
    }
    buf[i] = 0;

    // Strip last '\n'
    if (i > 0  && buf[i - 1] == '\n') {
        buf[i - 1] = 0;
        i--;
    }
    // Strip last '\r'
    if (i > 0  && buf[i - 1] == '\r') {
        buf[i - 1] = 0;
        i--;
    }

    return ret ? ret : (int)i;
}

O
overweight 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448
static int util_input(char *buf, size_t maxlen, bool echo_back)
{
    int ret = 0;

    if (set_echo_back(echo_back)) {
        return -1;
    }

    ret = util_input_notty(buf, maxlen);

    if (set_echo_back(true)) {
        return -1;
    }

    return ret;
}

// Get input from stdin, echo back if get any charactor.
int util_input_echo(char *buf, size_t maxlen)
{
    return util_input(buf, maxlen, true);
}

// Get input from stdin, no echo back.
int util_input_noecho(char *buf, size_t maxlen)
{
    return util_input(buf, maxlen, false);
}

void usleep_nointerupt(unsigned long usec)
{
#define SECOND_TO_USECOND_MUTIPLE 1000000
    int ret = 0;
    struct timespec request = { 0 };
    struct timespec remain = { 0 };
    if (usec == 0) {
        return;
    }

    request.tv_sec = (time_t)(usec / SECOND_TO_USECOND_MUTIPLE);
    request.tv_nsec = (long)((usec % SECOND_TO_USECOND_MUTIPLE) * 1000);

    do {
        ret = nanosleep(&request, &remain);
        request = remain;
    } while (ret == -1 && errno == EINTR);
}