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