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