1 /* xwrap.c - wrappers around existing library functions.
2 *
3 * Functions with the x prefix are wrappers that either succeed or kill the
4 * program with an error message, but never return failure. They usually have
5 * the same arguments and return value as the function they wrap.
6 *
7 * Copyright 2006 Rob Landley <rob@landley.net>
8 */
9
10 #include "toys.h"
11
12 // strcpy and strncat with size checking. Size is the total space in "dest",
13 // including null terminator. Exit if there's not enough space for the string
14 // (including space for the null terminator), because silently truncating is
15 // still broken behavior. (And leaving the string unterminated is INSANE.)
xstrncpy(char * dest,char * src,size_t size)16 void 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
xstrncat(char * dest,char * src,size_t size)22 void 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 // We replaced exit(), _exit(), and atexit() with xexit(), _xexit(), and
32 // sigatexit(). This gives _xexit() the option to siglongjmp(toys.rebound, 1)
33 // instead of exiting, lets xexit() report stdout flush failures to stderr
34 // and change the exit code to indicate error, lets our toys.exit function
35 // change happen for signal exit paths and lets us remove the functions
36 // after we've called them.
37
_xexit(void)38 void _xexit(void)
39 {
40 if (toys.rebound) siglongjmp(*toys.rebound, 1);
41
42 _exit(toys.exitval);
43 }
44
xexit(void)45 void xexit(void)
46 {
47 // Call toys.xexit functions in reverse order added.
48 while (toys.xexit) {
49 struct arg_list *al = llist_pop(&toys.xexit);
50
51 // typecast xexit->arg to a function pointer, then call it using invalid
52 // signal 0 to let signal handlers tell actual signal from regular exit.
53 ((void (*)(int))(al->arg))(0);
54
55 free(al);
56 }
57 xflush(1);
58 _xexit();
59 }
60
xmmap(void * addr,size_t length,int prot,int flags,int fd,off_t off)61 void *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 // Die unless we can allocate memory.
xmalloc(size_t size)69 void *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 // Die unless we can allocate prezeroed memory.
xzalloc(size_t size)78 void *xzalloc(size_t size)
79 {
80 void *ret = xmalloc(size);
81 memset(ret, 0, size);
82 return ret;
83 }
84
85 // Die unless we can change the size of an existing allocation, possibly
86 // moving it. (Notice different arguments from libc function.)
xrealloc(void * ptr,size_t size)87 void *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 // Die unless we can allocate a copy of this many bytes of string.
xstrndup(char * s,size_t n)96 char *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 // Die unless we can allocate a copy of this string.
xstrdup(char * s)106 char *xstrdup(char *s)
107 {
108 return xstrndup(s, strlen(s));
109 }
110
xmemdup(void * s,long len)111 void *xmemdup(void *s, long len)
112 {
113 void *ret = xmalloc(len);
114 memcpy(ret, s, len);
115
116 return ret;
117 }
118
119 // Die unless we can allocate enough space to sprintf() into.
xmprintf(char * format,...)120 char *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 // How long is it?
130 len = vsnprintf(0, 0, format, va);
131 len++;
132 va_end(va);
133
134 // Allocate and do the sprintf()
135 ret = xmalloc(len);
136 vsnprintf(ret, len, format, va2);
137 va_end(va2);
138
139 return ret;
140 }
141
142 // if !flush just check for error on stdout without flushing
xflush(int flush)143 void xflush(int flush)
144 {
145 if ((flush && fflush(0)) || ferror(stdout))
146 if (!toys.exitval) perror_msg("write");
147 }
148
xprintf(char * format,...)149 void 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 // Put string with length (does not append newline)
xputsl(char * s,int len)160 void 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 // xputs with no newline
xputsn(char * s)173 void xputsn(char *s)
174 {
175 xputsl(s, strlen(s));
176 }
177
178 // Write string to stdout with newline, flushing and checking for errors
xputs(char * s)179 void xputs(char *s)
180 {
181 puts(s);
182 xflush(0);
183 }
184
xputc(char c)185 void xputc(char c)
186 {
187 if (EOF == fputc(c, stdout)) perror_exit("write");
188 xflush(0);
189 }
190
191 // This is called through the XVFORK macro because parent/child of vfork
192 // share a stack, so child returning from a function would stomp the return
193 // address parent would need. Solution: make vfork() an argument so processes
194 // diverge before function gets called.
xvforkwrap(pid_t pid)195 pid_t __attribute__((returns_twice)) xvforkwrap(pid_t pid)
196 {
197 if (pid == -1) perror_exit("vfork");
198
199 // Signal to xexec() and friends that we vforked so can't recurse
200 if (!pid) toys.stacktop = 0;
201
202 return pid;
203 }
204
205 // Die unless we can exec argv[] (or run builtin command). Note that anything
206 // with a path isn't a builtin, so /bin/sh won't match the builtin sh.
xexec(char ** argv)207 void xexec(char **argv)
208 {
209 // Only recurse to builtin when we have multiplexer and !vfork context.
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 // Spawn child process, capturing stdin/stdout.
221 // argv[]: command to exec. If null, child re-runs original program with
222 // toys.stacktop zeroed.
223 // pipes[2]: Filehandle to move to stdin/stdout of new process.
224 // If -1, replace with pipe handle connected to stdin/stdout.
225 // NULL treated as {0, 1}, I.E. leave stdin/stdout as is
226 // return: pid of child process
xpopen_setup(char ** argv,int * pipes,void (* callback)(void))227 pid_t xpopen_setup(char **argv, int *pipes, void (*callback)(void))
228 {
229 int cestnepasun[4], pid;
230
231 // Make the pipes?
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 // Child process: Dance of the stdin/stdout redirection.
240 // cestnepasun[1]->cestnepasun[0] and cestnepasun[3]->cestnepasun[2]
241 if (pipes) {
242 // if we had no stdin/out, pipe handles could overlap, so test for it
243 // and free up potentially overlapping pipe handles before reuse
244
245 // in child, close read end of output pipe, use write end as new stdout
246 if (cestnepasun[2]) {
247 close(cestnepasun[2]);
248 pipes[1] = cestnepasun[3];
249 }
250
251 // in child, close write end of input pipe, use read end as new stdin
252 if (cestnepasun[1]) {
253 close(cestnepasun[1]);
254 pipes[0] = cestnepasun[0];
255 }
256
257 // If swapping stdin/stdout, dup a filehandle that gets closed before use
258 if (!pipes[1]) pipes[1] = dup(0);
259
260 // Are we redirecting stdin?
261 if (pipes[0]) {
262 dup2(pipes[0], 0);
263 close(pipes[0]);
264 }
265
266 // Are we redirecting stdout?
267 if (pipes[1] != 1) {
268 dup2(pipes[1], 1);
269 close(pipes[1]);
270 }
271 }
272 if (callback) callback();
273 if (argv) xexec(argv);
274
275 // In fork() case, force recursion because we know it's us.
276 if (CFG_TOYBOX_FORK) {
277 toy_init(toys.which, toys.argv);
278 toys.stacktop = 0;
279 toys.which->toy_main();
280 xexit();
281 // In vfork() case, exec /proc/self/exe with high bit of first letter set
282 // to tell main() we reentered.
283 } else {
284 char *s = "/proc/self/exe";
285
286 // We did a nommu-friendly vfork but must exec to continue.
287 // setting high bit of argv[0][0] to let new process know
288 **toys.argv |= 0x80;
289 execv(s, toys.argv);
290 perror_msg_raw(s);
291
292 _exit(127);
293 }
294 }
295
296 // Parent process: vfork had a shared environment, clean up.
297 if (!CFG_TOYBOX_FORK) **toys.argv &= 0x7f;
298
299 if (pipes) {
300 if (cestnepasun[1]) {
301 pipes[0] = cestnepasun[1];
302 close(cestnepasun[0]);
303 }
304 if (cestnepasun[2]) {
305 pipes[1] = cestnepasun[2];
306 close(cestnepasun[3]);
307 }
308 }
309
310 return pid;
311 }
312
xpopen_both(char ** argv,int * pipes)313 pid_t xpopen_both(char **argv, int *pipes)
314 {
315 return xpopen_setup(argv, pipes, 0);
316 }
317
318
319 // Wait for child process to exit, then return adjusted exit code.
xwaitpid(pid_t pid)320 int xwaitpid(pid_t pid)
321 {
322 int status;
323
324 while (-1 == waitpid(pid, &status, 0) && errno == EINTR);
325
326 return WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status)+128;
327 }
328
xpclose_both(pid_t pid,int * pipes)329 int xpclose_both(pid_t pid, int *pipes)
330 {
331 if (pipes) {
332 close(pipes[0]);
333 close(pipes[1]);
334 }
335
336 return xwaitpid(pid);
337 }
338
339 // Wrapper to xpopen with a pipe for just one of stdin/stdout
xpopen(char ** argv,int * pipe,int isstdout)340 pid_t xpopen(char **argv, int *pipe, int isstdout)
341 {
342 int pipes[2], pid;
343
344 pipes[0] = isstdout ? 0 : -1;
345 pipes[1] = isstdout ? -1 : 1;
346 pid = xpopen_both(argv, pipes);
347 *pipe = pid ? pipes[!!isstdout] : -1;
348
349 return pid;
350 }
351
xpclose(pid_t pid,int pipe)352 int xpclose(pid_t pid, int pipe)
353 {
354 close(pipe);
355
356 return xpclose_both(pid, 0);
357 }
358
359 // Call xpopen and wait for it to finish, keeping existing stdin/stdout.
xrun(char ** argv)360 int xrun(char **argv)
361 {
362 return xpclose_both(xpopen_both(argv, 0), 0);
363 }
364
xaccess(char * path,int flags)365 void xaccess(char *path, int flags)
366 {
367 if (access(path, flags)) perror_exit("Can't access '%s'", path);
368 }
369
370 // Die unless we can delete a file. (File must exist to be deleted.)
xunlink(char * path)371 void xunlink(char *path)
372 {
373 if (unlink(path)) perror_exit("unlink '%s'", path);
374 }
375
376 // Die unless we can open/create a file, returning file descriptor.
377 // The meaning of O_CLOEXEC is reversed (it defaults on, pass it to disable)
378 // and WARN_ONLY tells us not to exit.
xcreate_stdio(char * path,int flags,int mode)379 int xcreate_stdio(char *path, int flags, int mode)
380 {
381 int fd = open(path, (flags^O_CLOEXEC)&~WARN_ONLY, mode);
382
383 if (fd == -1) ((mode&WARN_ONLY) ? perror_msg_raw : perror_exit_raw)(path);
384 return fd;
385 }
386
387 // Die unless we can open a file, returning file descriptor.
xopen_stdio(char * path,int flags)388 int xopen_stdio(char *path, int flags)
389 {
390 return xcreate_stdio(path, flags, 0);
391 }
392
xpipe(int * pp)393 void xpipe(int *pp)
394 {
395 if (pipe(pp)) perror_exit("xpipe");
396 }
397
xclose(int fd)398 void xclose(int fd)
399 {
400 if (close(fd)) perror_exit("xclose");
401 }
402
xdup(int fd)403 int xdup(int fd)
404 {
405 if (fd != -1) {
406 fd = dup(fd);
407 if (fd == -1) perror_exit("xdup");
408 }
409 return fd;
410 }
411
412 // Move file descriptor above stdin/stdout/stderr, using /dev/null to consume
413 // old one. (We should never be called with stdin/stdout/stderr closed, but...)
notstdio(int fd)414 int notstdio(int fd)
415 {
416 if (fd<0) return fd;
417
418 while (fd<3) {
419 int fd2 = xdup(fd);
420
421 close(fd);
422 xopen_stdio("/dev/null", O_RDWR);
423 fd = fd2;
424 }
425
426 return fd;
427 }
428
xrename(char * from,char * to)429 void xrename(char *from, char *to)
430 {
431 if (rename(from, to)) perror_exit("rename %s -> %s", from, to);
432 }
433
xtempfile(char * name,char ** tempname)434 int xtempfile(char *name, char **tempname)
435 {
436 int fd;
437
438 *tempname = xmprintf("%s%s", name, "XXXXXX");
439 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
440
441 return fd;
442 }
443
444 // Create a file but don't return stdin/stdout/stderr
xcreate(char * path,int flags,int mode)445 int xcreate(char *path, int flags, int mode)
446 {
447 return notstdio(xcreate_stdio(path, flags, mode));
448 }
449
450 // Open a file descriptor NOT in stdin/stdout/stderr
xopen(char * path,int flags)451 int xopen(char *path, int flags)
452 {
453 return notstdio(xopen_stdio(path, flags));
454 }
455
456 // Open read only, treating "-" as a synonym for stdin, defaulting to warn only
openro(char * path,int flags)457 int openro(char *path, int flags)
458 {
459 if (!strcmp(path, "-")) return 0;
460
461 return xopen(path, flags^WARN_ONLY);
462 }
463
464 // Open read only, treating "-" as a synonym for stdin.
xopenro(char * path)465 int xopenro(char *path)
466 {
467 return openro(path, O_RDONLY|WARN_ONLY);
468 }
469
xfdopen(int fd,char * mode)470 FILE *xfdopen(int fd, char *mode)
471 {
472 FILE *f = fdopen(fd, mode);
473
474 if (!f) perror_exit("xfdopen");
475
476 return f;
477 }
478
479 // Die unless we can open/create a file, returning FILE *.
xfopen(char * path,char * mode)480 FILE *xfopen(char *path, char *mode)
481 {
482 FILE *f = fopen(path, mode);
483 if (!f) perror_exit("No file %s", path);
484 return f;
485 }
486
487 // Die if there's an error other than EOF.
xread(int fd,void * buf,size_t len)488 size_t xread(int fd, void *buf, size_t len)
489 {
490 ssize_t ret = read(fd, buf, len);
491 if (ret < 0) perror_exit("xread");
492
493 return ret;
494 }
495
xreadall(int fd,void * buf,size_t len)496 void xreadall(int fd, void *buf, size_t len)
497 {
498 if (len != readall(fd, buf, len)) perror_exit("xreadall");
499 }
500
501 // There's no xwriteall(), just xwrite(). When we read, there may or may not
502 // be more data waiting. When we write, there is data and it had better go
503 // somewhere.
504
xwrite(int fd,void * buf,size_t len)505 void xwrite(int fd, void *buf, size_t len)
506 {
507 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
508 }
509
510 // Die if lseek fails, probably due to being called on a pipe.
511
xlseek(int fd,off_t offset,int whence)512 off_t xlseek(int fd, off_t offset, int whence)
513 {
514 offset = lseek(fd, offset, whence);
515 if (offset<0) perror_exit("lseek");
516
517 return offset;
518 }
519
xgetcwd(void)520 char *xgetcwd(void)
521 {
522 char *buf = getcwd(NULL, 0);
523 if (!buf) perror_exit("xgetcwd");
524
525 return buf;
526 }
527
xstat(char * path,struct stat * st)528 void xstat(char *path, struct stat *st)
529 {
530 if(stat(path, st)) perror_exit("Can't stat %s", path);
531 }
532
533 // Canonicalize path, even to file with one or more missing components at end.
534 // Returns allocated string for pathname or NULL if doesn't exist
535 // exact = 1 file must exist, 0 dir must exist, -1 show theoretical location,
536 // -2 don't resolve last file
xabspath(char * path,int exact)537 char *xabspath(char *path, int exact)
538 {
539 struct string_list *todo, *done = 0;
540 int try = 9999, dirfd = open("/", O_PATH), missing = 0;
541 char *ret;
542
543 // If this isn't an absolute path, start with cwd.
544 if (*path != '/') {
545 char *temp = xgetcwd();
546
547 splitpath(path, splitpath(temp, &todo));
548 free(temp);
549 } else splitpath(path, &todo);
550
551 // Iterate through path components in todo, prepend processed ones to done.
552 while (todo) {
553 struct string_list *new = llist_pop(&todo), **tail;
554 ssize_t len;
555
556 // Eventually break out of endless loops
557 if (!try--) {
558 errno = ELOOP;
559 goto error;
560 }
561
562 // Removable path componenents.
563 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
564 int x = new->str[1];
565
566 free(new);
567 if (!x) continue;
568 if (done) free(llist_pop(&done));
569 len = 0;
570
571 if (missing) missing--;
572 else {
573 if (-1 == (x = openat(dirfd, "..", O_PATH))) goto error;
574 close(dirfd);
575 dirfd = x;
576 }
577 continue;
578 }
579
580 // Is this a symlink?
581 if (exact == -2 && !todo) len = 0;
582 else len = readlinkat(dirfd, new->str, libbuf, sizeof(libbuf));
583 if (len>4095) goto error;
584
585 // Not a symlink: add to linked list, move dirfd, fail if error
586 if (len<1) {
587 int fd;
588
589 new->next = done;
590 done = new;
591 if (errno == EINVAL && !todo) break;
592 if (errno == ENOENT && exact<0) {
593 missing++;
594 continue;
595 }
596 if (errno != EINVAL && (exact || todo)) goto error;
597
598 fd = openat(dirfd, new->str, O_PATH);
599 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
600 close(dirfd);
601 dirfd = fd;
602 continue;
603 }
604
605 // If this symlink is to an absolute path, discard existing resolved path
606 libbuf[len] = 0;
607 if (*libbuf == '/') {
608 llist_traverse(done, free);
609 done=0;
610 close(dirfd);
611 dirfd = open("/", O_PATH);
612 }
613 free(new);
614
615 // prepend components of new path. Note symlink to "/" will leave new NULL
616 tail = splitpath(libbuf, &new);
617
618 // symlink to "/" will return null and leave tail alone
619 if (new) {
620 *tail = todo;
621 todo = new;
622 }
623 }
624 close(dirfd);
625
626 // At this point done has the path, in reverse order. Reverse list while
627 // calculating buffer length.
628
629 try = 2;
630 while (done) {
631 struct string_list *temp = llist_pop(&done);
632
633 if (todo) try++;
634 try += strlen(temp->str);
635 temp->next = todo;
636 todo = temp;
637 }
638
639 // Assemble return buffer
640
641 ret = xmalloc(try);
642 *ret = '/';
643 ret [try = 1] = 0;
644 while (todo) {
645 if (try>1) ret[try++] = '/';
646 try = stpcpy(ret+try, todo->str) - ret;
647 free(llist_pop(&todo));
648 }
649
650 return ret;
651
652 error:
653 close(dirfd);
654 llist_traverse(todo, free);
655 llist_traverse(done, free);
656
657 return 0;
658 }
659
xchdir(char * path)660 void xchdir(char *path)
661 {
662 if (chdir(path)) perror_exit("chdir '%s'", path);
663 }
664
xchroot(char * path)665 void xchroot(char *path)
666 {
667 if (chroot(path)) error_exit("chroot '%s'", path);
668 xchdir("/");
669 }
670
xgetpwuid(uid_t uid)671 struct passwd *xgetpwuid(uid_t uid)
672 {
673 struct passwd *pwd = getpwuid(uid);
674 if (!pwd) error_exit("bad uid %ld", (long)uid);
675 return pwd;
676 }
677
xgetgrgid(gid_t gid)678 struct group *xgetgrgid(gid_t gid)
679 {
680 struct group *group = getgrgid(gid);
681
682 if (!group) perror_exit("gid %ld", (long)gid);
683 return group;
684 }
685
xgetuid(char * name)686 unsigned xgetuid(char *name)
687 {
688 struct passwd *up = getpwnam(name);
689 char *s = 0;
690 long uid;
691
692 if (up) return up->pw_uid;
693
694 uid = estrtol(name, &s, 10);
695 if (!errno && s && !*s && uid>=0 && uid<=UINT_MAX) return uid;
696
697 error_exit("bad user '%s'", name);
698 }
699
xgetgid(char * name)700 unsigned xgetgid(char *name)
701 {
702 struct group *gr = getgrnam(name);
703 char *s = 0;
704 long gid;
705
706 if (gr) return gr->gr_gid;
707
708 gid = estrtol(name, &s, 10);
709 if (!errno && s && !*s && gid>=0 && gid<=UINT_MAX) return gid;
710
711 error_exit("bad group '%s'", name);
712 }
713
xgetpwnam(char * name)714 struct passwd *xgetpwnam(char *name)
715 {
716 struct passwd *up = getpwnam(name);
717
718 if (!up) perror_exit("user '%s'", name);
719 return up;
720 }
721
xgetgrnam(char * name)722 struct group *xgetgrnam(char *name)
723 {
724 struct group *gr = getgrnam(name);
725
726 if (!gr) perror_exit("group '%s'", name);
727 return gr;
728 }
729
730 // setuid() can fail (for example, too many processes belonging to that user),
731 // which opens a security hole if the process continues as the original user.
732
xsetuser(struct passwd * pwd)733 void xsetuser(struct passwd *pwd)
734 {
735 if (initgroups(pwd->pw_name, pwd->pw_gid) || setgid(pwd->pw_uid)
736 || setuid(pwd->pw_uid)) perror_exit("xsetuser '%s'", pwd->pw_name);
737 }
738
739 // This can return null (meaning file not found). It just won't return null
740 // for memory allocation reasons.
xreadlink(char * name)741 char *xreadlink(char *name)
742 {
743 int len, size = 0;
744 char *buf = 0;
745
746 // Grow by 64 byte chunks until it's big enough.
747 for(;;) {
748 size +=64;
749 buf = xrealloc(buf, size);
750 len = readlink(name, buf, size);
751
752 if (len<0) {
753 free(buf);
754 return 0;
755 }
756 if (len<size) {
757 buf[len]=0;
758 return buf;
759 }
760 }
761 }
762
xreadfile(char * name,char * buf,off_t len)763 char *xreadfile(char *name, char *buf, off_t len)
764 {
765 if (!(buf = readfile(name, buf, len))) perror_exit("Bad '%s'", name);
766
767 return buf;
768 }
769
770 // The data argument to ioctl() is actually long, but it's usually used as
771 // a pointer. If you need to feed in a number, do (void *)(long) typecast.
xioctl(int fd,int request,void * data)772 int xioctl(int fd, int request, void *data)
773 {
774 int rc;
775
776 errno = 0;
777 rc = ioctl(fd, request, data);
778 if (rc == -1 && errno) perror_exit("ioctl %x", request);
779
780 return rc;
781 }
782
783 // Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
784 // exists and is this executable.
xpidfile(char * name)785 void xpidfile(char *name)
786 {
787 char pidfile[256], spid[32];
788 int i, fd;
789 pid_t pid;
790
791 sprintf(pidfile, "/var/run/%s.pid", name);
792 // Try three times to open the sucker.
793 for (i=0; i<3; i++) {
794 fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);
795 if (fd != -1) break;
796
797 // If it already existed, read it. Loop for race condition.
798 fd = open(pidfile, O_RDONLY);
799 if (fd == -1) continue;
800
801 // Is the old program still there?
802 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
803 close(fd);
804 pid = atoi(spid);
805 if (pid < 1 || (kill(pid, 0) && errno == ESRCH)) unlink(pidfile);
806
807 // An else with more sanity checking might be nice here.
808 }
809
810 if (i == 3) error_exit("xpidfile %s", name);
811
812 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
813 close(fd);
814 }
815
816 // Return bytes copied from in to out. If bytes <0 copy all of in to out.
817 // If consuemd isn't null, amount read saved there (return is written or error)
sendfile_len(int in,int out,long long bytes,long long * consumed)818 long long sendfile_len(int in, int out, long long bytes, long long *consumed)
819 {
820 long long total = 0, len;
821
822 if (consumed) *consumed = 0;
823 if (in<0) return 0;
824 while (bytes != total) {
825 len = bytes-total;
826 if (bytes<0 || len>sizeof(libbuf)) len = sizeof(libbuf);
827
828 len = read(in, libbuf, len);
829 if (!len && errno==EAGAIN) continue;
830 if (len<1) break;
831 if (consumed) *consumed += len;
832 if (writeall(out, libbuf, len) != len) return -1;
833 total += len;
834 }
835
836 return total;
837 }
838
839 // error_exit if we couldn't copy all bytes
xsendfile_len(int in,int out,long long bytes)840 long long xsendfile_len(int in, int out, long long bytes)
841 {
842 long long len = sendfile_len(in, out, bytes, 0);
843
844 if (bytes != -1 && bytes != len) {
845 if (out == 1 && len<0) xexit();
846 error_exit("short %s", (len<0) ? "write" : "read");
847 }
848
849 return len;
850 }
851
852 // warn and pad with zeroes if we couldn't copy all bytes
xsendfile_pad(int in,int out,long long len)853 void xsendfile_pad(int in, int out, long long len)
854 {
855 len -= xsendfile_len(in, out, len);
856 if (len) {
857 perror_msg("short read");
858 memset(libbuf, 0, sizeof(libbuf));
859 while (len) {
860 int i = len>sizeof(libbuf) ? sizeof(libbuf) : len;
861
862 xwrite(out, libbuf, i);
863 len -= i;
864 }
865 }
866 }
867
868 // copy all of in to out
xsendfile(int in,int out)869 long long xsendfile(int in, int out)
870 {
871 return xsendfile_len(in, out, -1);
872 }
873
xstrtod(char * s)874 double xstrtod(char *s)
875 {
876 char *end;
877 double d;
878
879 errno = 0;
880 d = strtod(s, &end);
881 if (!errno && *end) errno = E2BIG;
882 if (errno) perror_exit("strtod %s", s);
883
884 return d;
885 }
886
887 // parse fractional seconds with optional s/m/h/d suffix
xparsetime(char * arg,long zeroes,long * fraction)888 long xparsetime(char *arg, long zeroes, long *fraction)
889 {
890 long l, fr = 0, mask = 1;
891 char *end;
892
893 if (*arg != '.' && !isdigit(*arg)) error_exit("Not a number '%s'", arg);
894 l = strtoul(arg, &end, 10);
895 if (*end == '.') {
896 end++;
897 while (zeroes--) {
898 fr *= 10;
899 mask *= 10;
900 if (isdigit(*end)) fr += *end++-'0';
901 }
902 while (isdigit(*end)) end++;
903 }
904
905 // Parse suffix
906 if (*end) {
907 int ismhd[]={1,60,3600,86400}, i = stridx("smhd", *end);
908
909 if (i == -1 || *(end+1)) error_exit("Unknown suffix '%s'", end);
910 l *= ismhd[i];
911 fr *= ismhd[i];
912 l += fr/mask;
913 fr %= mask;
914 }
915 if (fraction) *fraction = fr;
916
917 return l;
918 }
919
xparsemillitime(char * arg)920 long long xparsemillitime(char *arg)
921 {
922 long l, ll;
923
924 l = xparsetime(arg, 3, &ll);
925
926 return (l*1000LL)+ll;
927 }
928
929
930
931 // Compile a regular expression into a regex_t
xregcomp(regex_t * preg,char * regex,int cflags)932 void xregcomp(regex_t *preg, char *regex, int cflags)
933 {
934 int rc;
935
936 // BSD regex implementations don't support the empty regex (which isn't
937 // allowed in the POSIX grammar), but glibc does. Fake it for BSD.
938 if (!*regex) {
939 regex = "()";
940 cflags |= REG_EXTENDED;
941 }
942
943 if ((rc = regcomp(preg, regex, cflags))) {
944 regerror(rc, preg, libbuf, sizeof(libbuf));
945 error_exit("bad regex: %s", libbuf);
946 }
947 }
948
xtzset(char * new)949 char *xtzset(char *new)
950 {
951 char *old = getenv("TZ");
952
953 if (old) old = xstrdup(old);
954 if (new ? setenv("TZ", new, 1) : unsetenv("TZ")) perror_exit("setenv");
955 tzset();
956
957 return old;
958 }
959
960 // Set a signal handler
xsignal_flags(int signal,void * handler,int flags)961 void xsignal_flags(int signal, void *handler, int flags)
962 {
963 struct sigaction *sa = (void *)libbuf;
964
965 memset(sa, 0, sizeof(struct sigaction));
966 sa->sa_handler = handler;
967 sa->sa_flags = flags;
968
969 if (sigaction(signal, sa, 0)) perror_exit("xsignal %d", signal);
970 }
971
xsignal(int signal,void * handler)972 void xsignal(int signal, void *handler)
973 {
974 xsignal_flags(signal, handler, 0);
975 }
976
977
xvali_date(struct tm * tm,char * str)978 time_t xvali_date(struct tm *tm, char *str)
979 {
980 time_t t;
981
982 if (tm && (unsigned)tm->tm_sec<=60 && (unsigned)tm->tm_min<=59
983 && (unsigned)tm->tm_hour<=23 && tm->tm_mday && (unsigned)tm->tm_mday<=31
984 && (unsigned)tm->tm_mon<=11 && (t = mktime(tm)) != -1) return t;
985
986 error_exit("bad date %s", str);
987 }
988
989 // Parse date string (relative to current *t). Sets time_t and nanoseconds.
xparsedate(char * str,time_t * t,unsigned * nano,int endian)990 void xparsedate(char *str, time_t *t, unsigned *nano, int endian)
991 {
992 struct tm tm;
993 time_t now = *t;
994 int len = 0, i = 0;
995 // Formats with seconds come first. Posix can't agree on whether 12 digits
996 // has year before (touch -t) or year after (date), so support both.
997 char *s = str, *p, *oldtz = 0, *formats[] = {"%Y-%m-%d %T", "%Y-%m-%dT%T",
998 "%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d", "%H:%M", "%m%d%H%M",
999 endian ? "%m%d%H%M%y" : "%y%m%d%H%M",
1000 endian ? "%m%d%H%M%C%y" : "%C%y%m%d%H%M"};
1001
1002 *nano = 0;
1003
1004 // Parse @UNIXTIME[.FRACTION]
1005 if (*str == '@') {
1006 long long ll;
1007
1008 // Collect seconds and nanoseconds.
1009 // &ll is not just t because we can't guarantee time_t is 64 bit (yet).
1010 sscanf(s, "@%lld%n", &ll, &len);
1011 if (s[len]=='.') {
1012 s += len+1;
1013 for (len = 0; len<9; len++) {
1014 *nano *= 10;
1015 if (isdigit(*s)) *nano += *s++-'0';
1016 }
1017 }
1018 *t = ll;
1019 if (!s[len]) return;
1020 xvali_date(0, str);
1021 }
1022
1023 // Trailing Z means UTC timezone, don't expect libc to know this.
1024 // (Trimming it off here means it won't show up in error messages.)
1025 if ((i = strlen(str)) && toupper(str[i-1])=='Z') {
1026 str[--i] = 0;
1027 oldtz = getenv("TZ");
1028 if (oldtz) oldtz = xstrdup(oldtz);
1029 setenv("TZ", "UTC0", 1);
1030 }
1031
1032 // Try each format
1033 for (i = 0; i<ARRAY_LEN(formats); i++) {
1034 localtime_r(&now, &tm);
1035 tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
1036 tm.tm_isdst = -endian;
1037
1038 if ((p = strptime(s, formats[i], &tm))) {
1039 if (*p == '.') {
1040 p++;
1041 // If format didn't already specify seconds, grab seconds
1042 if (i>2) {
1043 len = 0;
1044 sscanf(p, "%2u%n", &tm.tm_sec, &len);
1045 p += len;
1046 }
1047 // nanoseconds
1048 for (len = 0; len<9; len++) {
1049 *nano *= 10;
1050 if (isdigit(*p)) *nano += *p++-'0';
1051 }
1052 }
1053
1054 if (!*p) break;
1055 }
1056 }
1057
1058 // Sanity check field ranges
1059 *t = xvali_date((i!=ARRAY_LEN(formats)) ? &tm : 0, str);
1060
1061 if (oldtz) setenv("TZ", oldtz, 1);
1062 free(oldtz);
1063 }
1064
xgetline(FILE * fp,int * len)1065 char *xgetline(FILE *fp, int *len)
1066 {
1067 char *new = 0;
1068 size_t linelen = 0;
1069 long ll;
1070
1071 errno = 0;
1072 if (1>(ll = getline(&new, &linelen, fp))) {
1073 if (errno) perror_msg("getline");
1074 new = 0;
1075 } else if (new[linelen-1] == '\n') new[--linelen] = 0;
1076 if (len) *len = ll;
1077
1078 return new;
1079 }
1080