1
2
3
4
5
6
7
8
9
10#include "toys.h"
11
12
13
14
15
16void xstrncpy(char *dest, char *src, size_t size)
17{
18 if (strlen(src)+1 > size) error_exit("'%s' > %ld bytes", src, (long)size);
19 strcpy(dest, src);
20}
21
22void xstrncat(char *dest, char *src, size_t size)
23{
24 long len = strlen(dest);
25
26 if (len+strlen(src)+1 > size)
27 error_exit("'%s%s' > %ld bytes", dest, src, (long)size);
28 strcpy(dest+len, src);
29}
30
31
32
33
34
35
36
37
38void _xexit(void)
39{
40 if (toys.rebound) siglongjmp(*toys.rebound, 1);
41
42 _exit(toys.exitval);
43}
44
45void xexit(void)
46{
47
48 while (toys.xexit) {
49 struct arg_list *al = llist_pop(&toys.xexit);
50
51
52
53 ((void (*)(int))(al->arg))(0);
54
55 free(al);
56 }
57 xflush(1);
58 _xexit();
59}
60
61void *xmmap(void *addr, size_t length, int prot, int flags, int fd, off_t off)
62{
63 void *ret = mmap(addr, length, prot, flags, fd, off);
64 if (ret == MAP_FAILED) perror_exit("mmap");
65 return ret;
66}
67
68
69void *xmalloc(size_t size)
70{
71 void *ret = malloc(size);
72 if (!ret) error_exit("xmalloc(%ld)", (long)size);
73
74 return ret;
75}
76
77
78void *xzalloc(size_t size)
79{
80 void *ret = xmalloc(size);
81 memset(ret, 0, size);
82 return ret;
83}
84
85
86
87void *xrealloc(void *ptr, size_t size)
88{
89 ptr = realloc(ptr, size);
90 if (!ptr) error_exit("xrealloc");
91
92 return ptr;
93}
94
95
96char *xstrndup(char *s, size_t n)
97{
98 char *ret = strndup(s, n);
99
100 if (!ret) error_exit("xstrndup");
101
102 return ret;
103}
104
105
106char *xstrdup(char *s)
107{
108 return xstrndup(s, strlen(s));
109}
110
111void *xmemdup(void *s, long len)
112{
113 void *ret = xmalloc(len);
114 memcpy(ret, s, len);
115
116 return ret;
117}
118
119
120char *xmprintf(char *format, ...)
121{
122 va_list va, va2;
123 int len;
124 char *ret;
125
126 va_start(va, format);
127 va_copy(va2, va);
128
129
130 len = vsnprintf(0, 0, format, va);
131 len++;
132 va_end(va);
133
134
135 ret = xmalloc(len);
136 vsnprintf(ret, len, format, va2);
137 va_end(va2);
138
139 return ret;
140}
141
142
143void xflush(int flush)
144{
145 if ((flush && fflush(0)) || ferror(stdout))
146 if (!toys.exitval) perror_msg("write");
147}
148
149void xprintf(char *format, ...)
150{
151 va_list va;
152 va_start(va, format);
153
154 vprintf(format, va);
155 va_end(va);
156 xflush(0);
157}
158
159
160void xputsl(char *s, int len)
161{
162 int out;
163
164 while (len != (out = fwrite(s, 1, len, stdout))) {
165 if (out<1) perror_exit("write");
166 len -= out;
167 s += out;
168 }
169 xflush(0);
170}
171
172
173void xputsn(char *s)
174{
175 xputsl(s, strlen(s));
176}
177
178
179void xputs(char *s)
180{
181 puts(s);
182 xflush(0);
183}
184
185void xputc(char c)
186{
187 if (EOF == fputc(c, stdout)) perror_exit("write");
188 xflush(0);
189}
190
191
192
193
194
195pid_t __attribute__((returns_twice)) xvforkwrap(pid_t pid)
196{
197 if (pid == -1) perror_exit("vfork");
198
199
200 toys.stacktop = 0;
201
202 return pid;
203}
204
205
206
207void xexec(char **argv)
208{
209
210 if (CFG_TOYBOX && !CFG_TOYBOX_NORECURSE && toys.stacktop && **argv != '/')
211 toy_exec(argv);
212 execvp(argv[0], argv);
213
214 toys.exitval = 126+(errno == ENOENT);
215 perror_msg("exec %s", argv[0]);
216 if (!toys.stacktop) _exit(toys.exitval);
217 xexit();
218}
219
220
221
222
223
224
225
226
227pid_t xpopen_both(char **argv, int *pipes)
228{
229 int cestnepasun[4], pid;
230
231
232 memset(cestnepasun, 0, sizeof(cestnepasun));
233 if (pipes) for (pid = 0; pid < 2; pid++) {
234 if (pipes[pid] != -1) continue;
235 if (pipe(cestnepasun+(2*pid))) perror_exit("pipe");
236 }
237
238 if (!(pid = CFG_TOYBOX_FORK ? xfork() : XVFORK())) {
239
240
241 if (pipes) {
242
243
244
245
246 if (cestnepasun[2]) {
247 close(cestnepasun[2]);
248 pipes[1] = cestnepasun[3];
249 }
250
251
252 if (cestnepasun[1]) {
253 close(cestnepasun[1]);
254 pipes[0] = cestnepasun[0];
255 }
256
257
258 if (!pipes[1]) pipes[1] = dup(0);
259
260
261 if (pipes[0]) {
262 dup2(pipes[0], 0);
263 close(pipes[0]);
264 }
265
266
267 if (pipes[1] != 1) {
268 dup2(pipes[1], 1);
269 close(pipes[1]);
270 }
271 }
272 if (argv) xexec(argv);
273
274
275 if (CFG_TOYBOX_FORK) {
276 toy_init(toys.which, toys.argv);
277 toys.stacktop = 0;
278 toys.which->toy_main();
279 xexit();
280
281
282 } else {
283 char *s = "/proc/self/exe";
284
285
286
287 **toys.argv |= 0x80;
288 execv(s, toys.argv);
289 perror_msg_raw(s);
290
291 _exit(127);
292 }
293 }
294
295
296 if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
297
298 if (pipes) {
299 if (cestnepasun[1]) {
300 pipes[0] = cestnepasun[1];
301 close(cestnepasun[0]);
302 }
303 if (cestnepasun[2]) {
304 pipes[1] = cestnepasun[2];
305 close(cestnepasun[3]);
306 }
307 }
308
309 return pid;
310}
311
312
313int xwaitpid(pid_t pid)
314{
315 int status;
316
317 while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
318
319 return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+127;
320}
321
322int xpclose_both(pid_t pid, int *pipes)
323{
324 if (pipes) {
325 close(pipes[0]);
326 close(pipes[1]);
327 }
328
329 return xwaitpid(pid);
330}
331
332
333pid_t xpopen(char **argv, int *pipe, int isstdout)
334{
335 int pipes[2], pid;
336
337 pipes[0] = isstdout ? 0 : -1;
338 pipes[1] = isstdout ? -1 : 1;
339 pid = xpopen_both(argv, pipes);
340 *pipe = pid ? pipes[!!isstdout] : -1;
341
342 return pid;
343}
344
345int xpclose(pid_t pid, int pipe)
346{
347 close(pipe);
348
349 return xpclose_both(pid, 0);
350}
351
352
353int xrun(char **argv)
354{
355 return xpclose_both(xpopen_both(argv, 0), 0);
356}
357
358void xaccess(char *path, int flags)
359{
360 if (access(path, flags)) perror_exit("Can't access '%s'", path);
361}
362
363
364void xunlink(char *path)
365{
366 if (unlink(path)) perror_exit("unlink '%s'", path);
367}
368
369
370
371
372int xcreate_stdio(char *path, int flags, int mode)
373{
374 int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
375
376 if (fd == -1) ((mode&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
377 return fd;
378}
379
380
381int xopen_stdio(char *path, int flags)
382{
383 return xcreate_stdio(path, flags, 0);
384}
385
386void xpipe(int *pp)
387{
388 if (pipe(pp)) perror_exit("xpipe");
389}
390
391void xclose(int fd)
392{
393 if (close(fd)) perror_exit("xclose");
394}
395
396int xdup(int fd)
397{
398 if (fd != -1) {
399 fd = dup(fd);
400 if (fd == -1) perror_exit("xdup");
401 }
402 return fd;
403}
404
405
406
407int notstdio(int fd)
408{
409 if (fd<0) return fd;
410
411 while (fd<3) {
412 int fd2 = xdup(fd);
413
414 close(fd);
415 xopen_stdio("/dev/null", O_RDWR);
416 fd = fd2;
417 }
418
419 return fd;
420}
421
422void xrename(char *from, char *to)
423{
424 if (rename(from, to)) perror_exit("rename %s -> %s", from, to);
425}
426
427int xtempfile(char *name, char **tempname)
428{
429 int fd;
430
431 *tempname = xmprintf("%s%s", name, "XXXXXX");
432 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
433
434 return fd;
435}
436
437
438int xcreate(char *path, int flags, int mode)
439{
440 return notstdio(xcreate_stdio(path, flags, mode));
441}
442
443
444int xopen(char *path, int flags)
445{
446 return notstdio(xopen_stdio(path, flags));
447}
448
449
450int openro(char *path, int flags)
451{
452 if (!strcmp(path, "-")) return 0;
453
454 return xopen(path, flags^WARN_ONLY);
455}
456
457
458int xopenro(char *path)
459{
460 return openro(path, O_RDONLY|WARN_ONLY);
461}
462
463FILE *xfdopen(int fd, char *mode)
464{
465 FILE *f = fdopen(fd, mode);
466
467 if (!f) perror_exit("xfdopen");
468
469 return f;
470}
471
472
473FILE *xfopen(char *path, char *mode)
474{
475 FILE *f = fopen(path, mode);
476 if (!f) perror_exit("No file %s", path);
477 return f;
478}
479
480
481size_t xread(int fd, void *buf, size_t len)
482{
483 ssize_t ret = read(fd, buf, len);
484 if (ret < 0) perror_exit("xread");
485
486 return ret;
487}
488
489void xreadall(int fd, void *buf, size_t len)
490{
491 if (len != readall(fd, buf, len)) perror_exit("xreadall");
492}
493
494
495
496
497
498void xwrite(int fd, void *buf, size_t len)
499{
500 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
501}
502
503
504
505off_t xlseek(int fd, off_t offset, int whence)
506{
507 offset = lseek(fd, offset, whence);
508 if (offset<0) perror_exit("lseek");
509
510 return offset;
511}
512
513char *xgetcwd(void)
514{
515 char *buf = getcwd(NULL, 0);
516 if (!buf) perror_exit("xgetcwd");
517
518 return buf;
519}
520
521void xstat(char *path, struct stat *st)
522{
523 if(stat(path, st)) perror_exit("Can't stat %s", path);
524}
525
526
527
528
529char *xabspath(char *path, int exact)
530{
531 struct string_list *todo, *done = 0;
532 int try = 9999, dirfd = open("/", O_PATH), missing = 0;
533 char *ret;
534
535
536 if (*path != '/') {
537 char *temp = xgetcwd();
538
539 splitpath(path, splitpath(temp, &todo));
540 free(temp);
541 } else splitpath(path, &todo);
542
543
544 while (todo) {
545 struct string_list *new = llist_pop(&todo), **tail;
546 ssize_t len;
547
548
549 if (!try--) {
550 errno = ELOOP;
551 goto error;
552 }
553
554
555 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
556 int x = new->str[1];
557
558 free(new);
559 if (!x) continue;
560 if (done) free(llist_pop(&done));
561 len = 0;
562
563 if (missing) missing--;
564 else {
565 if (-1 == (x = openat(dirfd, "..", O_PATH))) goto error;
566 close(dirfd);
567 dirfd = x;
568 }
569 continue;
570 }
571
572
573 len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
574 if (len>4095) goto error;
575
576
577 if (len<1) {
578 int fd;
579
580 new->next = done;
581 done = new;
582 if (errno == EINVAL && !todo) break;
583 if (errno == ENOENT && exact<0) {
584 missing++;
585 continue;
586 }
587 if (errno != EINVAL && (exact || todo)) goto error;
588
589 fd = openat(dirfd, new->str, O_PATH);
590 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
591 close(dirfd);
592 dirfd = fd;
593 continue;
594 }
595
596
597 libbuf[len] = 0;
598 if (*libbuf == '/') {
599 llist_traverse(done, free);
600 done=0;
601 close(dirfd);
602 dirfd = open("/", O_PATH);
603 }
604 free(new);
605
606
607 tail = splitpath(libbuf, &new);
608
609
610 if (new) {
611 *tail = todo;
612 todo = new;
613 }
614 }
615 close(dirfd);
616
617
618
619
620 try = 2;
621 while (done) {
622 struct string_list *temp = llist_pop(&done);
623
624 if (todo) try++;
625 try += strlen(temp->str);
626 temp->next = todo;
627 todo = temp;
628 }
629
630
631
632 ret = xmalloc(try);
633 *ret = '/';
634 ret [try = 1] = 0;
635 while (todo) {
636 if (try>1) ret[try++] = '/';
637 try = stpcpy(ret+try, todo->str) - ret;
638 free(llist_pop(&todo));
639 }
640
641 return ret;
642
643error:
644 close(dirfd);
645 llist_traverse(todo, free);
646 llist_traverse(done, free);
647
648 return 0;
649}
650
651void xchdir(char *path)
652{
653 if (chdir(path)) perror_exit("chdir '%s'", path);
654}
655
656void xchroot(char *path)
657{
658 if (chroot(path)) error_exit("chroot '%s'", path);
659 xchdir("/");
660}
661
662struct passwd *xgetpwuid(uid_t uid)
663{
664 struct passwd *pwd = getpwuid(uid);
665 if (!pwd) error_exit("bad uid %ld", (long)uid);
666 return pwd;
667}
668
669struct group *xgetgrgid(gid_t gid)
670{
671 struct group *group = getgrgid(gid);
672
673 if (!group) perror_exit("gid %ld", (long)gid);
674 return group;
675}
676
677unsigned xgetuid(char *name)
678{
679 struct passwd *up = getpwnam(name);
680 char *s = 0;
681 long uid;
682
683 if (up) return up->pw_uid;
684
685 uid = estrtol(name, &s, 10);
686 if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
687
688 error_exit("bad user '%s'", name);
689}
690
691unsigned xgetgid(char *name)
692{
693 struct group *gr = getgrnam(name);
694 char *s = 0;
695 long gid;
696
697 if (gr) return gr->gr_gid;
698
699 gid = estrtol(name, &s, 10);
700 if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
701
702 error_exit("bad group '%s'", name);
703}
704
705struct passwd *xgetpwnam(char *name)
706{
707 struct passwd *up = getpwnam(name);
708
709 if (!up) perror_exit("user '%s'", name);
710 return up;
711}
712
713struct group *xgetgrnam(char *name)
714{
715 struct group *gr = getgrnam(name);
716
717 if (!gr) perror_exit("group '%s'", name);
718 return gr;
719}
720
721
722
723
724void xsetuser(struct passwd *pwd)
725{
726 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
727 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
728}
729
730
731
732char *xreadlink(char *name)
733{
734 int len, size = 0;
735 char *buf = 0;
736
737
738 for(;;) {
739 size +=64;
740 buf = xrealloc(buf, size);
741 len = readlink(name, buf, size);
742
743 if (len<0) {
744 free(buf);
745 return 0;
746 }
747 if (len<size) {
748 buf[len]=0;
749 return buf;
750 }
751 }
752}
753
754char *xreadfile(char *name, char *buf, off_t len)
755{
756 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
757
758 return buf;
759}
760
761
762
763int xioctl(int fd, int request, void *data)
764{
765 int rc;
766
767 errno = 0;
768 rc = ioctl(fd, request, data);
769 if (rc == -1 && errno) perror_exit("ioctl %x", request);
770
771 return rc;
772}
773
774
775
776void xpidfile(char *name)
777{
778 char pidfile[256], spid[32];
779 int i, fd;
780 pid_t pid;
781
782 sprintf(pidfile, "/var/run/%s.pid", name);
783
784 for (i=0; i<3; i++) {
785 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
786 if (fd != -1) break;
787
788
789 fd = open(pidfile, O_RDONLY);
790 if (fd == -1) continue;
791
792
793 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
794 close(fd);
795 pid = atoi(spid);
796 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
797
798
799 }
800
801 if (i == 3) error_exit("xpidfile %s", name);
802
803 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
804 close(fd);
805}
806
807
808
809long long sendfile_len(int in, int out, long long bytes, long long *consumed)
810{
811 long long total = 0, len;
812
813 if (consumed) *consumed = 0;
814 if (in<0) return 0;
815 while (bytes != total) {
816 len = bytes-total;
817 if (bytes<0 || len>sizeof(libbuf)) len = sizeof(libbuf);
818
819 len = read(in, libbuf, len);
820 if (!len && errno==EAGAIN) continue;
821 if (len<1) break;
822 if (consumed) *consumed += len;
823 if (writeall(out, libbuf, len) != len) return -1;
824 total += len;
825 }
826
827 return total;
828}
829
830
831long long xsendfile_len(int in, int out, long long bytes)
832{
833 long long len = sendfile_len(in, out, bytes, 0);
834
835 if (bytes != -1 && bytes != len) {
836 if (out == 1 && len<0) xexit();
837 error_exit("short %s", (len<0) ? "write" : "read");
838 }
839
840 return len;
841}
842
843
844void xsendfile_pad(int in, int out, long long len)
845{
846 len -= xsendfile_len(in, out, len);
847 if (len) {
848 perror_msg("short read");
849 memset(libbuf, 0, sizeof(libbuf));
850 while (len) {
851 int i = len>sizeof(libbuf) ? sizeof(libbuf) : len;
852
853 xwrite(out, libbuf, i);
854 len -= i;
855 }
856 }
857}
858
859
860long long xsendfile(int in, int out)
861{
862 return xsendfile_len(in, out, -1);
863}
864
865double xstrtod(char *s)
866{
867 char *end;
868 double d;
869
870 errno = 0;
871 d = strtod(s, &end);
872 if (!errno && *end) errno = E2BIG;
873 if (errno) perror_exit("strtod %s", s);
874
875 return d;
876}
877
878
879long xparsetime(char *arg, long zeroes, long *fraction)
880{
881 long l, fr = 0, mask = 1;
882 char *end;
883
884 if (*arg != '.' && !isdigit(*arg)) error_exit("Not a number '%s'", arg);
885 l = strtoul(arg, &end, 10);
886 if (*end == '.') {
887 end++;
888 while (zeroes--) {
889 fr *= 10;
890 mask *= 10;
891 if (isdigit(*end)) fr += *end++-'0';
892 }
893 while (isdigit(*end)) end++;
894 }
895
896
897 if (*end) {
898 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *end);
899
900 if (i == -1 || *(end+1)) error_exit("Unknown suffix '%s'", end);
901 l *= ismhd[i];
902 fr *= ismhd[i];
903 l += fr/mask;
904 fr %= mask;
905 }
906 if (fraction) *fraction = fr;
907
908 return l;
909}
910
911long long xparsemillitime(char *arg)
912{
913 long l, ll;
914
915 l = xparsetime(arg, 3, &ll);
916
917 return (l*1000LL)+ll;
918}
919
920
921
922
923void xregcomp(regex_t *preg, char *regex, int cflags)
924{
925 int rc = regcomp(preg, regex, cflags);
926
927 if (rc) {
928 regerror(rc, preg, libbuf, sizeof(libbuf));
929 error_exit("xregcomp: %s", libbuf);
930 }
931}
932
933char *xtzset(char *new)
934{
935 char *old = getenv("TZ");
936
937 if (old) old = xstrdup(old);
938 if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
939 tzset();
940
941 return old;
942}
943
944
945void xsignal_flags(int signal, void *handler, int flags)
946{
947 struct sigaction *sa = (void *)libbuf;
948
949 memset(sa, 0, sizeof(struct sigaction));
950 sa->sa_handler = handler;
951 sa->sa_flags = flags;
952
953 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
954}
955
956void xsignal(int signal, void *handler)
957{
958 xsignal_flags(signal, handler, 0);
959}
960
961
962time_t xvali_date(struct tm *tm, char *str)
963{
964 time_t t;
965
966 if (tm && (unsigned)tm->tm_sec<=60 && (unsigned)tm->tm_min<=59
967 && (unsigned)tm->tm_hour<=23 && tm->tm_mday && (unsigned)tm->tm_mday<=31
968 && (unsigned)tm->tm_mon<=11 && (t = mktime(tm)) != -1) return t;
969
970 error_exit("bad date %s", str);
971}
972
973
974void xparsedate(char *str, time_t *t, unsigned *nano, int endian)
975{
976 struct tm tm;
977 time_t now = *t;
978 int len = 0, i = 0;
979
980
981 char *s = str, *p, *oldtz = 0, *formats[] = {"%Y-%m-%d %T", "%Y-%m-%dT%T",
982 "%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M", "%m%d%H%M",
983 endian ? "%m%d%H%M%y" : "%y%m%d%H%M",
984 endian ? "%m%d%H%M%C%y" : "%C%y%m%d%H%M"};
985
986 *nano = 0;
987
988
989 if (*str == '@') {
990 long long ll;
991
992
993
994 sscanf(s, "@%lld%n", &ll, &len);
995 if (s[len]=='.') {
996 s += len+1;
997 for (len = 0; len<9; len++) {
998 *nano *= 10;
999 if (isdigit(*s)) *nano += *s++-'0';
1000 }
1001 }
1002 *t = ll;
1003 if (!s[len]) return;
1004 xvali_date(0, str);
1005 }
1006
1007
1008
1009 if ((i = strlen(str)) && toupper(str[i-1])=='Z') {
1010 str[--i] = 0;
1011 oldtz = getenv("TZ");
1012 if (oldtz) oldtz = xstrdup(oldtz);
1013 setenv("TZ", "UTC0", 1);
1014 }
1015
1016
1017 for (i = 0; i<ARRAY_LEN(formats); i++) {
1018 localtime_r(&now, &tm);
1019 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
1020 tm.tm_isdst = -endian;
1021
1022 if ((p = strptime(s, formats[i], &tm))) {
1023 if (*p == '.') {
1024 p++;
1025
1026 if (i>2) {
1027 len = 0;
1028 sscanf(p, "%2u%n", &tm.tm_sec, &len);
1029 p += len;
1030 }
1031
1032 for (len = 0; len<9; len++) {
1033 *nano *= 10;
1034 if (isdigit(*p)) *nano += *p++-'0';
1035 }
1036 }
1037
1038 if (!*p) break;
1039 }
1040 }
1041
1042
1043 *t = xvali_date((i!=ARRAY_LEN(formats)) ? &tm : 0, str);
1044
1045 if (oldtz) setenv("TZ", oldtz, 1);
1046 free(oldtz);
1047}
1048