summaryrefslogtreecommitdiff
path: root/src/libsystem/libsystem.c
blob: a91174503ea7664b87331492e3b869846081aff4 (plain)
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
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
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/

/*
 * libsystem
 *
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <ctype.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <mntent.h>
#include <stdint.h>
#include <inttypes.h>

#include "libsystem.h"

static int _errno_old;

#define STORE_RESET_ERRNO do {          \
        _errno_old = errno;             \
        errno = 0;                      \
} while (0)

#define RESTORE_ERRNO do {              \
        errno = _errno_old;             \
        _errno_old = 0;                 \
} while (0)

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;
}

char *truncate_nl(char *s) {
        assert(s);

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

        return s;
}

char *strnappend(const char *s, const char *suffix, size_t b) {
        size_t a;
        char *r;

        if (!s && !suffix)
                return strdup("");

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

        if (!suffix)
                return strdup(s);

        assert(s);
        assert(suffix);

        a = strlen(s);
        if (b > ((size_t) - 1) - a)
                return NULL;

        r = new(char, a + b + 1);
        if (!r)
                return NULL;

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

        return r;
}

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

char *strstrip(char *s) {
        char *e;

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

        s += strspn(s, WHITESPACE);

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

        *e = 0;

        return s;
}

int strdup_strip(const char *str, char **ret) {
        char *r = NULL;
        size_t s, l;

        assert(str);
        assert(ret);

        s = strspn(str, WHITESPACE);

        for (l = strlen(str + s); l > 0; l--)
                if (!strchr(WHITESPACE, str[s + l - 1]))
                        break;

        r = strndup(str + s, l);
        if (!r)
                return -ENOMEM;

        *ret = r;

        return 0;
}

int strndup_strip(const char *str, size_t len, char **ret) {
        char *r = NULL;
        size_t s, l;

        assert(str);
        assert(ret);

        s = strspn(str, WHITESPACE);

        l = strlen(str + s);
        if (len > s)
                l = l < len - s ? l : len - s;
        else
                return -EFAULT;

        for (; l > 0; l--)
                if (!strchr(WHITESPACE, str[s + l - 1]))
                        break;

        r = strndup(str + s, l);
        if (!r)
                return -ENOMEM;

        *ret = r;

        return 0;
}

bool nulstr_contains(const char *nulstr, const char *needle) {
        const char *i;

        if (!nulstr)
                return false;

        NULSTR_FOREACH(i, nulstr)
                if (streq(i, needle))
                        return true;

        return false;
}

bool path_is_absolute(const char *p) {

        assert(p);

        return p[0] == '/';
}

char *path_kill_slashes(char *path) {
        char *f, *t;
        bool slash = false;

        /* Removes redundant inner and trailing slashes. Modifies the
         * passed string in-place.
         *
         * ///foo///bar/ becomes /foo/bar
         */

        for (f = path, t = path; *f; f++) {

                if (*f == '/') {
                        slash = true;
                        continue;
                }

                if (slash) {
                        slash = false;
                        *(t++) = '/';
                }

                *(t++) = *f;
        }

        /* Special rule, if we are talking of the root directory, a
           trailing slash is good */

        if (t == path && slash)
                *(t++) = '/';

        *t = 0;
        return path;
}

char *endswith(const char *s, const char *postfix) {
        size_t sl, pl;

        assert(s);
        assert(postfix);

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

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

        if (sl < pl)
                return NULL;

        if (memcmp(s + sl - pl, postfix, pl) != 0)
                return NULL;

        return (char *) s + sl - pl;
}

int parse_boolean(const char *v) {
        assert(v);

        if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || strcaseeq(v, "on"))
                return 1;
        else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || strcaseeq(v, "off"))
                return 0;

        return -EINVAL;
}

int parse_bytes(const char *b, size_t *s) {
        _cleanup_free_ char *num = NULL;
        size_t len, num_l, unit_l;

        assert(b);

        len = strlen(b);

        if (!len)
                return 0;

        num_l = strspn(b, "0123456789");
        if (num_l < len - 1)
                return -EINVAL;

        unit_l = strcspn(b, "BKMG");
        if (num_l != unit_l)
                return -EINVAL;

        num = strndup(b, num_l);
        if (!num)
                return -ENOMEM;

        switch (b[len - 1]) {
        case 'G':
                *s = atoi(num) << 30;
                break;
        case 'M':
                *s = atoi(num) << 20;
                break;
        case 'K':
                *s = atoi(num) << 10;
                break;
        case 'B':
        default:
                *s = atoi(num);
                break;
        }

        return 0;
}

int parse_percent(const char *string, size_t *percent) {
        _cleanup_free_ char *num = NULL;
        size_t len, num_len, per;

        assert(string);
        assert(percent);

        len = strlen(string);
        if (!len)
                return 0;

        if (string[len - 1] != '%')
                return -EINVAL;

        num_len = strspn(string, "0123456789");
        if (num_len < len - 1)
                return -EINVAL;

        num = strndup(string, num_len);
        if (!num)
                return -ENOMEM;

        per = atoi(num);
        if (per > 100)
                return -EINVAL;

        *percent = per;

        return 0;
}

static bool __quote_complete(char *str, size_t l, char q) {
        char *s, *s2;

        assert(str);

        if (!l)
                return true;

        s = strchr(str, q);
        if (!s || (s - str) > l)
                return true;

        s = strchr(s + 1, q);
        if (!s || (s - str) > l)
                return false;

        s2 = strchr(s + 1, q);
        if (!s2 || (s2 - str) > l)
                return true;

        return __quote_complete(s + 1, l - (s + 1 - str), q);
}

static bool quote_complete(char *str, size_t l) {
        char quotes[] = QUOTES;
        int i;

        assert(str);

        if (!l)
                return true;

        for (i = 0; quotes[i]; i++) {
                if (!__quote_complete(str, l, quotes[i]))
                        return false;
        }

        return true;
}

char *split(const char *c, size_t *l, const char *separator, char **state) {
        bool separator_include_quotes;
        char *current;
        size_t s;

        assert(c);
        assert(l);
        assert(separator);
        assert(state);

        current = *state ? *state : (char *) c;
        if (!*current || *c == 0)
                return NULL;

        *l = 0;
        separator_include_quotes = !!strspn(separator, QUOTES);
        current += strspn(current, separator);

        while ((s = strcspn(current + *l, separator))) {
                *l += s;
                if (separator_include_quotes ||
                    quote_complete(current, *l))
                        break;
                (*l)++;
        }

        *state = current + *l;

        return (char *) current;
}

bool is_number(const char *s, int l) {
        int i;

        for (i = 0; i < l; i++)
                if (!isdigit(s[i]))
                        return false;

        return true;
}

static int do_copy_internal(const char *src, const char *dst, mode_t mode, bool force) {
        _cleanup_close_ int rfd = -1, wfd = -1;
        char buf[1024];
        ssize_t red;
        int r;

        assert(src);
        assert(dst);

        if (!force) {
                r = access(dst, F_OK);
                if (r == 0)
                        return -EALREADY;
                else if (errno != ENOENT)
                        return -errno;
        }

        wfd = open(dst, O_CREAT | O_WRONLY | O_TRUNC, mode);
        if (wfd < 0)
                return -errno;

        rfd = open(src, O_RDONLY);
        if (rfd < 0)
                return -errno;

        while ((red = read(rfd, buf, 1024)) > 0)
                if (write(wfd, buf, red) != red)
                        return -errno;

        if (red < 0)
                return -errno;

        return 0;
}

int do_copy_mode(const char *src, const char *dst, mode_t mode) {

        assert(src);
        assert(dst);

        return do_copy_internal(src, dst, mode, false);
}

int do_copy_mode_force(const char *src, const char *dst, mode_t mode) {

        assert(src);
        assert(dst);

        return do_copy_internal(src, dst, mode, true);
}

int do_copy(const char *src, const char *dst) {

        assert(src);
        assert(dst);

        return do_copy_internal(src, dst, 0644, false);
}

int do_copy_force(const char *src, const char *dst) {

        assert(src);
        assert(dst);

        return do_copy_internal(src, dst, 0644, true);
}

int do_mkdir(const char *path, mode_t mode) {
        char d[PATH_MAX];
        size_t s, l;
        int r, p;

        assert(path);

        l = strlen(path);

        for (p = 0, s = 0; p < l; p += s + 1) {
                s = strcspn(path + p, "/");
                if (!s)
                        continue;

                assert(PATH_MAX > p + s + 1);

                r = snprintf(d, p + s + 1, "%s", path);
                if (r < 0)
                        return r;

                r = mkdir(d, mode);
                if (r < 0 && errno != EEXIST)
                        return -errno;
        }

        return 0;
}

int rmdir_recursive(const char *path) {
        _cleanup_closedir_ DIR *d = NULL;
        struct dirent *de;
        int r;

        assert(path);

        d = opendir(path);
        if (!d)
                return -errno;

        FOREACH_DIRENT(de, d, return -errno) {
                _cleanup_free_ char *p = NULL;

                r = asprintf(&p, "%s/%s", path, de->d_name);
                if (r < 0)
                        return -ENOMEM;

                if (de->d_type == DT_DIR) {
                        r = rmdir_recursive(p);
                        if (r < 0)
                                return r;
                } else {
                        r = unlink(p);
                        if (r < 0)
                                return r;
                }
        }

        return rmdir(path);
}

char *strdup_unquote(const char *str, const char *quotes) {
        size_t l;

        assert(str);

        l = strlen(str);
        if (l < 2)
                return strdup(str);

        if (strchr(quotes, str[0]) && str[0] == str[l - 1])
                return strndup(str + 1, l - 2);

        return strdup(str);
}

int write_str_to_file(FILE *f, const char *str, enum file_write_flags flags) {
        int r = 0;

        assert(f);
        assert(str);

        STORE_RESET_ERRNO;

        (void) fputs(str, f);
        if ((flags & FILE_WRITE_NEWLINE_IF_NOT) && !endswith(str, "\n"))
                (void) fputc('\n', f);

        if (flags & FILE_WRITE_WITH_FFLUSH)
                (void) fflush(f);

        if (ferror(f))
                r = errno ? -errno : -EIO;

        RESTORE_ERRNO;

        return r;
}

int write_str_to_path(const char *path, const char *str, enum file_write_flags flags) {
        _cleanup_fclose_ FILE *f = NULL;

        assert(path);
        assert(str);

        if (flags & FILE_WRITE_APPEND)
                f = fopen(path, "ae");
        else
                f = fopen(path, "we");
        if (!f)
                return -errno;

        return write_str_to_file(f, str, flags);
}

int read_one_line_from_file(FILE *f, char **line) {
        char t[LINE_MAX], *c;

        assert(f);
        assert(line);

        STORE_RESET_ERRNO;

        if (!fgets(t, sizeof(t), f)) {

                if (ferror(f)) {
                        int r;

                        r = errno ? -errno : -EIO;
                        RESTORE_ERRNO;
                        return r;
                }

                t[0] = 0;
        }

        RESTORE_ERRNO;

        c = strdup(t);
        if (!c)
                return -ENOMEM;

        *line = truncate_nl(c);

        return 0;
}

int read_one_line_from_path(const char *path, char **line) {
        _cleanup_fclose_ FILE *f = NULL;

        assert(path);
        assert(line);

        f = fopen(path, "re");
        if (!f)
                return -errno;

        return read_one_line_from_file(f, line);
}

#define DEFINE_WRITE_NUM_TO_FILE(type, format)                          \
        int write_##type##_to_file(FILE *f,                             \
                                   type##_t u,                          \
                                   enum file_write_flags flags) {       \
                int r = 0;                                              \
                                                                        \
                assert(f);                                              \
                                                                        \
                STORE_RESET_ERRNO;                                      \
                                                                        \
                (void) fprintf(f, format, u);                           \
                if (flags & FILE_WRITE_NEWLINE_IF_NOT)                  \
                        (void) fputc('\n', f);                          \
                                                                        \
                if (flags & FILE_WRITE_WITH_FFLUSH)                     \
                        (void) fflush(f);                               \
                                                                        \
                if (ferror(f))                                          \
                        r = errno ? -errno : -EIO;                      \
                                                                        \
                RESTORE_ERRNO;                                          \
                                                                        \
                return r;                                               \
        }

#define DEFINE_WRITE_NUM_TO_PATH(type)                                  \
        int write_##type##_to_path(const char *path,                    \
                                   type##_t u,                          \
                                   enum file_write_flags flags) {       \
                _cleanup_fclose_ FILE *f = NULL;                        \
                                                                        \
                assert(path);                                           \
                                                                        \
                if (flags & FILE_WRITE_APPEND)                          \
                        f = fopen(path, "ae");                          \
                else                                                    \
                        f = fopen(path, "we");                          \
                if (!f)                                                 \
                        return -errno;                                  \
                                                                        \
                return write_##type##_to_file(f, u, flags);             \
        }

#define DEFINE_WRITE_NUM_DUAL(type, format)     \
        DEFINE_WRITE_NUM_TO_FILE(type, format); \
        DEFINE_WRITE_NUM_TO_PATH(type)

#define DEFINE_READ_NUM_FROM_FILE(type, format)                 \
        int read_##type##_from_file(FILE *f, type##_t *num) {   \
                int r = 0;                                      \
                                                                \
                assert(f);                                      \
                assert(num);                                    \
                                                                \
                STORE_RESET_ERRNO;                              \
                                                                \
                r = fscanf(f, format, num);                     \
                if (r == EOF && ferror(f))                      \
                        r = errno ? -errno : -EOF;              \
                                                                \
                RESTORE_ERRNO;                                  \
                                                                \
                return r;                                       \
        }

#define DEFINE_READ_NUM_FROM_PATH(type)                                 \
        int read_##type##_from_path(const char *path, type##_t *num) {  \
                _cleanup_fclose_ FILE *f = NULL;                        \
                                                                        \
                assert(path);                                           \
                assert(num);                                            \
                                                                        \
                f = fopen(path, "re");                                  \
                if (!f)                                                 \
                        return -errno;                                  \
                                                                        \
                return read_##type##_from_file(f, num);                 \
        }

#define DEFINE_READ_NUM_DUAL(type, format)              \
        DEFINE_READ_NUM_FROM_FILE(type, format);        \
        DEFINE_READ_NUM_FROM_PATH(type)

#define DEFINE_READ_WRITE_NUM_DUAL(type, r_format, w_format)    \
        DEFINE_READ_NUM_DUAL(type, r_format);                   \
        DEFINE_WRITE_NUM_DUAL(type, w_format)

DEFINE_READ_WRITE_NUM_DUAL(int32, "%d", "%d");
DEFINE_READ_WRITE_NUM_DUAL(uint32, "%u", "%u");
DEFINE_READ_WRITE_NUM_DUAL(int64, "%" SCNd64, "%" PRId64);
DEFINE_READ_WRITE_NUM_DUAL(uint64, "%" SCNu64, "%" PRIu64);

int str_to_strv(const char *str, char ***strv, const char *separator) {
        char *w, *state, *p;
        char **v = NULL, **new = NULL;
        size_t l;
        size_t i = 0;

        FOREACH_WORD_SEPARATOR(w, l, str, separator, state) {
                p = strndup(w, l);
                if (!p) {
                        free(v);
                        return -ENOMEM;
                }

                new = (char **) realloc(v, sizeof(char *) * (i + 2));
                if (!new) {
                        free(p);
                        free(v);
                        p = NULL;
                        return -ENOMEM;
                }

                v = new;

                v[i] = p;
                v[i + 1] = NULL;
                i++;
        }

        *strv = v;

        return 0;
}

size_t sizeof_strv(char **strv) {
        size_t u = 0;

        if (!strv)
                return 0;

        while(strv[u++])
                ;

        return u - 1;
}

int strv_attach(char **first, char **second, char ***strv, bool free_second) {
        char **new = NULL;
        size_t n1 = 0, n2 = 0;

        assert(strv);

        if (first)
                n1 = sizeof_strv(first);

        if (second) {
                n2 = sizeof_strv(second);

                new = (char **) realloc(first, sizeof(char *) * (n1 + n2 + 1));
                if (!new)
                        return -ENOMEM;

                first = new;

                memcpy(first + n1, second, sizeof(char *) * (n2 + 1));

                if (free_second)
                        free(second);
        }

        *strv = first;

        return 0;
}

void strv_free_full(char **strv) {
        char **s;

        if (!strv)
                return;

        FOREACH_STRV(s, strv) {
                if (s && *s) {
                        free(*s);
                        *s = NULL;
                }
        }

        free(strv);
        strv = NULL;
}

bool isdir(const char *path) {
        struct stat st;

        assert(path);

        if (lstat(path, &st) < 0)
                return false;

        return S_ISDIR(st.st_mode);
}

int touch(const char *path) {
        _cleanup_fclose_ FILE *f = NULL;

        assert(path);

        f = fopen(path, "w");
        if (!f)
                return -errno;

        return 0;
}

bool mnt_is_mounted(const char *fsname, const char *dir, const char *type, const char *opts) {
        struct mntent *ent;
        FILE *f = NULL;
        bool matched = false;

        f = setmntent("/etc/mtab", "r");
        if (!f)
                return false;

        while ((ent = getmntent(f))) {
                if (fsname) {
                        if (streq(fsname, ent->mnt_fsname))
                                matched = true;
                        else
                                goto no_match;
                }

                if (dir) {
                        if (streq(dir, ent->mnt_dir))
                                matched = true;
                        else
                                goto no_match;
                }

                if (type) {
                        if (streq(type, ent->mnt_type))
                                matched = true;
                        else
                                goto no_match;
                }

                if (opts) {
                        if (streq(opts, ent->mnt_opts))
                                matched = true;
                        else
                                goto no_match;
                }

                if (matched)
                        break;

        no_match:
                matched = false;
        }

        endmntent(f);

        return matched;
}