util.c 147 KB
Newer Older
1
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
Lennart Poettering's avatar
Lennart Poettering committed
2

3 4 5 6 7 8
/***
  This file is part of systemd.

  Copyright 2010 Lennart Poettering

  systemd is free software; you can redistribute it and/or modify it
9 10
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
11 12 13 14 15
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
  Lesser General Public License for more details.
17

18
  You should have received a copy of the GNU Lesser General Public License
19 20 21
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

Lennart Poettering's avatar
Lennart Poettering committed
22 23 24 25
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
26
#include <stdlib.h>
27 28
#include <signal.h>
#include <stdio.h>
29 30 31
#include <syslog.h>
#include <sched.h>
#include <sys/resource.h>
Kay Sievers's avatar
Kay Sievers committed
32
#include <linux/sched.h>
33 34
#include <sys/types.h>
#include <sys/stat.h>
35
#include <fcntl.h>
36
#include <dirent.h>
37 38 39
#include <sys/ioctl.h>
#include <linux/vt.h>
#include <linux/tiocl.h>
Lennart Poettering's avatar
Lennart Poettering committed
40 41 42 43
#include <termios.h>
#include <stdarg.h>
#include <sys/inotify.h>
#include <sys/poll.h>
44
#include <libgen.h>
45
#include <ctype.h>
46
#include <sys/prctl.h>
47 48
#include <sys/utsname.h>
#include <pwd.h>
49
#include <netinet/ip.h>
50
#include <linux/kd.h>
51
#include <dlfcn.h>
52
#include <sys/wait.h>
53
#include <sys/time.h>
54
#include <glob.h>
55
#include <grp.h>
56
#include <sys/mman.h>
57 58
#include <sys/vfs.h>
#include <linux/magic.h>
59
#include <limits.h>
Michal Schmidt's avatar
Michal Schmidt committed
60 61
#include <langinfo.h>
#include <locale.h>
62
#include <libgen.h>
Lennart Poettering's avatar
Lennart Poettering committed
63 64 65

#include "macro.h"
#include "util.h"
66 67
#include "ioprio.h"
#include "missing.h"
68
#include "log.h"
69
#include "strv.h"
70
#include "label.h"
Kay Sievers's avatar
Kay Sievers committed
71
#include "path-util.h"
72
#include "exit-status.h"
73
#include "hashmap.h"
74
#include "env-util.h"
75
#include "fileio.h"
76

77 78
int saved_argc = 0;
char **saved_argv = NULL;
79

80
static volatile unsigned cached_columns = 0;
81
static volatile unsigned cached_lines = 0;
82

cee1's avatar
cee1 committed
83 84 85 86
size_t page_size(void) {
        static __thread size_t pgsz = 0;
        long r;

87
        if (_likely_(pgsz > 0))
cee1's avatar
cee1 committed
88 89
                return pgsz;

90 91
        r = sysconf(_SC_PAGESIZE);
        assert(r > 0);
cee1's avatar
cee1 committed
92 93 94 95 96

        pgsz = (size_t) r;
        return pgsz;
}

97 98 99 100 101 102 103 104 105 106 107 108 109
bool streq_ptr(const char *a, const char *b) {

        /* Like streq(), but tries to make sense of NULL pointers */

        if (a && b)
                return streq(a, b);

        if (!a && !b)
                return true;

        return false;
}

110
char* endswith(const char *s, const char *postfix) {
Lennart Poettering's avatar
Lennart Poettering committed
111 112 113 114 115 116 117 118
        size_t sl, pl;

        assert(s);
        assert(postfix);

        sl = strlen(s);
        pl = strlen(postfix);

119
        if (pl == 0)
120
                return (char*) s + sl;
121

Lennart Poettering's avatar
Lennart Poettering committed
122
        if (sl < pl)
123 124 125 126
                return NULL;

        if (memcmp(s + sl - pl, postfix, pl) != 0)
                return NULL;
Lennart Poettering's avatar
Lennart Poettering committed
127

128
        return (char*) s + sl - pl;
Lennart Poettering's avatar
Lennart Poettering committed
129 130
}

131 132
char* startswith(const char *s, const char *prefix) {
        const char *a, *b;
Lennart Poettering's avatar
Lennart Poettering committed
133 134 135 136

        assert(s);
        assert(prefix);

137 138 139 140 141 142
        a = s, b = prefix;
        for (;;) {
                if (*b == 0)
                        return (char*) a;
                if (*a != *b)
                        return NULL;
Lennart Poettering's avatar
Lennart Poettering committed
143

144 145
                a++, b++;
        }
Lennart Poettering's avatar
Lennart Poettering committed
146 147
}

148 149
char* startswith_no_case(const char *s, const char *prefix) {
        const char *a, *b;
150 151 152 153

        assert(s);
        assert(prefix);

154 155 156 157 158 159
        a = s, b = prefix;
        for (;;) {
                if (*b == 0)
                        return (char*) a;
                if (tolower(*a) != tolower(*b))
                        return NULL;
160

161 162
                a++, b++;
        }
163 164
}

Lennart Poettering's avatar
Lennart Poettering committed
165 166 167 168 169 170 171 172 173 174 175 176
bool first_word(const char *s, const char *word) {
        size_t sl, wl;

        assert(s);
        assert(word);

        sl = strlen(s);
        wl = strlen(word);

        if (sl < wl)
                return false;

177 178 179
        if (wl == 0)
                return true;

Lennart Poettering's avatar
Lennart Poettering committed
180 181 182
        if (memcmp(s, word, wl) != 0)
                return false;

183 184
        return s[wl] == 0 ||
                strchr(WHITESPACE, s[wl]);
Lennart Poettering's avatar
Lennart Poettering committed
185 186
}

187
int close_nointr(int fd) {
188
        int r;
Lennart Poettering's avatar
Lennart Poettering committed
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        assert(fd >= 0);
        r = close(fd);

        /* Just ignore EINTR; a retry loop is the wrong
         * thing to do on Linux.
         *
         * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
         * https://bugzilla.gnome.org/show_bug.cgi?id=682819
         * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
         * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
         */
        if (_unlikely_(r < 0 && errno == EINTR))
                return 0;
        else if (r >= 0)
                return r;
        else
                return -errno;
Lennart Poettering's avatar
Lennart Poettering committed
207
}
208

209
void close_nointr_nofail(int fd) {
210
        PROTECT_ERRNO;
211 212 213 214 215 216 217

        /* like close_nointr() but cannot fail, and guarantees errno
         * is unchanged */

        assert_se(close_nointr(fd) == 0);
}

218 219 220
void close_many(const int fds[], unsigned n_fd) {
        unsigned i;

221 222
        assert(fds || n_fd <= 0);

223 224 225 226
        for (i = 0; i < n_fd; i++)
                close_nointr_nofail(fds[i]);
}

227 228 229 230 231 232 233 234 235 236 237
int unlink_noerrno(const char *path) {
        PROTECT_ERRNO;
        int r;

        r = unlink(path);
        if (r < 0)
                return -errno;

        return 0;
}

238 239 240
int parse_boolean(const char *v) {
        assert(v);

241
        if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
242
                return 1;
243
        else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
244 245 246 247 248
                return 0;

        return -EINVAL;
}

249
int parse_pid(const char *s, pid_t* ret_pid) {
Lennart Poettering's avatar
Lennart Poettering committed
250
        unsigned long ul = 0;
251 252 253 254 255 256
        pid_t pid;
        int r;

        assert(s);
        assert(ret_pid);

257 258
        r = safe_atolu(s, &ul);
        if (r < 0)
259 260 261 262 263 264 265 266 267 268 269 270 271 272
                return r;

        pid = (pid_t) ul;

        if ((unsigned long) pid != ul)
                return -ERANGE;

        if (pid <= 0)
                return -ERANGE;

        *ret_pid = pid;
        return 0;
}

273 274 275 276 277 278 279 280
int parse_uid(const char *s, uid_t* ret_uid) {
        unsigned long ul = 0;
        uid_t uid;
        int r;

        assert(s);
        assert(ret_uid);

281 282
        r = safe_atolu(s, &ul);
        if (r < 0)
283 284 285 286 287 288 289 290 291 292 293
                return r;

        uid = (uid_t) ul;

        if ((unsigned long) uid != ul)
                return -ERANGE;

        *ret_uid = uid;
        return 0;
}

294 295
int safe_atou(const char *s, unsigned *ret_u) {
        char *x = NULL;
296
        unsigned long l;
297 298 299 300 301 302 303

        assert(s);
        assert(ret_u);

        errno = 0;
        l = strtoul(s, &x, 0);

304
        if (!x || x == s || *x || errno)
305
                return errno > 0 ? -errno : -EINVAL;
306

307
        if ((unsigned long) (unsigned) l != l)
308 309 310 311 312 313 314 315
                return -ERANGE;

        *ret_u = (unsigned) l;
        return 0;
}

int safe_atoi(const char *s, int *ret_i) {
        char *x = NULL;
316
        long l;
317 318 319 320 321 322 323

        assert(s);
        assert(ret_i);

        errno = 0;
        l = strtol(s, &x, 0);

324
        if (!x || x == s || *x || errno)
325
                return errno > 0 ? -errno : -EINVAL;
326

327
        if ((long) (int) l != l)
328 329
                return -ERANGE;

330 331 332 333 334 335 336 337 338 339 340 341 342 343
        *ret_i = (int) l;
        return 0;
}

int safe_atollu(const char *s, long long unsigned *ret_llu) {
        char *x = NULL;
        unsigned long long l;

        assert(s);
        assert(ret_llu);

        errno = 0;
        l = strtoull(s, &x, 0);

344
        if (!x || x == s || *x || errno)
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
                return errno ? -errno : -EINVAL;

        *ret_llu = l;
        return 0;
}

int safe_atolli(const char *s, long long int *ret_lli) {
        char *x = NULL;
        long long l;

        assert(s);
        assert(ret_lli);

        errno = 0;
        l = strtoll(s, &x, 0);

361
        if (!x || x == s || *x || errno)
362 363 364
                return errno ? -errno : -EINVAL;

        *ret_lli = l;
365 366
        return 0;
}
367

368 369 370 371 372 373 374
int safe_atod(const char *s, double *ret_d) {
        char *x = NULL;
        double d;

        assert(s);
        assert(ret_d);

375 376 377 378
        RUN_WITH_LOCALE(LC_NUMERIC_MASK, "C") {
                errno = 0;
                d = strtod(s, &x);
        }
379 380 381 382 383 384 385 386

        if (!x || x == s || *x || errno)
                return errno ? -errno : -EINVAL;

        *ret_d = (double) d;
        return 0;
}

387
/* Split a string into words. */
388
char *split(const char *c, size_t *l, const char *separator, char **state) {
389 390 391 392 393 394 395
        char *current;

        current = *state ? *state : (char*) c;

        if (!*current || *c == 0)
                return NULL;

396 397
        current += strspn(current, separator);
        *l = strcspn(current, separator);
398 399 400 401 402
        *state = current+*l;

        return (char*) current;
}

403 404 405
/* Split a string into words, but consider strings enclosed in '' and
 * "" as words even if they include spaces. */
char *split_quoted(const char *c, size_t *l, char **state) {
406 407
        char *current, *e;
        bool escaped = false;
408 409 410 411 412 413 414 415 416 417 418

        current = *state ? *state : (char*) c;

        if (!*current || *c == 0)
                return NULL;

        current += strspn(current, WHITESPACE);

        if (*current == '\'') {
                current ++;

419 420 421 422 423 424 425 426 427 428 429
                for (e = current; *e; e++) {
                        if (escaped)
                                escaped = false;
                        else if (*e == '\\')
                                escaped = true;
                        else if (*e == '\'')
                                break;
                }

                *l = e-current;
                *state = *e == 0 ? e : e+1;
430 431 432
        } else if (*current == '\"') {
                current ++;

433 434 435 436 437 438 439 440 441 442 443
                for (e = current; *e; e++) {
                        if (escaped)
                                escaped = false;
                        else if (*e == '\\')
                                escaped = true;
                        else if (*e == '\"')
                                break;
                }

                *l = e-current;
                *state = *e == 0 ? e : e+1;
444
        } else {
445 446 447 448 449 450 451 452 453 454
                for (e = current; *e; e++) {
                        if (escaped)
                                escaped = false;
                        else if (*e == '\\')
                                escaped = true;
                        else if (strchr(WHITESPACE, *e))
                                break;
                }
                *l = e-current;
                *state = e;
455 456 457 458 459 460 461
        }

        return (char*) current;
}

int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
        int r;
462
        _cleanup_fclose_ FILE *f = NULL;
463
        char line[LINE_MAX];
464
        long unsigned ppid;
465
        const char *p;
466

467
        assert(pid >= 0);
468 469
        assert(_ppid);

470 471 472 473
        if (pid == 0) {
                *_ppid = getppid();
                return 0;
        }
474

475 476
        p = procfs_file_alloca(pid, "stat");
        f = fopen(p, "re");
477
        if (!f)
478 479
                return -errno;

480
        if (!fgets(line, sizeof(line), f)) {
481
                r = feof(f) ? -EIO : -errno;
482 483 484 485 486 487 488
                return r;
        }

        /* Let's skip the pid and comm fields. The latter is enclosed
         * in () but does not escape any () in its value, so let's
         * skip over it manually */

489 490
        p = strrchr(line, ')');
        if (!p)
491 492 493 494 495 496
                return -EIO;

        p++;

        if (sscanf(p, " "
                   "%*c "  /* state */
497
                   "%lu ", /* ppid */
498 499 500
                   &ppid) != 1)
                return -EIO;

501
        if ((long unsigned) (pid_t) ppid != ppid)
502 503 504 505 506 507 508
                return -ERANGE;

        *_ppid = (pid_t) ppid;

        return 0;
}

509
int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
510
        _cleanup_fclose_ FILE *f = NULL;
511 512
        char line[LINE_MAX];
        const char *p;
513

514
        assert(pid >= 0);
515 516
        assert(st);

517 518 519 520
        if (pid == 0)
                p = "/proc/self/stat";
        else
                p = procfs_file_alloca(pid, "stat");
521

522
        f = fopen(p, "re");
523
        if (!f)
524 525
                return -errno;

526 527 528
        if (!fgets(line, sizeof(line), f)) {
                if (ferror(f))
                        return -errno;
529

530 531
                return -EIO;
        }
532 533 534 535 536

        /* Let's skip the pid and comm fields. The latter is enclosed
         * in () but does not escape any () in its value, so let's
         * skip over it manually */

537 538
        p = strrchr(line, ')');
        if (!p)
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
                return -EIO;

        p++;

        if (sscanf(p, " "
                   "%*c "  /* state */
                   "%*d "  /* ppid */
                   "%*d "  /* pgrp */
                   "%*d "  /* session */
                   "%*d "  /* tty_nr */
                   "%*d "  /* tpgid */
                   "%*u "  /* flags */
                   "%*u "  /* minflt */
                   "%*u "  /* cminflt */
                   "%*u "  /* majflt */
                   "%*u "  /* cmajflt */
                   "%*u "  /* utime */
                   "%*u "  /* stime */
                   "%*d "  /* cutime */
                   "%*d "  /* cstime */
                   "%*d "  /* priority */
                   "%*d "  /* nice */
                   "%*d "  /* num_threads */
                   "%*d "  /* itrealvalue */
                   "%llu "  /* starttime */,
                   st) != 1)
                return -EIO;

        return 0;
}

570 571 572 573 574 575 576 577 578 579 580
int fchmod_umask(int fd, mode_t m) {
        mode_t u;
        int r;

        u = umask(0777);
        r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
        umask(u);

        return r;
}

581 582 583 584 585 586 587
char *truncate_nl(char *s) {
        assert(s);

        s[strcspn(s, NEWLINE)] = 0;
        return s;
}

588
int get_process_comm(pid_t pid, char **name) {
589
        const char *p;
590 591

        assert(name);
592
        assert(pid >= 0);
593

594
        if (pid == 0)
595 596 597
                p = "/proc/self/comm";
        else
                p = procfs_file_alloca(pid, "comm");
598

599
        return read_one_line_file(p, name);
600 601
}

602
int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
603
        _cleanup_fclose_ FILE *f = NULL;
604
        char *r = NULL, *k;
605
        const char *p;
606 607 608
        int c;

        assert(line);
609
        assert(pid >= 0);
610

611
        if (pid == 0)
612 613 614
                p = "/proc/self/cmdline";
        else
                p = procfs_file_alloca(pid, "cmdline");
615

616
        f = fopen(p, "re");
617 618
        if (!f)
                return -errno;
619

620
        if (max_length == 0) {
621 622
                size_t len = 0, allocated = 0;

623
                while ((c = getc(f)) != EOF) {
624 625

                        if (!GREEDY_REALLOC(r, allocated, len+2)) {
626 627 628
                                free(r);
                                return -ENOMEM;
                        }
629 630

                        r[len++] = isprint(c) ? c : ' ';
631
                }
632 633 634 635

                if (len > 0)
                        r[len-1] = 0;

636 637 638
        } else {
                bool space = false;
                size_t left;
639

640
                r = new(char, max_length);
641
                if (!r)
642
                        return -ENOMEM;
643

644 645 646
                k = r;
                left = max_length;
                while ((c = getc(f)) != EOF) {
647

648 649 650 651 652 653 654 655 656
                        if (isprint(c)) {
                                if (space) {
                                        if (left <= 4)
                                                break;

                                        *(k++) = ' ';
                                        left--;
                                        space = false;
                                }
657 658 659 660

                                if (left <= 4)
                                        break;

661
                                *(k++) = (char) c;
662
                                left--;
663 664 665
                        }  else
                                space = true;
                }
666

667 668 669 670 671 672
                if (left <= 4) {
                        size_t n = MIN(left-1, 3U);
                        memcpy(k, "...", n);
                        k[n] = 0;
                } else
                        *k = 0;
673 674
        }

675
        /* Kernel threads have no argv[] */
676
        if (r == NULL || r[0] == 0) {
677 678 679 680 681
                char *t;
                int h;

                free(r);

682 683 684 685 686
                if (!comm_fallback)
                        return -ENOENT;

                h = get_process_comm(pid, &t);
                if (h < 0)
687 688
                        return h;

689
                r = strjoin("[", t, "]", NULL);
690 691
                free(t);

692
                if (!r)
693 694
                        return -ENOMEM;
        }
695

696 697 698 699
        *line = r;
        return 0;
}

700
int is_kernel_thread(pid_t pid) {
701
        const char *p;
702 703 704 705 706 707 708 709
        size_t count;
        char c;
        bool eof;
        FILE *f;

        if (pid == 0)
                return 0;

710
        assert(pid > 0);
711

712 713
        p = procfs_file_alloca(pid, "cmdline");
        f = fopen(p, "re");
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        if (!f)
                return -errno;

        count = fread(&c, 1, 1, f);
        eof = feof(f);
        fclose(f);

        /* Kernel threads have an empty cmdline */

        if (count <= 0)
                return eof ? 1 : -errno;

        return 0;
}

729

730
int get_process_exe(pid_t pid, char **name) {
731
        const char *p;
732

733
        assert(pid >= 0);
734 735 736
        assert(name);

        if (pid == 0)
737 738 739
                p = "/proc/self/exe";
        else
                p = procfs_file_alloca(pid, "exe");
740

741
        return readlink_malloc(p, name);
742 743
}

744
static int get_process_id(pid_t pid, const char *field, uid_t *uid) {
745
        _cleanup_fclose_ FILE *f = NULL;
746
        char line[LINE_MAX];
747
        const char *p;
748

749
        assert(field);
750 751 752 753 754
        assert(uid);

        if (pid == 0)
                return getuid();

755 756
        p = procfs_file_alloca(pid, "status");
        f = fopen(p, "re");
757 758 759
        if (!f)
                return -errno;

760
        FOREACH_LINE(line, f, return -errno) {
761
                char *l;
762 763 764

                l = strstrip(line);

765 766
                if (startswith(l, field)) {
                        l += strlen(field);
767 768 769 770
                        l += strspn(l, WHITESPACE);

                        l[strcspn(l, WHITESPACE)] = 0;

771
                        return parse_uid(l, uid);
772 773 774
                }
        }

775
        return -EIO;
776 777
}

778 779 780 781 782
int get_process_uid(pid_t pid, uid_t *uid) {
        return get_process_id(pid, "Uid:", uid);
}

int get_process_gid(pid_t pid, gid_t *gid) {
783
        assert_cc(sizeof(uid_t) == sizeof(gid_t));
784 785 786
        return get_process_id(pid, "Gid:", gid);
}

787 788
char *strnappend(const char *s, const char *suffix, size_t b) {
        size_t a;
Lennart Poettering's avatar
Lennart Poettering committed
789 790
        char *r;

791 792 793 794 795 796 797 798 799
        if (!s && !suffix)
                return strdup("");

        if (!s)
                return strndup(suffix, b);

        if (!suffix)
                return strdup(s);

Lennart Poettering's avatar
Lennart Poettering committed
800 801 802 803
        assert(s);
        assert(suffix);

        a = strlen(s);
Lennart Poettering's avatar
Lennart Poettering committed
804
        if (b > ((size_t) -1) - a)
Lennart Poettering's avatar
Lennart Poettering committed
805
                return NULL;
Lennart Poettering's avatar
Lennart Poettering committed
806

Lennart Poettering's avatar
Lennart Poettering committed
807 808
        r = new(char, a+b+1);
        if (!r)
Lennart Poettering's avatar
Lennart Poettering committed
809 810 811 812 813 814 815 816
                return NULL;

        memcpy(r, s, a);
        memcpy(r+a, suffix, b);
        r[a+b] = 0;

        return r;
}
Lennart Poettering's avatar
Lennart Poettering committed
817

818 819 820 821
char *strappend(const char *s, const char *suffix) {
        return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
}

Lennart Poettering's avatar
Lennart Poettering committed
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
int readlink_malloc(const char *p, char **r) {
        size_t l = 100;

        assert(p);
        assert(r);

        for (;;) {
                char *c;
                ssize_t n;

                if (!(c = new(char, l)))
                        return -ENOMEM;

                if ((n = readlink(p, c, l-1)) < 0) {
                        int ret = -errno;
                        free(c);
                        return ret;
                }

                if ((size_t) n < l-1) {
                        c[n] = 0;
                        *r = c;
                        return 0;
                }

                free(c);
                l *= 2;
        }
}

852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
int readlink_and_make_absolute(const char *p, char **r) {
        char *target, *k;
        int j;

        assert(p);
        assert(r);

        if ((j = readlink_malloc(p, &target)) < 0)
                return j;

        k = file_in_same_dir(p, target);
        free(target);

        if (!k)
                return -ENOMEM;

        *r = k;
        return 0;
}

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
int readlink_and_canonicalize(const char *p, char **r) {
        char *t, *s;
        int j;

        assert(p);
        assert(r);

        j = readlink_and_make_absolute(p, &t);
        if (j < 0)
                return j;

        s = canonicalize_file_name(t);
        if (s) {
                free(t);
                *r = s;
        } else
                *r = t;

        path_kill_slashes(*r);

        return 0;
}

895 896 897 898
int reset_all_signal_handlers(void) {
        int sig;

        for (sig = 1; sig < _NSIG; sig++) {
899 900 901 902
                struct sigaction sa = {
                        .sa_handler = SIG_DFL,
                        .sa_flags = SA_RESTART,
                };
903 904 905 906 907 908 909 910 911 912 913

                if (sig == SIGKILL || sig == SIGSTOP)
                        continue;

                /* On Linux the first two RT signals are reserved by
                 * glibc, and sigaction() will return EINVAL for them. */
                if ((sigaction(sig, &sa, NULL) < 0))
                        if (errno != EINVAL)
                                return -errno;
        }

914
        return 0;
915
}
916 917

char *strstrip(char *s) {
918
        char *e;
919 920 921 922 923 924

        /* Drops trailing whitespace. Modifies the string in
         * place. Returns pointer to first non-space character */

        s += strspn(s, WHITESPACE);

925 926 927
        for (e = strchr(s, 0); e > s; e --)
                if (!strchr(WHITESPACE, e[-1]))
                        break;
928

929
        *e = 0;
930 931 932 933

        return s;
}

934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
char *delete_chars(char *s, const char *bad) {
        char *f, *t;

        /* Drops all whitespace, regardless where in the string */

        for (f = s, t = s; *f; f++) {
                if (strchr(bad, *f))
                        continue;

                *(t++) = *f;
        }

        *t = 0;

        return s;
}

951 952 953 954 955 956 957 958 959 960 961 962 963
bool in_charset(const char *s, const char* charset) {
        const char *i;

        assert(s);
        assert(charset);

        for (i = s; *i; i++)
                if (!strchr(charset, *i))
                        return false;

        return true;
}

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
char *file_in_same_dir(const char *path, const char *filename) {
        char *e, *r;
        size_t k;

        assert(path);
        assert(filename);

        /* This removes the last component of path and appends
         * filename, unless the latter is absolute anyway or the
         * former isn't */

        if (path_is_absolute(filename))
                return strdup(filename);

        if (!(e = strrchr(path, '/')))
                return strdup(filename);

        k = strlen(filename);
        if (!(r = new(char, e-path+1+k+1)))
                return NULL;

        memcpy(r, path, e-path+1);
        memcpy(r+(e-path)+1, filename, k+1);

        return r;
}
Lennart Poettering's avatar
Lennart Poettering committed
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
int rmdir_parents(const char *path, const char *stop) {
        size_t l;
        int r = 0;

        assert(path);
        assert(stop);

        l = strlen(path);

        /* Skip trailing slashes */
        while (l > 0 && path[l-1] == '/')
                l--;

        while (l > 0) {
                char *t;

                /* Skip last component */
                while (l > 0 && path[l-1] != '/')
                        l--;

                /* Skip trailing slashes */
                while (l > 0 && path[l-1] == '/')
                        l--;

                if (l <= 0)
                        break;

                if (!(t = strndup(path, l)))
                        return -ENOMEM;

                if (path_startswith(stop, t)) {
                        free(t);
                        return 0;
                }

                r = rmdir(t);
                free(t);

                if (r < 0)
                        if (errno != ENOENT)
                                return -errno;
        }

        return 0;
}

Lennart Poettering's avatar
Lennart Poettering committed
1037 1038 1039 1040 1041
char hexchar(int x) {
        static const char table[16] = "0123456789abcdef";

        return table[x & 15];
}
1042 1043 1044 1045 1046 1047 1048

int unhexchar(char c) {

        if (c >= '0' && c <= '9')
                return c - '0';

        if (c >= 'a' && c <= 'f')
1049
                return c - 'a' + 10;
1050 1051

        if (c >= 'A' && c <= 'F')
1052
                return c - 'A' + 10;
1053 1054 1055 1056

        return -1;
}

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
char *hexmem(const void *p, size_t l) {
        char *r, *z;
        const uint8_t *x;

        z = r = malloc(l * 2 + 1);
        if (!r)
                return NULL;

        for (x = p; x < (const uint8_t*) p + l; x++) {
                *(z++) = hexchar(*x >> 4);
                *(z++) = hexchar(*x & 15);
        }

        *z = 0;
        return r;
}

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
void *unhexmem(const char *p, size_t l) {
        uint8_t *r, *z;
        const char *x;

        assert(p);

        z = r = malloc((l + 1) / 2 + 1);
        if (!r)
                return NULL;

        for (x = p; x < p + l; x += 2) {
                int a, b;

                a = unhexchar(x[0]);
                if (x+1 < p + l)
                        b = unhexchar(x[1]);
                else
                        b = 0;

                *(z++) = (uint8_t) a << 4 | (uint8_t) b;
        }

        *z = 0;
        return r;
}

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
char octchar(int x) {
        return '0' + (x & 7);
}

int unoctchar(char c) {

        if (c >= '0' && c <= '7')
                return c - '0';

        return -1;
}

1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
char decchar(int x) {
        return '0' + (x % 10);
}

int undecchar(char c) {

        if (c >= '0' && c <= '9')
                return c - '0';

        return -1;
}

1124 1125 1126 1127 1128 1129 1130 1131
char *cescape(const char *s) {
        char *r, *t;
        const char *f;

        assert(s);

        /* Does C style string escaping. */

1132 1133
        r = new(char, strlen(s)*4 + 1);
        if (!r)
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
                return NULL;

        for (f = s, t = r; *f; f++)

                switch (*f) {

                case '\a':
                        *(t++) = '\\';
                        *(t++) = 'a';
                        break;
                case '\b':
                        *(t++) = '\\';
                        *(t++) = 'b';
                        break;
                case '\f':
                        *(t++) = '\\';
                        *(t++) = 'f';
                        break;
                case '\n':
                        *(t++) = '\\';
                        *(t++) = 'n';
                        break;
                case '\r':
                        *(t++) = '\\';
                        *(t++) = 'r';
                        break;
                case '\t':
                        *(t++) = '\\';
                        *(t++) = 't';
                        break;
                case '\v':
                        *(t++) = '\\';
                        *(t++) = 'v';
                        break;
                case '\\':
                        *(t++) = '\\';
                        *(t++) = '\\';
                        break;
                case '"':
                        *(t++) = '\\';
                        *(t++) = '"';
                        break;
                case '\'':
                        *(t++) = '\\';
                        *(t++) = '\'';
                        break;

                default:
                        /* For special chars we prefer octal over
                         * hexadecimal encoding, simply because glib's
                         * g_strescape() does the same */
                        if ((*f < ' ') || (*f >= 127)) {
                                *(t++) = '\\';
                                *(t++) = octchar((unsigned char) *f >> 6);
                                *(t++) = octchar((unsigned char) *f >> 3);
                                *(t++) = octchar((unsigned char) *f);
                        } else
                                *(t++) = *f;
                        break;
                }

        *t = 0;

        return r;
}

1200
char *cunescape_length_with_prefix(const char *s, size_t length, const char *prefix) {
1201 1202
        char *r, *t;
        const char *f;
1203
        size_t pl;
1204 1205 1206

        assert(s);

1207 1208 1209
        /* Undoes C style string escaping, and optionally prefixes it. */

        pl = prefix ? strlen(prefix) : 0;
1210

1211
        r = new(char, pl+length+1);
1212
        if (!r)
1213 1214
                return r;

1215 1216 1217 1218
        if (prefix)
                memcpy(r, prefix, pl);

        for (f = s, t = r + pl; f < s + length; f++) {
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

                if (*f != '\\') {
                        *(t++) = *f;
                        continue;
                }

                f++;

                switch (*f) {

                case 'a':
                        *(t++) = '\a';
                        break;
                case 'b':
                        *(t++) = '\b';
                        break;
                case 'f':
                        *(t++) = '\f';
                        break;
                case 'n':
                        *(t++) = '\n';
                        break;
                case 'r':
                        *(t++) = '\r';
                        break;
                case 't':
                        *(t++) = '\t';
                        break;
                case 'v':
                        *(t++) = '\v';
                        break;
                case '\\':
                        *(t++) = '\\';
                        break;
                case '"':
                        *(t++) = '"';
                        break