utils_file.c 36.0 KB
Newer Older
O
overweight 已提交
1 2
/******************************************************************************
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2019. 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
O
overweight 已提交
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.
O
overweight 已提交
11 12 13 14 15 16 17
 * Author: tanyifeng
 * Create: 2018-11-1
 * Description: provide container utils functions
 *******************************************************************************/

#define _GNU_SOURCE
#include "utils_file.h"
18

O
overweight 已提交
19 20 21
#include <string.h>
#include <errno.h>
#include <stdio.h>
O
openeuler-iSula 已提交
22
#include <stdlib.h>
O
overweight 已提交
23 24 25
#include <unistd.h>
#include <sys/param.h>
#include <sys/stat.h>
W
wujing 已提交
26 27
#include <sys/ioctl.h>
#include <linux/fs.h>
O
overweight 已提交
28 29
#include <regex.h>
#include <dirent.h>
30 31
#include <fcntl.h>
#include <limits.h>
O
overweight 已提交
32 33

#include "constants.h"
H
haozi007 已提交
34
#include "isula_libutils/log.h"
O
overweight 已提交
35 36
#include "utils.h"
#include "path.h"
L
lifeng68 已提交
37
#include "map.h"
38 39
#include "utils_array.h"
#include "utils_string.h"
L
lifeng68 已提交
40

41 42
static void do_calculate_dir_size_without_hardlink(const char *dirpath, int recursive_depth, int64_t *total_size,
                                                   int64_t *total_inode, map_t *map);
O
overweight 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

bool util_dir_exists(const char *path)
{
    struct stat s;
    int nret;

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

    nret = stat(path, &s);
    if (nret < 0) {
        return false;
    }

    return S_ISDIR(s.st_mode);
}

G
gaohuatao 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
// This function is identical to "util_file_exists",except that if f is a symbolic file, return true
bool util_fileself_exists(const char *f)
{
    struct stat buf;
    int nret;

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

    nret = lstat(f, &buf);
    if (nret < 0) {
        return false;
    }
    return true;
}

// When f is a symbolic file, if the file that it refers to not exits ,return false
O
overweight 已提交
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
bool util_file_exists(const char *f)
{
    struct stat buf;
    int nret;

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

    nret = stat(f, &buf);
    if (nret < 0) {
        return false;
    }
    return true;
}

// Remove removes the named file or directory.
int util_path_remove(const char *path)
{
    int saved_errno;

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

L
lifeng68 已提交
104
    if (unlink(path) == 0 || errno == ENOENT) {
O
overweight 已提交
105 106 107
        return 0;
    }
    saved_errno = errno;
L
lifeng68 已提交
108
    if (rmdir(path) == 0 || errno == ENOENT) {
O
overweight 已提交
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
        return 0;
    }
    if (errno == ENOTDIR) {
        errno = saved_errno;
    }
    return -1;
}

ssize_t util_write_nointr(int fd, const void *buf, size_t count)
{
    ssize_t nret;

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

    for (;;) {
        nret = write(fd, buf, count);
        if (nret < 0 && errno == EINTR) {
            continue;
        } else {
            break;
        }
    }
    return nret;
}

ssize_t util_read_nointr(int fd, void *buf, size_t count)
{
    ssize_t nret;

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

    for (;;) {
        nret = read(fd, buf, count);
        if (nret < 0 && errno == EINTR) {
            continue;
        } else {
            break;
        }
    }

    return nret;
}

int util_mkdir_p(const char *dir, mode_t mode)
{
    const char *tmp_pos = NULL;
    const char *base = NULL;
    char *cur_dir = NULL;
    int len = 0;

    if (dir == NULL || strlen(dir) > PATH_MAX) {
        goto err_out;
    }

    tmp_pos = dir;
    base = dir;

    do {
        dir = tmp_pos + strspn(tmp_pos, "/");
        tmp_pos = dir + strcspn(dir, "/");
        len = (int)(dir - base);
        if (len <= 0) {
            break;
        }
        cur_dir = strndup(base, (size_t)len);
        if (cur_dir == NULL) {
            ERROR("strndup failed");
            goto err_out;
        }
        if (*cur_dir) {
            if (mkdir(cur_dir, mode) && (errno != EEXIST || !util_dir_exists(cur_dir))) {
                ERROR("failed to create directory '%s': %s", cur_dir, strerror(errno));
                goto err_out;
            }
        }
        UTIL_FREE_AND_SET_NULL(cur_dir);
    } while (tmp_pos != dir);

L
lifeng68 已提交
191 192 193 194
    if (chmod(base, mode) != 0) {
        SYSERROR("Failed to chmod for directory");
    }

O
overweight 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    return 0;
err_out:
    free(cur_dir);
    return -1;
}

static bool check_dir_valid(const char *dirpath, int recursive_depth, int *failure)
{
    if ((recursive_depth + 1) > MAX_PATH_DEPTH) {
        ERROR("Reach max path depth: %s", dirpath);
        *failure = 1;
        return false;
    }

    if (!util_dir_exists(dirpath)) {
        return false;
    }

    return true;
}

W
wujing 已提交
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
static int mark_file_mutable(const char *fname)
{
    int ret = 0;
    int fd = -EBADF;
    int attributes = 0;

    fd = open(fname, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
    if (fd < 0) {
        SYSERROR("Failed to open file to modify flags:%s", fname);
        return -1;
    }

    if (ioctl(fd, FS_IOC_GETFLAGS, &attributes) < 0) {
        SYSERROR("Failed to retrieve file flags");
        ret = -1;
        goto out;
    }

    attributes &= ~FS_IMMUTABLE_FL;

    if (ioctl(fd, FS_IOC_SETFLAGS, &attributes) < 0) {
        SYSERROR("Failed to set file flags");
        ret = -1;
        goto out;
    }

out:
    if (fd >= 0) {
        close(fd);
    }
    return ret;
}

O
overweight 已提交
249 250 251 252 253 254 255 256 257
static int recursive_rmdir_next_depth(struct stat fstat, const char *fname, int recursive_depth, int *saved_errno,
                                      int failure)
{
    if (S_ISDIR(fstat.st_mode)) {
        if (util_recursive_rmdir(fname, (recursive_depth + 1)) < 0) {
            failure = 1;
        }
    } else {
        if (unlink(fname) < 0) {
258
            ERROR("Failed to delete %s: %s", fname, strerror(errno));
O
overweight 已提交
259 260 261
            if (*saved_errno == 0) {
                *saved_errno = errno;
            }
W
wujing 已提交
262 263 264 265 266 267 268 269 270

            if (mark_file_mutable(fname) != 0) {
                ERROR("Failed to mark file mutable");
            }

            if (unlink(fname) < 0) {
                ERROR("Failed to delete \"%s\": %s", fname, strerror(errno));
                failure = 1;
            }
O
overweight 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        }
    }

    return failure;
}

static int recursive_rmdir_helper(const char *dirpath, int recursive_depth, int *saved_errno)
{
    int nret = 0;
    struct dirent *pdirent = NULL;
    DIR *directory = NULL;
    int failure = 0;
    char fname[MAXPATHLEN];

    directory = opendir(dirpath);
    if (directory == NULL) {
        ERROR("Failed to open %s", dirpath);
        return 1;
    }
    pdirent = readdir(directory);
    for (; pdirent != NULL; pdirent = readdir(directory)) {
        struct stat fstat;
O
openeuler-iSula 已提交
293
        int pathname_len;
O
overweight 已提交
294

O
openeuler-iSula 已提交
295
        if (!strcmp(pdirent->d_name, ".") || !strcmp(pdirent->d_name, "..")) {
O
overweight 已提交
296 297 298
            continue;
        }

O
openeuler-iSula 已提交
299
        (void)memset(fname, 0, sizeof(fname));
O
overweight 已提交
300

O
openeuler-iSula 已提交
301 302
        pathname_len = snprintf(fname, MAXPATHLEN, "%s/%s", dirpath, pdirent->d_name);
        if (pathname_len < 0 || pathname_len >= MAXPATHLEN) {
O
overweight 已提交
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
            ERROR("Pathname too long");
            failure = 1;
            continue;
        }

        nret = lstat(fname, &fstat);
        if (nret) {
            ERROR("Failed to stat %s", fname);
            failure = 1;
            continue;
        }

        failure = recursive_rmdir_next_depth(fstat, fname, recursive_depth, saved_errno, failure);
    }

    if (rmdir(dirpath) < 0 && errno != ENOENT) {
        if (*saved_errno == 0) {
            *saved_errno = errno;
        }
        ERROR("Failed to delete %s", dirpath);
        failure = 1;
    }

    nret = closedir(directory);
    if (nret) {
        ERROR("Failed to close directory %s", dirpath);
        failure = 1;
    }

    return failure;
}

W
wujing 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
static void run_force_rmdir(void *args)
{
    execvp(((char **)args)[0], (char **)args);
}

static int exec_force_rmdir_command(const char *dir)
{
    int ret = 0;
    char **args = NULL;
    char *stdout_msg = NULL;
    char *stderr_msg = NULL;

    if (dir == NULL) {
        ERROR("Directory path is NULL");
        return -1;
    }

L
lifeng68 已提交
352
    if (util_array_append(&args, "rm") != 0 || util_array_append(&args, "-rf") != 0 ||
W
wujing 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        util_array_append(&args, dir) != 0) {
        ERROR("Out of memory");
        ret = -1;
        goto free_out;
    }

    if (!util_exec_cmd(run_force_rmdir, args, NULL, &stdout_msg, &stderr_msg)) {
        ERROR("force rmdir failed, unexpected command output %s with error: %s", stdout_msg, stderr_msg);
        ret = -1;
        goto free_out;
    }

free_out:
    util_free_array(args);
    free(stdout_msg);
    free(stderr_msg);
    return ret;
}

O
overweight 已提交
372 373 374 375 376 377 378 379 380 381 382 383 384 385
int util_recursive_rmdir(const char *dirpath, int recursive_depth)
{
    int failure = 0;
    int saved_errno = 0;

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

    if (!check_dir_valid(dirpath, recursive_depth, &failure)) {
        goto err_out;
    }

    failure = recursive_rmdir_helper(dirpath, recursive_depth, &saved_errno);
W
wujing 已提交
386 387 388 389 390 391 392
    if (failure != 0) {
        INFO("Recursive delete dir failed. Try delete forcely with command");
        failure = exec_force_rmdir_command(dirpath);
        if (failure != 0) {
            ERROR("Recursive delete dir forcely with command failed");
        }
    }
O
overweight 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409

err_out:
    errno = saved_errno;
    return failure ? -1 : 0;
}

char *util_path_join(const char *dir, const char *file)
{
    int nret = 0;
    char path[PATH_MAX] = { 0 };
    char cleaned[PATH_MAX] = { 0 };

    if (dir == NULL || file == NULL) {
        ERROR("NULL dir or file failed");
        return NULL;
    }

O
openeuler-iSula 已提交
410 411
    nret = snprintf(path, PATH_MAX, "%s/%s", dir, file);
    if (nret < 0 || nret >= PATH_MAX) {
O
overweight 已提交
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
        ERROR("dir or file too long failed");
        return NULL;
    }

    if (cleanpath(path, cleaned, sizeof(cleaned)) == NULL) {
        ERROR("Failed to clean path: %s", path);
        return NULL;
    }

    return util_strdup_s(cleaned);
}

/*
 * if path do not exist, this function will create it.
 */
int util_ensure_path(char **confpath, const char *path)
{
    int err = -1;
    int fd;
    char real_path[PATH_MAX + 1] = { 0 };

    if (confpath == NULL || path == NULL) {
        return -1;
    }

    fd = util_open(path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, DEFAULT_SECURE_FILE_MODE);
    if (fd < 0 && errno != EEXIST) {
        ERROR("failed to open '%s'", path);
        goto err;
    }
    if (fd >= 0) {
        close(fd);
    }

    if (strlen(path) > PATH_MAX || NULL == realpath(path, real_path)) {
        ERROR("Failed to get real path: %s", path);
        goto err;
    }

    *confpath = util_strdup_s(real_path);

    err = EXIT_SUCCESS;

err:
    return err;
}

static void set_char_to_terminator(char *p)
{
    *p = '\0';
}

/*
 * @name is absolute path of this file.
 * make all directory in this absolute path.
 */
int util_build_dir(const char *name)
{
    char *n = NULL;
    char *p = NULL;
    char *e = NULL;
    int nret;

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

    n = util_strdup_s(name);

    if (n == NULL) {
        ERROR("Out of memory while creating directory '%s'.", name);
        return -1;
    }

    e = &n[strlen(n)];
    for (p = n + 1; p < e; p++) {
        if (*p != '/') {
            continue;
        }
        set_char_to_terminator(p);
        nret = mkdir(n, DEFAULT_SECURE_DIRECTORY_MODE);
        if (nret && (errno != EEXIST || !util_dir_exists(n))) {
            ERROR("failed to create directory '%s'.", n);
            free(n);
            return -1;
        }
        *p = '/';
    }
    free(n);
    return 0;
}

char *util_human_size(uint64_t val)
{
    int index = 0;
    int ret = 0;
    size_t len = 0;
    uint64_t ui = 0;
    char *out = NULL;
    char *uf[] = { "B", "KB", "MB", "GB" };

    ui = val;

    for (;;) {
        if (ui < 1024 || index >= 3) {
            break;
        }

        ui = (uint64_t)(ui / 1024);
        index++;
    }

L
LiuHao 已提交
524
    len = ISULAD_NUMSTRLEN64 + 2 + 1;
O
overweight 已提交
525 526 527 528 529 530
    out = util_common_calloc_s(len);
    if (out == NULL) {
        ERROR("Memory out");
        return NULL;
    }

O
openeuler-iSula 已提交
531 532
    ret = snprintf(out, len, "%llu%s", (unsigned long long)ui, uf[index]);
    if (ret < 0 || ret >= len) {
O
overweight 已提交
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        ERROR("Failed to print string");
        free(out);
        return NULL;
    }

    return out;
}

char *util_human_size_decimal(int64_t val)
{
    int nret = 0;
    int kb = 1024;
    int mb = kb * 1024;
    int gb = mb * 1024;
    char out[16] = { 0 }; /* 16 is enough, format like: 123.456 MB */

    if (val >= gb) {
O
openeuler-iSula 已提交
550
        nret = snprintf(out, sizeof(out), "%.3lf GB", ((double)val / gb));
O
overweight 已提交
551
    } else if (val >= mb) {
O
openeuler-iSula 已提交
552
        nret = snprintf(out, sizeof(out), "%.3lf MB", ((double)val / mb));
O
overweight 已提交
553
    } else if (val >= kb) {
O
openeuler-iSula 已提交
554
        nret = snprintf(out, sizeof(out), "%.3lf KB", ((double)val / kb));
O
overweight 已提交
555
    } else {
O
openeuler-iSula 已提交
556
        nret = snprintf(out, sizeof(out), "%lld B", (long long int)val);
O
overweight 已提交
557
    }
O
openeuler-iSula 已提交
558
    if (nret < 0 || nret >= sizeof(out)) {
O
overweight 已提交
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
        ERROR("Failed to print string");
        return NULL;
    }

    return util_strdup_s(out);
}

int util_open(const char *filename, int flags, mode_t mode)
{
    char rpath[PATH_MAX] = { 0x00 };

    if (cleanpath(filename, rpath, sizeof(rpath)) == NULL) {
        return -1;
    }
    if (mode) {
        return open(rpath, flags | O_CLOEXEC, mode);
    } else {
        return open(rpath, flags | O_CLOEXEC);
    }
}

FILE *util_fopen(const char *filename, const char *mode)
{
    unsigned int fdmode = 0;
    int f_fd = -1;
    int tmperrno;
    FILE *fp = NULL;
    char rpath[PATH_MAX] = { 0x00 };

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

    if (cleanpath(filename, rpath, sizeof(rpath)) == NULL) {
        ERROR("cleanpath failed");
        return NULL;
    }
    if (strncmp(mode, "a+", 2) == 0) {
        fdmode = O_RDWR | O_CREAT | O_APPEND;
    } else if (strncmp(mode, "a", 1) == 0) {
        fdmode = O_WRONLY | O_CREAT | O_APPEND;
    } else if (strncmp(mode, "w+", 2) == 0) {
        fdmode = O_RDWR | O_TRUNC | O_CREAT;
    } else if (strncmp(mode, "w", 1) == 0) {
        fdmode = O_WRONLY | O_TRUNC | O_CREAT;
    } else if (strncmp(mode, "r+", 2) == 0) {
        fdmode = O_RDWR;
    } else if (strncmp(mode, "r", 1) == 0) {
        fdmode = O_RDONLY;
    }

    fdmode |= O_CLOEXEC;

    f_fd = open(rpath, (int)fdmode, 0666);
    if (f_fd < 0) {
        return NULL;
    }

    fp = fdopen(f_fd, mode);
    tmperrno = errno;
    if (fp == NULL) {
        close(f_fd);
    }
    errno = tmperrno;
    return fp;
}

626 627 628
int util_gzip_compressed(const char *filename, bool *gzip)
{
#define GZIPHEADERLEN 3
L
lifeng68 已提交
629 630
    const char gzip_key[GZIPHEADERLEN] = { 0x1F, 0x8B, 0x08 };
    char data[GZIPHEADERLEN] = { 0 };
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
    size_t size_read = 0;
    int i = 0;
    FILE *f = NULL;
    int ret = 0;

    f = fopen(filename, "rb");
    if (f == NULL) {
        ERROR("Failed to open file %s: %s", filename, strerror(errno));
        return -1;
    }

    size_read = fread(data, 1, GZIPHEADERLEN, f);
    if ((0 == size_read && !feof(f)) || size_read > GZIPHEADERLEN) {
        ERROR("Failed to read file %s, size read %d", filename, (int)size_read);
        ret = -1;
        goto out;
    }

    if (size_read < GZIPHEADERLEN) {
        *gzip = false;
        goto out;
    }

    for (i = 0; i < GZIPHEADERLEN; i++) {
        if (data[i] != gzip_key[i]) {
            *gzip = false;
            goto out;
        }
    }
    *gzip = true;

out:
    fclose(f);
    f = NULL;

    return ret;
}

669
char *util_path_dir(const char *path)
O
overweight 已提交
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
{
    char *dir = NULL;
    int len = 0;
    int i = 0;

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

    len = (int)strlen(path);
    if (len == 0) {
        return util_strdup_s(".");
    }

    dir = util_strdup_s(path);

    for (i = len - 1; i > 0; i--) {
        if (dir[i] == '/') {
            dir[i] = 0;
            break;
        }
    }

694 695 696 697 698
    if (i == 0 && dir[0] == '/') {
        free(dir);
        return util_strdup_s("/");
    }

O
overweight 已提交
699 700 701
    return dir;
}

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
char *util_path_base(const char *path)
{
    char *dir = NULL;
    int len = 0;
    int i = 0;

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

    len = (int)strlen(path);
    if (len == 0) {
        return util_strdup_s(".");
    }

    dir = util_strdup_s(path);

    // strip last slashes
    for (i = len - 1; i >= 0; i--) {
        if (dir[i] != '/') {
            break;
        }
        dir[i] = '\0';
    }

    len = (int)strlen(dir);
    if (len == 0) {
        free(dir);
        return util_strdup_s("/");
    }

    for (i = len - 1; i >= 0; i--) {
        if (dir[i] == '/') {
            break;
        }
    }

    if (i < 0) {
        return dir;
    }

    char *result = util_strdup_s(&dir[i + 1]);
    free(dir);
    return result;
}

O
overweight 已提交
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
char *util_add_path(const char *path, const char *name)
{
    char *tmp_dir = NULL;
    char *new_path = NULL;

    if (path == NULL || name == NULL) {
        ERROR("invalid NULL param");
        return NULL;
    }

    tmp_dir = util_path_dir(path);
    new_path = util_path_join(tmp_dir, name);
    free(tmp_dir);

    return new_path;
}

/* note: This function can only read small text file. */
char *util_read_text_file(const char *path)
{
    char *buf = NULL;
    long len = 0;
    size_t readlen = 0;
    FILE *filp = NULL;
    const long max_size = 10 * 1024 * 1024; /* 10M */

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

    filp = util_fopen(path, "r");
    if (filp == NULL) {
782
        SYSERROR("open file %s failed", path);
O
overweight 已提交
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
        goto err_out;
    }

    if (fseek(filp, 0, SEEK_END)) {
        ERROR("Seek end failed");
        goto err_out;
    }

    len = ftell(filp);
    if (len > max_size) {
        ERROR("File to large!");
        goto err_out;
    }

    if (fseek(filp, 0, SEEK_SET)) {
        ERROR("Seek set failed");
        goto err_out;
    }

    buf = util_common_calloc_s((size_t)(len + 1));
    if (buf == NULL) {
        ERROR("out of memroy");
        goto err_out;
    }

    readlen = fread(buf, 1, (size_t)len, filp);
    if (((readlen < (size_t)len) && (!feof(filp))) || (readlen > (size_t)len)) {
        ERROR("Failed to read file %s, error: %s\n", path, strerror(errno));
        UTIL_FREE_AND_SET_NULL(buf);
        goto err_out;
    }

    buf[(size_t)len] = 0;

err_out:

    if (filp != NULL) {
        fclose(filp);
    }

    return buf;
}

int64_t util_file_size(const char *filename)
{
    struct stat st;

    if (filename == NULL) {
        ERROR("invalid NULL param");
        return -1;
    }

    if (stat(filename, &st)) {
        ERROR("stat file %s failed: %s", filename, strerror(errno));
        return -1;
    }

    return (int64_t)st.st_size;
}

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
int util_scan_subdirs(const char *directory, subdir_callback_t cb)
{
    DIR *dir = NULL;
    struct dirent *direntp = NULL;
    int ret = 0;

    if (directory == NULL || cb == NULL) {
        return -1;
    }

    dir = opendir(directory);
    if (dir == NULL) {
        ERROR("Failed to open directory: %s error:%s", directory, strerror(errno));
        return -1;
    }

    direntp = readdir(dir);
    for (; direntp != NULL; direntp = readdir(dir)) {
        if (strncmp(direntp->d_name, ".", 1) == 0) {
            continue;
        }

        if (!cb(directory, direntp)) {
            ERROR("Dealwith subdir: %s failed", direntp->d_name);
            ret = -1;
            break;
        }
    }

    closedir(dir);
    return ret;
}

O
overweight 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898
int util_list_all_subdir(const char *directory, char ***out)
{
    DIR *dir = NULL;
    struct dirent *direntp = NULL;
    char **names_array = NULL;
    char tmpdir[PATH_MAX] = { 0 };
    int nret;

    if (directory == NULL || out == NULL) {
        return -1;
    }

    dir = opendir(directory);
    if (dir == NULL) {
        ERROR("Failed to open directory: %s error:%s", directory, strerror(errno));
        return -1;
    }
    direntp = readdir(dir);
    for (; direntp != NULL; direntp = readdir(dir)) {
        if (strncmp(direntp->d_name, ".", 1) == 0) {
            continue;
        }

O
openeuler-iSula 已提交
899 900
        nret = snprintf(tmpdir, PATH_MAX, "%s/%s", directory, direntp->d_name);
        if (nret < 0 || nret >= PATH_MAX) {
O
overweight 已提交
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
            ERROR("Sprintf: %s failed", direntp->d_name);
            goto error_out;
        }
        if (!util_dir_exists(tmpdir)) {
            DEBUG("%s is not directory", direntp->d_name);
            continue;
        }
        if (util_array_append(&names_array, direntp->d_name)) {
            ERROR("Failed to append subdirectory array");
            goto error_out;
        }
    }

    closedir(dir);
    *out = names_array;
    return 0;

error_out:
    closedir(dir);
    util_free_array(names_array);
    names_array = NULL;
    return -1;
}

int util_file2str(const char *filename, char *buf, size_t len)
{
    int fd = -1;
    int num_read;

    if (filename == NULL || buf == NULL) {
        return -1;
    }

    fd = util_open(filename, O_RDONLY, 0);
    if (fd == -1) {
        return -1;
    }
    num_read = (int)read(fd, buf, len - 1);
    if (num_read <= 0) {
        num_read = -1;
    } else {
        buf[num_read] = 0;
    }
    close(fd);

    return num_read;
}

static int find_executable(const char *file)
{
    struct stat buf;
    int nret;

    nret = stat(file, &buf);
    if (nret < 0) {
        return errno;
    }
    if (!S_ISDIR(buf.st_mode) && (buf.st_mode & 0111) != 0) {
        return 0;
    }

    return EPERM;
}

char *look_path(const char *file, char **err)
{
    char *path_env = NULL;
    char *tmp = NULL;
    char *full_path = NULL;
    char *ret = NULL;
    char **paths = NULL;
    char **work = NULL;

    if (file == NULL || err == NULL) {
        return NULL;
    }

    /* if slash in file, directly use file and do not try PATH. */
    if (strings_contains_any(file, "/")) {
Z
zhuchunyi 已提交
980 981
        int en = find_executable(file);
        if (en == 0) {
O
overweight 已提交
982 983
            return util_strdup_s(file);
        }
Z
zhuchunyi 已提交
984
        if (asprintf(err, "find exec %s : %s", file, strerror(en)) < 0) {
O
overweight 已提交
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
            *err = util_strdup_s("Out of memory");
        }
        return NULL;
    }

    path_env = getenv("PATH");
    if (path_env == NULL) {
        *err = util_strdup_s("Not found PATH env");
        return NULL;
    }

    paths = util_string_split(path_env, ':');
    if (paths == NULL) {
        *err = util_strdup_s("Split PATH failed");
        goto free_out;
    }
    for (work = paths; work && *work; work++) {
        tmp = *work;
        if (strcmp("", tmp) == 0) {
            tmp = ".";
        }

        full_path = util_path_join(tmp, file);
        if (full_path == NULL) {
            *err = util_strdup_s("Out of memory");
            goto free_out;
        }
        if (find_executable(full_path) == 0) {
            ret = full_path;
            goto free_out;
        }
        UTIL_FREE_AND_SET_NULL(full_path);
    }

free_out:
    util_free_array(paths);
    return ret;
}

1024
int util_write_file(const char *fname, const char *content, size_t content_len, mode_t mode)
O
overweight 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
{
    int ret = 0;
    int dst_fd = -1;
    ssize_t len = 0;

    if (fname == NULL) {
        return -1;
    }
    if (content == NULL || content_len == 0) {
        return 0;
    }
1036
    dst_fd = util_open(fname, O_WRONLY | O_CREAT | O_TRUNC, mode);
O
overweight 已提交
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
    if (dst_fd < 0) {
        ERROR("Creat file: %s, failed: %s", fname, strerror(errno));
        ret = -1;
        goto free_out;
    }
    len = util_write_nointr(dst_fd, content, content_len);
    if (len < 0 || ((size_t)len) != content_len) {
        ret = -1;
        ERROR("Write file failed: %s", strerror(errno));
        goto free_out;
    }
free_out:
    if (dst_fd >= 0) {
        close(dst_fd);
    }
    return ret;
}

char *verify_file_and_get_real_path(const char *file)
{
#define MAX_FILE_SIZE (10 * SIZE_MB)
    char resolved_path[PATH_MAX] = { 0 };

    if (file == NULL) {
        return NULL;
    }
    if (realpath(file, resolved_path) == NULL) {
        ERROR("Failed to get realpath: %s , %s", resolved_path, strerror(errno));
        return NULL;
    }

    if (!util_file_exists(resolved_path)) {
        ERROR("%s not exist!", resolved_path);
        return NULL;
    }
    if (util_file_size(resolved_path) > MAX_FILE_SIZE) {
        ERROR("%s too large!", resolved_path);
        return NULL;
    }
    return util_strdup_s(resolved_path);
}

1079
int util_copy_file(const char *src_file, const char *dst_file, mode_t mode)
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
{
#define BUFSIZE 4096
    int ret = 0;
    char *nret = NULL;
    char real_src_file[PATH_MAX + 1] = { 0 };
    int src_fd = -1;
    int dst_fd = -1;
    char buf[BUFSIZE + 1] = { 0 };

    if (src_file == NULL || dst_file == NULL) {
        return ret;
    }
    nret = realpath(src_file, real_src_file);
    if (nret == NULL) {
        ERROR("real path: %s, return: %s", src_file, strerror(errno));
        ret = -1;
        return ret;
    }
    src_fd = util_open(real_src_file, O_RDONLY, CONFIG_FILE_MODE);
    if (src_fd < 0) {
        ERROR("Open src file: %s, failed: %s", real_src_file, strerror(errno));
        ret = -1;
        goto free_out;
    }
1104
    dst_fd = util_open(dst_file, O_WRONLY | O_CREAT | O_TRUNC, mode);
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
    if (dst_fd < 0) {
        ERROR("Creat file: %s, failed: %s", dst_file, strerror(errno));
        ret = -1;
        goto free_out;
    }
    while (true) {
        ssize_t len = util_read_nointr(src_fd, buf, BUFSIZE);
        if (len < 0) {
            ERROR("Read src file failed: %s", strerror(errno));
            ret = -1;
            goto free_out;
        } else if (len == 0) {
            break;
        }
        if (util_write_nointr(dst_fd, buf, (size_t)len) != len) {
            ERROR("Write file failed: %s", strerror(errno));
            ret = -1;
            goto free_out;
        }
    }

free_out:
    if (src_fd >= 0) {
        close(src_fd);
    }
    if (dst_fd >= 0) {
        close(dst_fd);
    }
    return ret;
}

1136 1137
static void recursive_cal_dir_size_helper(const char *dirpath, int recursive_depth, int64_t *total_size,
                                          int64_t *total_inode)
H
haozi007 已提交
1138
{
1139 1140 1141
    int nret = 0;
    struct dirent *pdirent = NULL;
    DIR *directory = NULL;
1142
    struct stat fstat;
1143
    char fname[MAXPATHLEN];
H
haozi007 已提交
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    // cal dir self node and size
    nret = lstat(dirpath, &fstat);
    if (nret != 0) {
        ERROR("Failed to stat directory %s", dirpath);
        return;
    }
    *total_size = *total_size + fstat.st_size;
    *total_inode = *total_inode + 1;

    // cal sub dirs node and size
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
    directory = opendir(dirpath);
    if (directory == NULL) {
        ERROR("Failed to open %s", dirpath);
        return;
    }
    pdirent = readdir(directory);
    for (; pdirent != NULL; pdirent = readdir(directory)) {
        int pathname_len;

        if (!strcmp(pdirent->d_name, ".") || !strcmp(pdirent->d_name, "..")) {
            continue;
        }

        (void)memset(fname, 0, sizeof(fname));

        pathname_len = snprintf(fname, MAXPATHLEN, "%s/%s", dirpath, pdirent->d_name);
        if (pathname_len < 0 || pathname_len >= MAXPATHLEN) {
            ERROR("Pathname too long");
            continue;
        }

        nret = lstat(fname, &fstat);
        if (nret) {
            ERROR("Failed to stat %s", fname);
            continue;
        }

        if (S_ISDIR(fstat.st_mode)) {
            int64_t subdir_size = 0;
            int64_t subdir_inode = 0;
            util_calculate_dir_size(fname, (recursive_depth + 1), &subdir_size, &subdir_inode);
            *total_size = *total_size + subdir_size;
            *total_inode = *total_inode + subdir_inode;
        } else {
            *total_size = *total_size + fstat.st_size;
            *total_inode = *total_inode + 1;
        }
H
haozi007 已提交
1192 1193
    }

1194 1195 1196
    nret = closedir(directory);
    if (nret) {
        ERROR("Failed to close directory %s", dirpath);
H
haozi007 已提交
1197 1198
    }

1199 1200
    return;
}
H
haozi007 已提交
1201

1202 1203 1204 1205 1206 1207 1208
void util_calculate_dir_size(const char *dirpath, int recursive_depth, int64_t *total_size, int64_t *total_inode)
{
    int64_t total_size_tmp = 0;
    int64_t total_inode_tmp = 0;

    if (dirpath == NULL) {
        return;
H
haozi007 已提交
1209 1210
    }

1211 1212 1213
    if ((recursive_depth + 1) > MAX_PATH_DEPTH) {
        ERROR("Reach max path depth: %s", dirpath);
        goto out;
H
haozi007 已提交
1214 1215
    }

1216 1217 1218
    if (!util_dir_exists(dirpath)) {
        ERROR("dir not exists: %s", dirpath);
        goto out;
H
haozi007 已提交
1219 1220
    }

1221 1222 1223 1224 1225 1226 1227
    recursive_cal_dir_size_helper(dirpath, recursive_depth, &total_size_tmp, &total_inode_tmp);

    if (total_size != NULL) {
        *total_size = total_size_tmp;
    }
    if (total_inode != NULL) {
        *total_inode = total_inode_tmp;
H
haozi007 已提交
1228 1229
    }

1230 1231
out:
    return;
H
haozi007 已提交
1232 1233
}

1234
static void recursive_cal_dir_size__without_hardlink_helper(const char *dirpath, int recursive_depth,
L
lifeng68 已提交
1235
                                                            int64_t *total_size, int64_t *total_inode, map_t *map)
L
lifeng68 已提交
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
{
    int nret = 0;
    struct dirent *pdirent = NULL;
    DIR *directory = NULL;
    char fname[MAXPATHLEN];

    directory = opendir(dirpath);
    if (directory == NULL) {
        ERROR("Failed to open %s", dirpath);
        return;
    }
    pdirent = readdir(directory);
    for (; pdirent != NULL; pdirent = readdir(directory)) {
        struct stat fstat;
        int pathname_len;

        if (!strcmp(pdirent->d_name, ".") || !strcmp(pdirent->d_name, "..")) {
            continue;
        }

        (void)memset(fname, 0, sizeof(fname));

        pathname_len = snprintf(fname, MAXPATHLEN, "%s/%s", dirpath, pdirent->d_name);
        if (pathname_len < 0 || pathname_len >= MAXPATHLEN) {
            ERROR("Pathname too long");
            continue;
        }

        nret = lstat(fname, &fstat);
        if (nret) {
            ERROR("Failed to stat %s", fname);
            continue;
        }

        if (S_ISDIR(fstat.st_mode)) {
            int64_t subdir_size = 0;
            int64_t subdir_inode = 0;
            do_calculate_dir_size_without_hardlink(fname, (recursive_depth + 1), &subdir_size, &subdir_inode, map);
            *total_size = *total_size + subdir_size;
            *total_inode = *total_inode + subdir_inode;
        } else {
1277
            if (map_search(map, (void *)(&(fstat.st_ino))) != NULL) {
L
lifeng68 已提交
1278 1279 1280 1281 1282
                continue;
            }
            *total_size = *total_size + fstat.st_size;
            *total_inode = *total_inode + 1;
            bool val = true;
1283
            map_insert(map, (void *)(&(fstat.st_ino)), (void *)&val);
L
lifeng68 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
        }
    }

    nret = closedir(directory);
    if (nret) {
        ERROR("Failed to close directory %s", dirpath);
    }

    return;
}

1295 1296
static void do_calculate_dir_size_without_hardlink(const char *dirpath, int recursive_depth, int64_t *total_size,
                                                   int64_t *total_inode, map_t *map)
L
lifeng68 已提交
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
{
    int64_t total_size_tmp = 0;
    int64_t total_inode_tmp = 0;

    if (dirpath == NULL) {
        return;
    }

    if ((recursive_depth + 1) > MAX_PATH_DEPTH) {
        ERROR("Reach max path depth: %s", dirpath);
        goto out;
    }

    if (!util_dir_exists(dirpath)) {
        ERROR("dir not exists: %s", dirpath);
        goto out;
    }

    recursive_cal_dir_size__without_hardlink_helper(dirpath, recursive_depth, &total_size_tmp, &total_inode_tmp, map);

    if (total_size != NULL) {
        *total_size = total_size_tmp;
    }
    if (total_inode != NULL) {
        *total_inode = total_inode_tmp;
    }

out:
    return;
}

void utils_calculate_dir_size_without_hardlink(const char *dirpath, int64_t *total_size, int64_t *total_inode)
{
    int64_t total_size_tmp = 0;
    int64_t total_inode_tmp = 0;
    map_t *map = NULL;

    if (dirpath == NULL) {
        return;
    }

    map = map_new(MAP_INT_BOOL, MAP_DEFAULT_CMP_FUNC, MAP_DEFAULT_FREE_FUNC);
    if (map == NULL) {
        ERROR("Out of memory");
        return;
    }

    if (!util_dir_exists(dirpath)) {
        ERROR("dir not exists: %s", dirpath);
        goto out;
    }

    do_calculate_dir_size_without_hardlink(dirpath, 0, &total_size_tmp, &total_inode_tmp, map);

    if (total_size != NULL) {
        *total_size = total_size_tmp;
    }
    if (total_inode != NULL) {
        *total_inode = total_inode_tmp;
    }

out:
    map_free(map);
    return;
}

H
haozi007 已提交
1363 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 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
static char *get_random_tmp_file(const char *fname)
{
#define RANDOM_TMP_PATH 10
    int nret = 0;
    char *result = NULL;
    char *base = NULL;
    char *dir = NULL;
    char rpath[PATH_MAX] = { 0x00 };
    char random_tmp[RANDOM_TMP_PATH + 1] = { 0x00 };

    base = util_path_base(fname);
    if (base == NULL) {
        ERROR("Failed to get base of %s", fname);
        goto out;
    }

    dir = util_path_dir(fname);
    if (dir == NULL) {
        ERROR("Failed to get dir of %s", fname);
        goto out;
    }

    if (util_generate_random_str(random_tmp, (size_t)RANDOM_TMP_PATH)) {
        ERROR("Failed to generate random str for random path");
        goto out;
    }

    nret = snprintf(rpath, PATH_MAX, ".tmp-%s-%s", base, random_tmp);
    if (nret < 0 || nret >= PATH_MAX) {
        ERROR("Failed to generate tmp base file");
        goto out;
    }

    result = util_path_join(dir, rpath);

out:
    free(base);
    free(dir);
    return result;
}

int util_atomic_write_file(const char *fname, const char *content, size_t content_len, mode_t mode)
{
    int ret = 0;
    char *tmp_file = NULL;
    char rpath[PATH_MAX] = { 0x00 };

    if (fname == NULL) {
        return -1;
    }
    if (content == NULL || content_len == 0) {
        return 0;
    }

    if (cleanpath(fname, rpath, sizeof(rpath)) == NULL) {
        return -1;
    }

    tmp_file = get_random_tmp_file(fname);
    if (tmp_file == NULL) {
        ERROR("Failed to get tmp file for %s", fname);
        ret = -1;
        goto free_out;
    }

    ret = util_write_file(tmp_file, content, content_len, mode);
    if (ret != 0) {
        ERROR("Failed to write content to tmp file for %s", tmp_file);
        ret = -1;
        goto free_out;
    }

    ret = rename(tmp_file, rpath);
    if (ret != 0) {
        ERROR("Failed to rename old file %s to target %s", tmp_file, rpath);
        ret = -1;
        goto free_out;
    }

free_out:
    free(tmp_file);
    return ret;
}
H
haozi007 已提交
1446

L
lifeng68 已提交
1447
static char *isula_utils_fisula_utils_read_file(FILE *stream, size_t *length)
H
haozi007 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
{
#define JSON_MAX_SIZE (10LL * 1024LL * 1024LL)
    char *buf = NULL;
    char *tmpbuf = NULL;
    size_t off = 0;

    while (1) {
        size_t ret, newsize, sizejudge;
        sizejudge = (JSON_MAX_SIZE - BUFSIZ) - 1;
        if (sizejudge < off) {
            goto out;
        }
        newsize = off + BUFSIZ + 1;

        tmpbuf = (char *)calloc(1, newsize);
        if (tmpbuf == NULL) {
            goto out;
        }

        if (buf != NULL) {
            (void)memcpy(tmpbuf, buf, off);

            (void)memset(buf, 0, off);

            free(buf);
        }

        buf = tmpbuf;
        tmpbuf = NULL;

        ret = fread(buf + off, 1, BUFSIZ, stream);
        if (ret == 0 && ferror(stream)) {
            goto out;
        }
        if (ret < BUFSIZ || feof(stream)) {
            *length = off + ret + 1;
            buf[*length - 1] = '\0';
            return buf;
        }

        off += BUFSIZ;
    }
out:
    free(buf);
    free(tmpbuf);
    return NULL;
}

static int do_check_args(const char *path)
{
    if (path == NULL) {
        return -1;
    }
    if (strlen(path) > PATH_MAX) {
        return -1;
    }
    return 0;
}

char *isula_utils_read_file(const char *path)
{
#define FILE_MODE 0640
    char *buf = NULL;
    char rpath[PATH_MAX + 1] = { 0 };
    int fd = -1;
    int tmperrno = -1;
    FILE *fp = NULL;
    size_t length = 0;

    if (do_check_args(path) != 0) {
        return NULL;
    }

    if (realpath(path, rpath) == NULL) {
        return NULL;
    }

    fd = open(rpath, O_RDONLY | O_CLOEXEC, FILE_MODE);
    if (fd < 0) {
        return NULL;
    }

    fp = fdopen(fd, "r");
    tmperrno = errno;
    if (fp == NULL) {
        (void)close(fd);
        errno = tmperrno;
        return NULL;
    }

L
lifeng68 已提交
1538
    buf = isula_utils_fisula_utils_read_file(fp, &length);
H
haozi007 已提交
1539 1540 1541
    (void)fclose(fp);
    return buf;
}
H
haozi007 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

int isula_utils_read_line(FILE *fp, read_line_callback_t cb, void *context)
{
    size_t len = 0;
    char *line = NULL;
    ssize_t nret = 0;
    int ret = 0;

    if (fp == NULL) {
        ERROR("Invalid parameter");
        return -1;
    }

    errno = 0;
    for (;;) {
        nret = getline(&line, &len, fp);
        if (nret == -1) {
            // end of file
H
haozi007 已提交
1560 1561 1562
            if (errno != 0) {
                ret = -1;
                ERROR("read line failed: %s", strerror(errno));
H
haozi007 已提交
1563 1564 1565 1566 1567 1568
            }
            goto out;
        }

        util_trim_newline(line);
        if (!cb(line, context)) {
H
haozi007 已提交
1569
            ret = -1;
H
haozi007 已提交
1570 1571 1572 1573 1574 1575 1576
            goto out;
        }
    }
out:
    free(line);
    return ret;
}