blob: 955f242622cf1eb7761d53b06b679f7dd0c7ba54 [file] [log] [blame]
Charlie Shepherd54524c92008-01-25 12:36:24 +00001/* lib.c - reusable stuff.
landley4f344e32006-10-05 16:18:03 -04002 *
landleycd9dfc32006-10-18 18:38:16 -04003 * Functions with the x prefix are wrappers for library functions. They either
4 * succeed or kill the program with an error message, but never return failure.
5 * They usually have the same arguments and return value as the function they
6 * wrap.
landley09ea7ac2006-10-30 01:38:00 -05007 *
8 * Copyright 2006 Rob Landley <rob@landley.net>
landley4f344e32006-10-05 16:18:03 -04009 */
10
11#include "toys.h"
12
Rob Landleye15850a2007-11-19 01:51:00 -060013// Strcpy with size checking: exit if there's not enough space for the string.
14void xstrcpy(char *dest, char *src, size_t size)
Rob Landley18d43ff2007-06-07 15:19:44 -040015{
Rob Landley7aa651a2012-11-13 17:14:08 -060016 if (strlen(src)+1 > size) error_exit("xstrcpy");
17 strcpy(dest, src);
Rob Landley18d43ff2007-06-07 15:19:44 -040018}
Rob Landley18d43ff2007-06-07 15:19:44 -040019
landley09ea7ac2006-10-30 01:38:00 -050020void verror_msg(char *msg, int err, va_list va)
21{
Rob Landley7aa651a2012-11-13 17:14:08 -060022 char *s = ": %s";
Rob Landley12138e42008-01-27 15:26:08 -060023
Rob Landley7aa651a2012-11-13 17:14:08 -060024 fprintf(stderr, "%s: ", toys.which->name);
25 if (msg) vfprintf(stderr, msg, va);
26 else s+=2;
27 if (err) fprintf(stderr, s, strerror(err));
28 putc('\n', stderr);
Rob Landley662a2672013-01-02 02:00:35 -060029 if (!toys.exitval) toys.exitval++;
landley09ea7ac2006-10-30 01:38:00 -050030}
31
32void error_msg(char *msg, ...)
33{
Rob Landley7aa651a2012-11-13 17:14:08 -060034 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050035
Rob Landley7aa651a2012-11-13 17:14:08 -060036 va_start(va, msg);
37 verror_msg(msg, 0, va);
38 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050039}
40
41void perror_msg(char *msg, ...)
42{
Rob Landley7aa651a2012-11-13 17:14:08 -060043 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050044
Rob Landley7aa651a2012-11-13 17:14:08 -060045 va_start(va, msg);
46 verror_msg(msg, errno, va);
47 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050048}
49
landley4f344e32006-10-05 16:18:03 -040050// Die with an error message.
51void error_exit(char *msg, ...)
52{
Rob Landley7aa651a2012-11-13 17:14:08 -060053 va_list va;
landley4f344e32006-10-05 16:18:03 -040054
Rob Landley7aa651a2012-11-13 17:14:08 -060055 if (CFG_HELP && toys.exithelp) {
56 *toys.optargs=*toys.argv;
57 USE_HELP(help_main();) // dear gcc: shut up.
58 fprintf(stderr,"\n");
59 }
Rob Landleyd06c58d2007-10-11 15:36:36 -050060
Rob Landley7aa651a2012-11-13 17:14:08 -060061 va_start(va, msg);
62 verror_msg(msg, 0, va);
63 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050064
Rob Landleycaf39c22012-11-16 00:35:46 -060065 if (toys.rebound) longjmp(*toys.rebound, 1);
66 else exit(toys.exitval);
landley09ea7ac2006-10-30 01:38:00 -050067}
68
Rob Landley055cfcb2007-01-14 20:20:06 -050069
landley09ea7ac2006-10-30 01:38:00 -050070// Die with an error message and strerror(errno)
71void perror_exit(char *msg, ...)
72{
Rob Landley7aa651a2012-11-13 17:14:08 -060073 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050074
Rob Landley7aa651a2012-11-13 17:14:08 -060075 va_start(va, msg);
76 verror_msg(msg, errno, va);
77 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050078
Rob Landleycaf39c22012-11-16 00:35:46 -060079 if (toys.rebound) longjmp(*toys.rebound, 1);
80 else exit(toys.exitval);
landley4f344e32006-10-05 16:18:03 -040081}
82
landley4f344e32006-10-05 16:18:03 -040083// Die unless we can allocate memory.
84void *xmalloc(size_t size)
85{
Rob Landley7aa651a2012-11-13 17:14:08 -060086 void *ret = malloc(size);
87 if (!ret) error_exit("xmalloc");
landleycd9dfc32006-10-18 18:38:16 -040088
Rob Landley7aa651a2012-11-13 17:14:08 -060089 return ret;
landley4f344e32006-10-05 16:18:03 -040090}
91
landleycd9dfc32006-10-18 18:38:16 -040092// Die unless we can allocate prezeroed memory.
93void *xzalloc(size_t size)
94{
Rob Landley7aa651a2012-11-13 17:14:08 -060095 void *ret = xmalloc(size);
96 memset(ret, 0, size);
97 return ret;
landleycd9dfc32006-10-18 18:38:16 -040098}
99
100// Die unless we can change the size of an existing allocation, possibly
101// moving it. (Notice different arguments from libc function.)
Rob Landley0c93f6c2007-04-29 19:55:21 -0400102void *xrealloc(void *ptr, size_t size)
landleycd9dfc32006-10-18 18:38:16 -0400103{
Rob Landley7aa651a2012-11-13 17:14:08 -0600104 ptr = realloc(ptr, size);
105 if (!ptr) error_exit("xrealloc");
Rob Landley0c93f6c2007-04-29 19:55:21 -0400106
Rob Landley7aa651a2012-11-13 17:14:08 -0600107 return ptr;
landleycd9dfc32006-10-18 18:38:16 -0400108}
109
Rob Landleyfa98d012006-11-02 02:57:27 -0500110// Die unless we can allocate a copy of this many bytes of string.
Rob Landley1e01cd12010-01-05 10:48:32 -0600111char *xstrndup(char *s, size_t n)
landley4f344e32006-10-05 16:18:03 -0400112{
Rob Landley7aa651a2012-11-13 17:14:08 -0600113 char *ret = xmalloc(++n);
114 strncpy(ret, s, n);
115 ret[--n]=0;
Rob Landley2c226852007-11-15 18:30:30 -0600116
Rob Landley7aa651a2012-11-13 17:14:08 -0600117 return ret;
landley4f344e32006-10-05 16:18:03 -0400118}
119
Rob Landleyfa98d012006-11-02 02:57:27 -0500120// Die unless we can allocate a copy of this string.
Rob Landley1e01cd12010-01-05 10:48:32 -0600121char *xstrdup(char *s)
Rob Landleyfa98d012006-11-02 02:57:27 -0500122{
Rob Landley7aa651a2012-11-13 17:14:08 -0600123 return xstrndup(s, strlen(s));
Rob Landleyfa98d012006-11-02 02:57:27 -0500124}
125
landley00f87f12006-10-25 18:38:37 -0400126// Die unless we can allocate enough space to sprintf() into.
127char *xmsprintf(char *format, ...)
128{
Rob Landley7aa651a2012-11-13 17:14:08 -0600129 va_list va, va2;
130 int len;
131 char *ret;
Rob Landley2c226852007-11-15 18:30:30 -0600132
Rob Landley7aa651a2012-11-13 17:14:08 -0600133 va_start(va, format);
134 va_copy(va2, va);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400135
Rob Landley7aa651a2012-11-13 17:14:08 -0600136 // How long is it?
137 len = vsnprintf(0, 0, format, va);
138 len++;
139 va_end(va);
landley00f87f12006-10-25 18:38:37 -0400140
Rob Landley7aa651a2012-11-13 17:14:08 -0600141 // Allocate and do the sprintf()
142 ret = xmalloc(len);
143 vsnprintf(ret, len, format, va2);
144 va_end(va2);
landley00f87f12006-10-25 18:38:37 -0400145
Rob Landley7aa651a2012-11-13 17:14:08 -0600146 return ret;
landley00f87f12006-10-25 18:38:37 -0400147}
148
Rob Landley24d1d452007-01-20 18:04:20 -0500149void xprintf(char *format, ...)
150{
Rob Landley7aa651a2012-11-13 17:14:08 -0600151 va_list va;
152 va_start(va, format);
Rob Landley24d1d452007-01-20 18:04:20 -0500153
Rob Landley7aa651a2012-11-13 17:14:08 -0600154 vprintf(format, va);
155 if (ferror(stdout)) perror_exit("write");
Rob Landley24d1d452007-01-20 18:04:20 -0500156}
157
Rob Landley5084fea2007-06-18 00:14:03 -0400158void xputs(char *s)
159{
Elie De Brauwerca4035b2012-12-16 13:43:36 +0100160 if (EOF == puts(s) || fflush(stdout)) perror_exit("write");
Rob Landley5084fea2007-06-18 00:14:03 -0400161}
162
Rob Landley24d1d452007-01-20 18:04:20 -0500163void xputc(char c)
164{
Rob Landley7aa651a2012-11-13 17:14:08 -0600165 if (EOF == fputc(c, stdout) || fflush(stdout)) perror_exit("write");
Rob Landley24d1d452007-01-20 18:04:20 -0500166}
167
168void xflush(void)
169{
Rob Landley7aa651a2012-11-13 17:14:08 -0600170 if (fflush(stdout)) perror_exit("write");;
Rob Landley24d1d452007-01-20 18:04:20 -0500171}
172
landleycd9dfc32006-10-18 18:38:16 -0400173// Die unless we can exec argv[] (or run builtin command). Note that anything
174// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500175void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400176{
Rob Landley7aa651a2012-11-13 17:14:08 -0600177 toy_exec(argv);
178 execvp(argv[0], argv);
Rob Landley26e7b5e2012-02-02 07:27:35 -0600179
Rob Landley7aa651a2012-11-13 17:14:08 -0600180 perror_exit("exec %s", argv[0]);
landley4f344e32006-10-05 16:18:03 -0400181}
182
Rob Landleyd3e9d642007-01-08 03:25:47 -0500183void xaccess(char *path, int flags)
184{
Rob Landley7aa651a2012-11-13 17:14:08 -0600185 if (access(path, flags)) perror_exit("Can't access '%s'", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500186}
187
Rob Landleye745d8e2007-12-20 06:30:19 -0600188// Die unless we can delete a file. (File must exist to be deleted.)
189void xunlink(char *path)
190{
Rob Landley7aa651a2012-11-13 17:14:08 -0600191 if (unlink(path)) perror_exit("unlink '%s'", path);
Rob Landleye745d8e2007-12-20 06:30:19 -0600192}
193
landley4f344e32006-10-05 16:18:03 -0400194// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500195int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400196{
Rob Landley7aa651a2012-11-13 17:14:08 -0600197 int fd = open(path, flags, mode);
198 if (fd == -1) perror_exit("%s", path);
199 return fd;
landley4f344e32006-10-05 16:18:03 -0400200}
201
Rob Landley1322beb2007-01-07 22:51:12 -0500202// Die unless we can open a file, returning file descriptor.
203int xopen(char *path, int flags)
204{
Rob Landley7aa651a2012-11-13 17:14:08 -0600205 return xcreate(path, flags, 0);
Rob Landley1322beb2007-01-07 22:51:12 -0500206}
207
Rob Landleybc078652007-12-15 21:47:25 -0600208void xclose(int fd)
209{
Rob Landley7aa651a2012-11-13 17:14:08 -0600210 if (close(fd)) perror_exit("xclose");
Rob Landleybc078652007-12-15 21:47:25 -0600211}
212
Rob Landleyeb7ea222012-04-14 22:30:41 -0500213int xdup(int fd)
214{
Rob Landley7aa651a2012-11-13 17:14:08 -0600215 if (fd != -1) {
216 fd = dup(fd);
217 if (fd == -1) perror_exit("xdup");
218 }
219 return fd;
Rob Landleyeb7ea222012-04-14 22:30:41 -0500220}
221
landley4f344e32006-10-05 16:18:03 -0400222// Die unless we can open/create a file, returning FILE *.
223FILE *xfopen(char *path, char *mode)
224{
Rob Landley7aa651a2012-11-13 17:14:08 -0600225 FILE *f = fopen(path, mode);
226 if (!f) perror_exit("No file %s", path);
227 return f;
landley4f344e32006-10-05 16:18:03 -0400228}
landley00f87f12006-10-25 18:38:37 -0400229
landley64b2e232006-10-30 10:01:19 -0500230// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500231ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500232{
Rob Landley7aa651a2012-11-13 17:14:08 -0600233 size_t count = 0;
Rob Landley15b23152008-07-18 04:15:59 -0500234
Rob Landley7aa651a2012-11-13 17:14:08 -0600235 while (count<len) {
236 int i = read(fd, buf+count, len-count);
237 if (!i) break;
238 if (i<0) return i;
239 count += i;
240 }
landley64b2e232006-10-30 10:01:19 -0500241
Rob Landley7aa651a2012-11-13 17:14:08 -0600242 return count;
landley64b2e232006-10-30 10:01:19 -0500243}
244
Rob Landleyf3e452a2007-01-08 02:49:39 -0500245// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500246ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500247{
Rob Landley7aa651a2012-11-13 17:14:08 -0600248 size_t count = 0;
249 while (count<len) {
250 int i = write(fd, buf+count, len-count);
251 if (i<1) return i;
252 count += i;
253 }
Rob Landleyf3e452a2007-01-08 02:49:39 -0500254
Rob Landley7aa651a2012-11-13 17:14:08 -0600255 return count;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500256}
257
Rob Landley055cfcb2007-01-14 20:20:06 -0500258// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500259size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500260{
Rob Landley7aa651a2012-11-13 17:14:08 -0600261 ssize_t ret = read(fd, buf, len);
262 if (ret < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500263
Rob Landley7aa651a2012-11-13 17:14:08 -0600264 return ret;
Rob Landley055cfcb2007-01-14 20:20:06 -0500265}
266
Rob Landley90163772007-01-18 21:54:08 -0500267void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500268{
Rob Landley7aa651a2012-11-13 17:14:08 -0600269 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500270}
landley00f87f12006-10-25 18:38:37 -0400271
Rob Landley90163772007-01-18 21:54:08 -0500272// There's no xwriteall(), just xwrite(). When we read, there may or may not
273// be more data waiting. When we write, there is data and it had better go
274// somewhere.
275
276void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500277{
Rob Landley7aa651a2012-11-13 17:14:08 -0600278 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500279}
280
Rob Landley52476712009-01-18 16:19:25 -0600281// Die if lseek fails, probably due to being called on a pipe.
282
283off_t xlseek(int fd, off_t offset, int whence)
284{
Rob Landley7aa651a2012-11-13 17:14:08 -0600285 offset = lseek(fd, offset, whence);
286 if (offset<0) perror_exit("lseek");
Rob Landley52476712009-01-18 16:19:25 -0600287
Rob Landley7aa651a2012-11-13 17:14:08 -0600288 return offset;
Rob Landley52476712009-01-18 16:19:25 -0600289}
290
Rob Landley2037b832012-07-15 16:56:20 -0500291off_t lskip(int fd, off_t offset)
292{
Rob Landley7aa651a2012-11-13 17:14:08 -0600293 off_t and = lseek(fd, offset, SEEK_CUR);
Rob Landley2037b832012-07-15 16:56:20 -0500294
Rob Landley7aa651a2012-11-13 17:14:08 -0600295 if (and != -1 && offset >= lseek(fd, offset, SEEK_END)
296 && offset+and == lseek(fd, offset+and, SEEK_SET)) return 0;
297 else {
298 char buf[4096];
299 while (offset>0) {
300 int try = offset>sizeof(buf) ? sizeof(buf) : offset, or;
Rob Landley2037b832012-07-15 16:56:20 -0500301
Rob Landley7aa651a2012-11-13 17:14:08 -0600302 or = readall(fd, buf, try);
303 if (or < 0) perror_msg("lskip to %lld", (long long)offset);
304 else offset -= try;
305 if (or < try) break;
306 }
Rob Landley2037b832012-07-15 16:56:20 -0500307
Rob Landley7aa651a2012-11-13 17:14:08 -0600308 return offset;
309 }
Rob Landley2037b832012-07-15 16:56:20 -0500310}
311
landley00f87f12006-10-25 18:38:37 -0400312char *xgetcwd(void)
313{
Rob Landley7aa651a2012-11-13 17:14:08 -0600314 char *buf = getcwd(NULL, 0);
315 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500316
Rob Landley7aa651a2012-11-13 17:14:08 -0600317 return buf;
landley00f87f12006-10-25 18:38:37 -0400318}
319
Rob Landleyd25f7e42007-02-03 14:11:26 -0500320void xstat(char *path, struct stat *st)
321{
Rob Landley7aa651a2012-11-13 17:14:08 -0600322 if(stat(path, st)) perror_exit("Can't stat %s", path);
Rob Landleyd25f7e42007-02-03 14:11:26 -0500323}
324
Rob Landleyfe91e682012-11-22 21:18:09 -0600325// Split a path into linked list of components, tracking head and tail of list.
326// Filters out // entries with no contents.
327struct string_list **splitpath(char *path, struct string_list **list)
landley00f87f12006-10-25 18:38:37 -0400328{
Rob Landleyfe91e682012-11-22 21:18:09 -0600329 char *new = path;
landley00f87f12006-10-25 18:38:37 -0400330
Rob Landleyfe91e682012-11-22 21:18:09 -0600331 *list = 0;
332 do {
333 int len;
landley00f87f12006-10-25 18:38:37 -0400334
Rob Landleyfe91e682012-11-22 21:18:09 -0600335 if (*path && *path != '/') continue;
336 len = path-new;
337 if (len > 0) {
338 *list = xmalloc(sizeof(struct string_list) + len + 1);
339 (*list)->next = 0;
340 strncpy((*list)->str, new, len);
341 (*list)->str[len] = 0;
342 list = &(*list)->next;
343 }
344 new = path+1;
345 } while (*path++);
346
347 return list;
348}
349
350// Cannonicalize path, even to file with one or more missing components at end.
351// if exact, require last path component to exist
352char *xabspath(char *path, int exact)
353{
354 struct string_list *todo, *done = 0;
355 int try = 9999, dirfd = open("/", 0);;
356 char buf[4096], *ret;
357
358 // If this isn't an absolute path, start with cwd.
359 if (*path != '/') {
360 char *temp = xgetcwd();
361
362 splitpath(path, splitpath(temp, &todo));
Rob Landleybd2e2272012-11-20 09:21:52 -0600363 free(temp);
Rob Landleyfe91e682012-11-22 21:18:09 -0600364 } else splitpath(path, &todo);
365
366 // Iterate through path components
367 while (todo) {
368 struct string_list *new = llist_pop(&todo), **tail;
369 ssize_t len;
370
371 if (!try--) {
372 errno = ELOOP;
373 goto error;
374 }
375
376 // Removable path componenents.
377 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
Rob Landley7c0e2802013-01-17 23:16:38 -0600378 int x = new->str[1];
379
Rob Landleyfe91e682012-11-22 21:18:09 -0600380 free(new);
Rob Landley7c0e2802013-01-17 23:16:38 -0600381 if (x) {
382 if (done) free(llist_pop(&done));
383 len = 0;
384 } else continue;
Rob Landleyfe91e682012-11-22 21:18:09 -0600385
386 // Is this a symlink?
Rob Landley7c0e2802013-01-17 23:16:38 -0600387 } else len=readlinkat(dirfd, new->str, buf, 4096);
388
Rob Landleyfe91e682012-11-22 21:18:09 -0600389 if (len>4095) goto error;
390 if (len<1) {
391 int fd;
Rob Landley7c0e2802013-01-17 23:16:38 -0600392 char *s = "..";
Rob Landleyfe91e682012-11-22 21:18:09 -0600393
Rob Landley7c0e2802013-01-17 23:16:38 -0600394 // For .. just move dirfd
395 if (len) {
396 // Not a symlink: add to linked list, move dirfd, fail if error
397 if ((exact || todo) && errno != EINVAL) goto error;
398 new->next = done;
399 done = new;
400 s = new->str;
401 }
402 fd = openat(dirfd, s, 0);
403 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
Rob Landleyfe91e682012-11-22 21:18:09 -0600404 close(dirfd);
405 dirfd = fd;
406 continue;
407 }
408
409 // If this symlink is to an absolute path, discard existing resolved path
410 buf[len] = 0;
411 if (*buf == '/') {
412 llist_traverse(done, free);
413 done=0;
414 close(dirfd);
415 dirfd = open("/", 0);
416 }
417 free(new);
418
419 // prepend components of new path. Note symlink to "/" will leave new NULL
420 tail = splitpath(buf, &new);
421
422 // symlink to "/" will return null and leave tail alone
423 if (new) {
424 *tail = todo;
425 todo = new;
426 }
427 }
428 close(dirfd);
429
430 // At this point done has the path, in reverse order. Reverse list while
431 // calculating buffer length.
432
433 try = 2;
434 while (done) {
435 struct string_list *temp = llist_pop(&done);;
436
437 if (todo) try++;
438 try += strlen(temp->str);
439 temp->next = todo;
440 todo = temp;
Rob Landley7aa651a2012-11-13 17:14:08 -0600441 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500442
Rob Landleyfe91e682012-11-22 21:18:09 -0600443 // Assemble return buffer
444
445 ret = xmalloc(try);
446 *ret = '/';
447 ret [try = 1] = 0;
448 while (todo) {
449 if (try>1) ret[try++] = '/';
450 try = stpcpy(ret+try, todo->str) - ret;
451 free(llist_pop(&todo));
Rob Landleybd2e2272012-11-20 09:21:52 -0600452 }
453
Rob Landleyfe91e682012-11-22 21:18:09 -0600454 return ret;
455
456error:
457 close(dirfd);
458 llist_traverse(todo, free);
459 llist_traverse(done, free);
460
461 return NULL;
Rob Landleyfa98d012006-11-02 02:57:27 -0500462}
463
Rob Landleyeec46372012-06-01 13:50:41 -0500464// Resolve all symlinks, returning malloc() memory.
465char *xrealpath(char *path)
466{
Rob Landley7aa651a2012-11-13 17:14:08 -0600467 char *new = realpath(path, NULL);
468 if (!new) perror_exit("realpath '%s'", path);
469 return new;
Rob Landleyeec46372012-06-01 13:50:41 -0500470}
471
Rob Landley988abb32008-05-12 00:52:27 -0500472void xchdir(char *path)
473{
Rob Landley7aa651a2012-11-13 17:14:08 -0600474 if (chdir(path)) error_exit("chdir '%s'", path);
Rob Landley988abb32008-05-12 00:52:27 -0500475}
476
Rob Landley35483412007-12-27 21:36:33 -0600477// Ensure entire path exists.
478// If mode != -1 set permissions on newly created dirs.
479// Requires that path string be writable (for temporary null terminators).
480void xmkpath(char *path, int mode)
481{
Rob Landley7aa651a2012-11-13 17:14:08 -0600482 char *p, old;
483 mode_t mask;
484 int rc;
485 struct stat st;
Rob Landley35483412007-12-27 21:36:33 -0600486
Rob Landley7aa651a2012-11-13 17:14:08 -0600487 for (p = path; ; p++) {
488 if (!*p || *p == '/') {
489 old = *p;
490 *p = rc = 0;
491 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
492 if (mode != -1) {
493 mask=umask(0);
494 rc = mkdir(path, mode);
495 umask(mask);
496 } else rc = mkdir(path, 0777);
497 }
498 *p = old;
499 if(rc) perror_exit("mkpath '%s'", path);
500 }
501 if (!*p) break;
502 }
Rob Landley35483412007-12-27 21:36:33 -0600503}
Rob Landleye0377fb2010-01-05 12:17:05 -0600504
505// setuid() can fail (for example, too many processes belonging to that user),
506// which opens a security hole if the process continues as the original user.
507
508void xsetuid(uid_t uid)
509{
Rob Landley7aa651a2012-11-13 17:14:08 -0600510 if (setuid(uid)) perror_exit("xsetuid");
Rob Landleye0377fb2010-01-05 12:17:05 -0600511}
512
513
Rob Landley0a04b3e2006-11-03 00:05:52 -0500514// Find all file in a colon-separated path with access type "type" (generally
515// X_OK or R_OK). Returns a list of absolute paths to each file found, in
516// order.
517
518struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500519{
Rob Landley7aa651a2012-11-13 17:14:08 -0600520 struct string_list *rlist = NULL, **prlist=&rlist;
521 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500522
Rob Landley7aa651a2012-11-13 17:14:08 -0600523 for (;;) {
524 char *next = path ? strchr(path, ':') : NULL;
525 int len = next ? next-path : strlen(path);
526 struct string_list *rnext;
527 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500528
Rob Landley7aa651a2012-11-13 17:14:08 -0600529 rnext = xmalloc(sizeof(void *) + strlen(filename)
530 + (len ? len : strlen(cwd)) + 2);
531 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
532 else {
533 char *res = rnext->str;
534 strncpy(res, path, len);
535 res += len;
536 *(res++) = '/';
537 strcpy(res, filename);
538 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500539
Rob Landley7aa651a2012-11-13 17:14:08 -0600540 // Confirm it's not a directory.
541 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
542 *prlist = rnext;
543 rnext->next = NULL;
544 prlist = &(rnext->next);
545 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500546
Rob Landley7aa651a2012-11-13 17:14:08 -0600547 if (!next) break;
548 path += len;
549 path++;
550 }
551 free(cwd);
landley00f87f12006-10-25 18:38:37 -0400552
Rob Landley7aa651a2012-11-13 17:14:08 -0600553 return rlist;
landley00f87f12006-10-25 18:38:37 -0400554}
landley09ea7ac2006-10-30 01:38:00 -0500555
556// Convert unsigned int to ascii, writing into supplied buffer. A truncated
557// result contains the first few digits of the result ala strncpy, and is
558// always null terminated (unless buflen is 0).
559void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
560{
Rob Landley7aa651a2012-11-13 17:14:08 -0600561 int i, out = 0;
landley09ea7ac2006-10-30 01:38:00 -0500562
Rob Landley7aa651a2012-11-13 17:14:08 -0600563 if (buflen) {
564 for (i=1000000000; i; i/=10) {
565 int res = n/i;
landley09ea7ac2006-10-30 01:38:00 -0500566
Rob Landley7aa651a2012-11-13 17:14:08 -0600567 if ((res || out || i == 1) && --buflen>0) {
568 out++;
569 n -= res*i;
570 *buf++ = '0' + res;
571 }
572 }
573 *buf = 0;
574 }
landley09ea7ac2006-10-30 01:38:00 -0500575}
576
577// Convert signed integer to ascii, using utoa_to_buf()
578void itoa_to_buf(int n, char *buf, unsigned buflen)
579{
Rob Landley7aa651a2012-11-13 17:14:08 -0600580 if (buflen && n<0) {
581 n = -n;
582 *buf++ = '-';
583 buflen--;
584 }
585 utoa_to_buf((unsigned)n, buf, buflen);
landley09ea7ac2006-10-30 01:38:00 -0500586}
587
588// This static buffer is used by both utoa() and itoa(), calling either one a
589// second time will overwrite the previous results.
590//
591// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
592// Note that int is always 32 bits on any remotely unix-like system, see
593// http://www.unix.org/whitepapers/64bit.html for details.
594
595static char itoa_buf[12];
596
597// Convert unsigned integer to ascii, returning a static buffer.
598char *utoa(unsigned n)
599{
Rob Landley7aa651a2012-11-13 17:14:08 -0600600 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
landley09ea7ac2006-10-30 01:38:00 -0500601
Rob Landley7aa651a2012-11-13 17:14:08 -0600602 return itoa_buf;
landley09ea7ac2006-10-30 01:38:00 -0500603}
604
605char *itoa(int n)
606{
Rob Landley7aa651a2012-11-13 17:14:08 -0600607 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
landley09ea7ac2006-10-30 01:38:00 -0500608
Rob Landley7aa651a2012-11-13 17:14:08 -0600609 return itoa_buf;
landley09ea7ac2006-10-30 01:38:00 -0500610}
Rob Landley055cfcb2007-01-14 20:20:06 -0500611
Rob Landleyf5757162007-02-16 21:08:22 -0500612// atol() with the kilo/mega/giga/tera/peta/exa extensions.
613// (zetta and yotta don't fit in 64 bits.)
Rob Landley5e6dca62012-02-09 06:09:27 -0600614long atolx(char *numstr)
Rob Landleyf5757162007-02-16 21:08:22 -0500615{
Rob Landley7aa651a2012-11-13 17:14:08 -0600616 char *c, *suffixes="bkmgtpe", *end;
617 long val = strtol(numstr, &c, 0);
Rob Landleyf5757162007-02-16 21:08:22 -0500618
Rob Landley7aa651a2012-11-13 17:14:08 -0600619 if (*c) {
620 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
621 int shift = end-suffixes;
622 if (shift--) val *= 1024L<<(shift*10);
623 } else {
624 while (isspace(*c)) c++;
625 if (*c) error_exit("not integer: %s", numstr);
626 }
627 }
Rob Landleyad63f4b2011-12-12 15:19:52 -0600628
Rob Landley7aa651a2012-11-13 17:14:08 -0600629 return val;
Rob Landleyf5757162007-02-16 21:08:22 -0500630}
631
Rob Landleyeb7ea222012-04-14 22:30:41 -0500632int numlen(long l)
633{
Rob Landley7aa651a2012-11-13 17:14:08 -0600634 int len = 0;
635 while (l) {
636 l /= 10;
637 len++;
638 }
639 return len;
Rob Landleyeb7ea222012-04-14 22:30:41 -0500640}
641
Rob Landley2037b832012-07-15 16:56:20 -0500642int stridx(char *haystack, char needle)
643{
Rob Landley7aa651a2012-11-13 17:14:08 -0600644 char *off;
Rob Landley2037b832012-07-15 16:56:20 -0500645
Rob Landley7aa651a2012-11-13 17:14:08 -0600646 if (!needle) return -1;
647 off = strchr(haystack, needle);
648 if (!off) return -1;
Rob Landley2037b832012-07-15 16:56:20 -0500649
Rob Landley7aa651a2012-11-13 17:14:08 -0600650 return off-haystack;
Rob Landley2037b832012-07-15 16:56:20 -0500651}
652
Rob Landley055cfcb2007-01-14 20:20:06 -0500653// Return how long the file at fd is, if there's any way to determine it.
654off_t fdlength(int fd)
655{
Rob Landley7aa651a2012-11-13 17:14:08 -0600656 off_t bottom = 0, top = 0, pos, old;
657 int size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500658
Rob Landley7aa651a2012-11-13 17:14:08 -0600659 // If the ioctl works for this, return it.
Rob Landley055cfcb2007-01-14 20:20:06 -0500660
Rob Landley7aa651a2012-11-13 17:14:08 -0600661 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500662
Rob Landley7aa651a2012-11-13 17:14:08 -0600663 // If not, do a binary search for the last location we can read. (Some
664 // block devices don't do BLKGETSIZE right.) This should probably have
665 // a CONFIG option...
Rob Landley055cfcb2007-01-14 20:20:06 -0500666
Rob Landley7aa651a2012-11-13 17:14:08 -0600667 old = lseek(fd, 0, SEEK_CUR);
668 do {
669 char temp;
Rob Landley055cfcb2007-01-14 20:20:06 -0500670
Rob Landley7aa651a2012-11-13 17:14:08 -0600671 pos = bottom + (top - bottom) / 2;
Rob Landley055cfcb2007-01-14 20:20:06 -0500672
Rob Landley7aa651a2012-11-13 17:14:08 -0600673 // If we can read from the current location, it's bigger.
Rob Landley055cfcb2007-01-14 20:20:06 -0500674
Rob Landley7aa651a2012-11-13 17:14:08 -0600675 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
676 if (bottom == top) bottom = top = (top+1) * 2;
677 else bottom = pos;
Rob Landley055cfcb2007-01-14 20:20:06 -0500678
Rob Landley7aa651a2012-11-13 17:14:08 -0600679 // If we can't, it's smaller.
Rob Landley055cfcb2007-01-14 20:20:06 -0500680
Rob Landley7aa651a2012-11-13 17:14:08 -0600681 } else {
682 if (bottom == top) {
683 if (!top) return 0;
684 bottom = top/2;
685 } else top = pos;
686 }
687 } while (bottom + 1 != top);
Rob Landley055cfcb2007-01-14 20:20:06 -0500688
Rob Landley7aa651a2012-11-13 17:14:08 -0600689 lseek(fd, old, SEEK_SET);
Rob Landleyf15387d2008-07-18 05:43:44 -0500690
Rob Landley7aa651a2012-11-13 17:14:08 -0600691 return pos + 1;
Rob Landley055cfcb2007-01-14 20:20:06 -0500692}
693
Rob Landley0c93f6c2007-04-29 19:55:21 -0400694// This can return null (meaning file not found). It just won't return null
695// for memory allocation reasons.
696char *xreadlink(char *name)
697{
Rob Landley7aa651a2012-11-13 17:14:08 -0600698 int len, size = 0;
699 char *buf = 0;
Rob Landley0c93f6c2007-04-29 19:55:21 -0400700
Rob Landley7aa651a2012-11-13 17:14:08 -0600701 // Grow by 64 byte chunks until it's big enough.
702 for(;;) {
703 size +=64;
704 buf = xrealloc(buf, size);
705 len = readlink(name, buf, size);
Rob Landley0c93f6c2007-04-29 19:55:21 -0400706
Rob Landley7aa651a2012-11-13 17:14:08 -0600707 if (len<0) {
708 free(buf);
709 return 0;
710 }
711 if (len<size) {
712 buf[len]=0;
713 return buf;
714 }
715 }
Rob Landley0c93f6c2007-04-29 19:55:21 -0400716}
717
Rob Landleyb3a33822007-01-25 16:10:37 -0500718/*
719 This might be of use or might not. Unknown yet...
720
Rob Landley055cfcb2007-01-14 20:20:06 -0500721// Read contents of file as a single freshly allocated nul-terminated string.
722char *readfile(char *name)
723{
Rob Landley7aa651a2012-11-13 17:14:08 -0600724 off_t len;
725 int fd;
726 char *buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500727
Rob Landley7aa651a2012-11-13 17:14:08 -0600728 fd = open(name, O_RDONLY);
729 if (fd == -1) return 0;
730 len = fdlength(fd);
731 buf = xmalloc(len+1);
732 buf[readall(fd, buf, len)] = 0;
Rob Landley055cfcb2007-01-14 20:20:06 -0500733
Rob Landley7aa651a2012-11-13 17:14:08 -0600734 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500735}
736
737char *xreadfile(char *name)
738{
Rob Landley7aa651a2012-11-13 17:14:08 -0600739 char *buf = readfile(name);
740 if (!buf) perror_exit("xreadfile %s", name);
741 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500742}
743
744*/
745
746// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
747// exists and is this executable.
748void xpidfile(char *name)
749{
Rob Landley7aa651a2012-11-13 17:14:08 -0600750 char pidfile[256], spid[32];
751 int i, fd;
752 pid_t pid;
Rob Landley055cfcb2007-01-14 20:20:06 -0500753
Rob Landley7aa651a2012-11-13 17:14:08 -0600754 sprintf(pidfile, "/var/run/%s.pid", name);
755 // Try three times to open the sucker.
756 for (i=0; i<3; i++) {
757 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
758 if (fd != -1) break;
Rob Landley055cfcb2007-01-14 20:20:06 -0500759
Rob Landley7aa651a2012-11-13 17:14:08 -0600760 // If it already existed, read it. Loop for race condition.
761 fd = open(pidfile, O_RDONLY);
762 if (fd == -1) continue;
Rob Landley055cfcb2007-01-14 20:20:06 -0500763
Rob Landley7aa651a2012-11-13 17:14:08 -0600764 // Is the old program still there?
765 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
766 close(fd);
767 pid = atoi(spid);
768 if (pid < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
Rob Landley2c226852007-11-15 18:30:30 -0600769
Rob Landley7aa651a2012-11-13 17:14:08 -0600770 // An else with more sanity checking might be nice here.
771 }
Rob Landley055cfcb2007-01-14 20:20:06 -0500772
Rob Landley7aa651a2012-11-13 17:14:08 -0600773 if (i == 3) error_exit("xpidfile %s", name);
774
775 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
776 close(fd);
Rob Landley055cfcb2007-01-14 20:20:06 -0500777}
Rob Landley7634b552007-11-29 17:49:50 -0600778
Rob Landley2bfaaf22008-07-03 19:19:00 -0500779// Iterate through an array of files, opening each one and calling a function
780// on that filehandle and name. The special filename "-" means stdin if
781// flags is O_RDONLY, stdout otherwise. An empty argument list calls
782// function() on just stdin/stdout.
783//
784// Note: read only filehandles are automatically closed when function()
785// returns, but writeable filehandles must be close by function()
Rob Landleyad63f4b2011-12-12 15:19:52 -0600786void loopfiles_rw(char **argv, int flags, int permissions, int failok,
Rob Landley7aa651a2012-11-13 17:14:08 -0600787 void (*function)(int fd, char *name))
Rob Landley7634b552007-11-29 17:49:50 -0600788{
Rob Landley7aa651a2012-11-13 17:14:08 -0600789 int fd;
Rob Landley7634b552007-11-29 17:49:50 -0600790
Rob Landley7aa651a2012-11-13 17:14:08 -0600791 // If no arguments, read from stdin.
792 if (!*argv) function(flags ? 1 : 0, "-");
793 else do {
794 // Filename "-" means read from stdin.
795 // Inability to open a file prints a warning, but doesn't exit.
Rob Landley7634b552007-11-29 17:49:50 -0600796
Rob Landley7aa651a2012-11-13 17:14:08 -0600797 if (!strcmp(*argv,"-")) fd=0;
798 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
799 perror_msg("%s", *argv);
800 toys.exitval = 1;
801 continue;
802 }
803 function(fd, *argv);
804 if (flags == O_RDONLY) close(fd);
805 } while (*++argv);
Rob Landley7634b552007-11-29 17:49:50 -0600806}
Rob Landleybc078652007-12-15 21:47:25 -0600807
Rob Landleyad63f4b2011-12-12 15:19:52 -0600808// Call loopfiles_rw with O_RDONLY and !failok (common case).
Rob Landley2bfaaf22008-07-03 19:19:00 -0500809void loopfiles(char **argv, void (*function)(int fd, char *name))
810{
Rob Landley7aa651a2012-11-13 17:14:08 -0600811 loopfiles_rw(argv, O_RDONLY, 0, 0, function);
Rob Landley2bfaaf22008-07-03 19:19:00 -0500812}
813
Rob Landleybc078652007-12-15 21:47:25 -0600814// Slow, but small.
815
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500816char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600817{
Rob Landley7aa651a2012-11-13 17:14:08 -0600818 char c, *buf = NULL;
819 long len = 0;
Rob Landleybc078652007-12-15 21:47:25 -0600820
Rob Landley7aa651a2012-11-13 17:14:08 -0600821 for (;;) {
822 if (1>read(fd, &c, 1)) break;
823 if (!(len & 63)) buf=xrealloc(buf, len+65);
824 if ((buf[len++]=c) == end) break;
825 }
826 if (buf) buf[len]=0;
827 if (plen) *plen = len;
Rob Landleybc078652007-12-15 21:47:25 -0600828
Rob Landley7aa651a2012-11-13 17:14:08 -0600829 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600830}
831
832char *get_line(int fd)
833{
Rob Landley7aa651a2012-11-13 17:14:08 -0600834 long len;
835 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600836
Rob Landley7aa651a2012-11-13 17:14:08 -0600837 if (buf && buf[--len]=='\n') buf[len]=0;
Rob Landleybc078652007-12-15 21:47:25 -0600838
Rob Landley7aa651a2012-11-13 17:14:08 -0600839 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600840}
841
842// Copy the rest of in to out and close both files.
843
844void xsendfile(int in, int out)
845{
Rob Landley7aa651a2012-11-13 17:14:08 -0600846 long len;
847 char buf[4096];
Rob Landleybc078652007-12-15 21:47:25 -0600848
Rob Landley7aa651a2012-11-13 17:14:08 -0600849 if (in<0) return;
850 for (;;) {
851 len = xread(in, buf, 4096);
852 if (len<1) break;
853 xwrite(out, buf, len);
854 }
Rob Landley42ecbab2007-12-18 02:02:21 -0600855}
856
Rob Landley67a069d2012-06-03 00:32:12 -0500857int wfchmodat(int fd, char *name, mode_t mode)
858{
Rob Landley7aa651a2012-11-13 17:14:08 -0600859 int rc = fchmodat(fd, name, mode, 0);
Rob Landley67a069d2012-06-03 00:32:12 -0500860
Rob Landley7aa651a2012-11-13 17:14:08 -0600861 if (rc) {
862 perror_msg("chmod '%s' to %04o", name, mode);
863 toys.exitval=1;
864 }
865 return rc;
Rob Landley67a069d2012-06-03 00:32:12 -0500866}
867
Rob Landleyc52db602012-07-30 01:01:33 -0500868static char *tempfile2zap;
869static void tempfile_handler(int i)
870{
Rob Landley7aa651a2012-11-13 17:14:08 -0600871 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
872 _exit(1);
Rob Landleyc52db602012-07-30 01:01:33 -0500873}
874
Rob Landley42ecbab2007-12-18 02:02:21 -0600875// Open a temporary file to copy an existing file into.
876int copy_tempfile(int fdin, char *name, char **tempname)
877{
Rob Landley7aa651a2012-11-13 17:14:08 -0600878 struct stat statbuf;
879 int fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600880
Rob Landley7aa651a2012-11-13 17:14:08 -0600881 *tempname = xstrndup(name, strlen(name)+6);
882 strcat(*tempname,"XXXXXX");
883 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
884 if (!tempfile2zap) sigatexit(tempfile_handler);
885 tempfile2zap = *tempname;
Rob Landley42ecbab2007-12-18 02:02:21 -0600886
Rob Landley7aa651a2012-11-13 17:14:08 -0600887 // Set permissions of output file
Rob Landley42ecbab2007-12-18 02:02:21 -0600888
Rob Landley7aa651a2012-11-13 17:14:08 -0600889 fstat(fdin, &statbuf);
890 fchmod(fd, statbuf.st_mode);
Rob Landley42ecbab2007-12-18 02:02:21 -0600891
Rob Landley7aa651a2012-11-13 17:14:08 -0600892 return fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600893}
894
895// Abort the copy and delete the temporary file.
896void delete_tempfile(int fdin, int fdout, char **tempname)
897{
Rob Landley7aa651a2012-11-13 17:14:08 -0600898 close(fdin);
899 close(fdout);
900 unlink(*tempname);
901 tempfile2zap = (char *)1;
902 free(*tempname);
903 *tempname = NULL;
Rob Landley42ecbab2007-12-18 02:02:21 -0600904}
905
906// Copy the rest of the data and replace the original with the copy.
907void replace_tempfile(int fdin, int fdout, char **tempname)
908{
Rob Landley7aa651a2012-11-13 17:14:08 -0600909 char *temp = xstrdup(*tempname);
Rob Landley42ecbab2007-12-18 02:02:21 -0600910
Rob Landley7aa651a2012-11-13 17:14:08 -0600911 temp[strlen(temp)-6]=0;
912 if (fdin != -1) {
913 xsendfile(fdin, fdout);
914 xclose(fdin);
915 }
916 xclose(fdout);
917 rename(*tempname, temp);
918 tempfile2zap = (char *)1;
919 free(*tempname);
920 free(temp);
921 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600922}
Rob Landley7e849c52009-01-03 18:15:18 -0600923
924// Create a 256 entry CRC32 lookup table.
925
Rob Landleyb15b8fa2009-01-05 01:05:43 -0600926void crc_init(unsigned int *crc_table, int little_endian)
Rob Landley7e849c52009-01-03 18:15:18 -0600927{
Rob Landley7aa651a2012-11-13 17:14:08 -0600928 unsigned int i;
Rob Landley7e849c52009-01-03 18:15:18 -0600929
Rob Landley7aa651a2012-11-13 17:14:08 -0600930 // Init the CRC32 table (big endian)
931 for (i=0; i<256; i++) {
932 unsigned int j, c = little_endian ? i : i<<24;
933 for (j=8; j; j--)
934 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
935 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
936 crc_table[i] = c;
937 }
Rob Landley7e849c52009-01-03 18:15:18 -0600938}
Rob Landley26e7b5e2012-02-02 07:27:35 -0600939
940// Quick and dirty query size of terminal, doesn't do ANSI probe fallback.
941// set *x=0 and *y=0 before calling to detect failure to set either, or
942// x=80 y=25 to provide defaults
943
944void terminal_size(unsigned *x, unsigned *y)
945{
Rob Landley7aa651a2012-11-13 17:14:08 -0600946 struct winsize ws;
947 int i;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600948
Rob Landley7aa651a2012-11-13 17:14:08 -0600949 //memset(&ws, 0, sizeof(ws));
950 for (i=0; i<3; i++) {
951 if (ioctl(i, TIOCGWINSZ, &ws)) continue;
952 if (x) *x = ws.ws_col;
953 if (y) *y = ws.ws_row;
954 }
955 if (x) {
956 char *s = getenv("COLUMNS");
Rob Landley26e7b5e2012-02-02 07:27:35 -0600957
Rob Landley7aa651a2012-11-13 17:14:08 -0600958 i = s ? atoi(s) : 0;
959 if (i>0) *x = i;
960 }
961 if (y) {
962 char *s = getenv("ROWS");
Rob Landley26e7b5e2012-02-02 07:27:35 -0600963
Rob Landley7aa651a2012-11-13 17:14:08 -0600964 i = s ? atoi(s) : 0;
965 if (i>0) *y = i;
966 }
Rob Landley26e7b5e2012-02-02 07:27:35 -0600967}
968
Rob Landleyf793d532012-02-27 21:56:49 -0600969int yesno(char *prompt, int def)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600970{
Rob Landley7aa651a2012-11-13 17:14:08 -0600971 char buf;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600972
Rob Landleydb8eb322012-12-08 02:25:32 -0600973 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
974 fflush(stderr);
975 while (fread(&buf, 1, 1, stdin)) {
976 int new;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600977
Rob Landley22791082013-01-31 04:13:07 -0600978 // The letter changes the value, the newline (or space) returns it.
Rob Landleydb8eb322012-12-08 02:25:32 -0600979 if (isspace(buf)) break;
980 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
Rob Landley7aa651a2012-11-13 17:14:08 -0600981 }
Rob Landleyee00a7f2012-03-19 19:19:21 -0500982
Rob Landley7aa651a2012-11-13 17:14:08 -0600983 return def;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600984}
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600985
986// Execute a callback for each PID that matches a process name from a list.
Elie De Brauwerca4035b2012-12-16 13:43:36 +0100987void for_each_pid_with_name_in(char **names, int (*callback)(pid_t pid, char *name))
Rob Landleyf42e11b2012-02-18 18:09:14 -0600988{
Rob Landley7aa651a2012-11-13 17:14:08 -0600989 DIR *dp;
990 struct dirent *entry;
991 char cmd[sizeof(toybuf)], path[64];
992 char **curname;
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600993
Rob Landley7aa651a2012-11-13 17:14:08 -0600994 if (!(dp = opendir("/proc"))) perror_exit("opendir");
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600995
Rob Landley7aa651a2012-11-13 17:14:08 -0600996 while ((entry = readdir(dp))) {
997 int fd, n;
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600998
Rob Landley7aa651a2012-11-13 17:14:08 -0600999 if (!isdigit(*entry->d_name)) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001000
Rob Landley7aa651a2012-11-13 17:14:08 -06001001 if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline",
1002 entry->d_name)) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001003
Rob Landley7aa651a2012-11-13 17:14:08 -06001004 if (-1 == (fd=open(path, O_RDONLY))) continue;
1005 n = read(fd, cmd, sizeof(cmd));
1006 close(fd);
1007 if (n<1) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001008
Rob Landley7aa651a2012-11-13 17:14:08 -06001009 for (curname = names; *curname; curname++)
Elie De Brauwer7c6209d2012-12-08 20:10:05 +01001010 if (!strcmp(basename(cmd), *curname))
Elie De Brauwerca4035b2012-12-16 13:43:36 +01001011 if (!callback(atol(entry->d_name), *curname)) goto done;
Rob Landley7aa651a2012-11-13 17:14:08 -06001012 }
Elie De Brauwer7c6209d2012-12-08 20:10:05 +01001013done:
Rob Landley7aa651a2012-11-13 17:14:08 -06001014 closedir(dp);
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001015}
Rob Landley2dd50ad2012-02-26 13:48:00 -06001016
1017struct signame {
Rob Landley7aa651a2012-11-13 17:14:08 -06001018 int num;
1019 char *name;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001020};
1021
1022// Signals required by POSIX 2008:
1023// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
1024
1025#define SIGNIFY(x) {SIG##x, #x}
1026
1027static struct signame signames[] = {
Rob Landley7aa651a2012-11-13 17:14:08 -06001028 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
1029 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
1030 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
1031 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
1032 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
Rob Landleyc52db602012-07-30 01:01:33 -05001033
Rob Landley7aa651a2012-11-13 17:14:08 -06001034 // Start of non-terminal signals
Rob Landleyc52db602012-07-30 01:01:33 -05001035
Rob Landley7aa651a2012-11-13 17:14:08 -06001036 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
1037 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
Rob Landley2dd50ad2012-02-26 13:48:00 -06001038};
1039
1040// not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
1041// obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
1042
Rob Landleyc52db602012-07-30 01:01:33 -05001043// Install the same handler on every signal that defaults to killing the process
1044void sigatexit(void *handler)
1045{
Rob Landley7aa651a2012-11-13 17:14:08 -06001046 int i;
1047 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
Rob Landleyc52db602012-07-30 01:01:33 -05001048}
Rob Landley2dd50ad2012-02-26 13:48:00 -06001049// Convert name to signal number. If name == NULL print names.
1050int sig_to_num(char *pidstr)
1051{
Rob Landley7aa651a2012-11-13 17:14:08 -06001052 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001053
Rob Landley7aa651a2012-11-13 17:14:08 -06001054 if (pidstr) {
1055 char *s;
1056 i = strtol(pidstr, &s, 10);
1057 if (!*s) return i;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001058
Rob Landley7aa651a2012-11-13 17:14:08 -06001059 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
1060 }
1061 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
1062 if (!pidstr) xputs(signames[i].name);
1063 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001064
Rob Landley7aa651a2012-11-13 17:14:08 -06001065 return -1;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001066}
1067
1068char *num_to_sig(int sig)
1069{
Rob Landley7aa651a2012-11-13 17:14:08 -06001070 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001071
Rob Landley7aa651a2012-11-13 17:14:08 -06001072 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
1073 if (signames[i].num == sig) return signames[i].name;
1074 return NULL;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001075}
Daniel Walter05744b32012-03-19 19:57:56 -05001076
Rob Landleyc52db602012-07-30 01:01:33 -05001077// premute mode bits based on posix mode strings.
Rob Landleyb6f601e2012-05-16 21:11:43 -05001078mode_t string_to_mode(char *modestr, mode_t mode)
Daniel Walter05744b32012-03-19 19:57:56 -05001079{
Rob Landley7aa651a2012-11-13 17:14:08 -06001080 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu";
1081 char *s, *str = modestr;
Rob Landleycf6bcb22012-03-19 20:56:18 -05001082
Rob Landley7aa651a2012-11-13 17:14:08 -06001083 // Handle octal mode
1084 if (isdigit(*str)) {
1085 mode = strtol(str, &s, 8);
1086 if (*s || (mode & ~(07777))) goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001087
Rob Landley7aa651a2012-11-13 17:14:08 -06001088 return mode;
1089 }
Rob Landleycf6bcb22012-03-19 20:56:18 -05001090
Rob Landley7aa651a2012-11-13 17:14:08 -06001091 // Gaze into the bin of permission...
1092 for (;;) {
1093 int i, j, dowho, dohow, dowhat, amask;
Rob Landleycf6bcb22012-03-19 20:56:18 -05001094
Rob Landley7aa651a2012-11-13 17:14:08 -06001095 dowho = dohow = dowhat = amask = 0;
Daniel Walter05744b32012-03-19 19:57:56 -05001096
Rob Landley7aa651a2012-11-13 17:14:08 -06001097 // Find the who, how, and what stanzas, in that order
1098 while (*str && (s = strchr(whos, *str))) {
1099 dowho |= 1<<(s-whos);
1100 str++;
1101 }
1102 // If who isn't specified, like "a" but honoring umask.
1103 if (!dowho) {
1104 dowho = 8;
1105 umask(amask=umask(0));
1106 }
1107 if (!*str || !(s = strchr(hows, *str))) goto barf;
1108 dohow = *(str++);
Rob Landley67a069d2012-06-03 00:32:12 -05001109
Rob Landley7aa651a2012-11-13 17:14:08 -06001110 if (!dohow) goto barf;
1111 while (*str && (s = strchr(whats, *str))) {
1112 dowhat |= 1<<(s-whats);
1113 str++;
1114 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001115
Rob Landley7aa651a2012-11-13 17:14:08 -06001116 // Convert X to x for directory or if already executable somewhere
1117 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001118
Rob Landley7aa651a2012-11-13 17:14:08 -06001119 // Copy mode from another category?
1120 if (!dowhat && *str && (s = strchr(whys, *str))) {
1121 dowhat = (mode>>(3*(s-whys)))&7;
1122 str++;
1123 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001124
Rob Landley7aa651a2012-11-13 17:14:08 -06001125 // Are we ready to do a thing yet?
1126 if (*str && *(str++) != ',') goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001127
Rob Landley7aa651a2012-11-13 17:14:08 -06001128 // Ok, apply the bits to the mode.
1129 for (i=0; i<4; i++) {
1130 for (j=0; j<3; j++) {
1131 mode_t bit = 0;
1132 int where = 1<<((3*i)+j);
Rob Landley31f49e72012-07-21 22:45:05 -05001133
Rob Landley7aa651a2012-11-13 17:14:08 -06001134 if (amask & where) continue;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001135
Rob Landley7aa651a2012-11-13 17:14:08 -06001136 // Figure out new value at this location
1137 if (i == 3) {
1138 // suid/sticky bit.
1139 if (j) {
1140 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
1141 } else if (dowhat & 16) bit++;
1142 } else {
1143 if (!(dowho&(8|(1<<i)))) continue;
1144 if (dowhat&(1<<j)) bit++;
1145 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001146
Rob Landley7aa651a2012-11-13 17:14:08 -06001147 // When selection active, modify bit
Rob Landleyb6f601e2012-05-16 21:11:43 -05001148
Rob Landley7aa651a2012-11-13 17:14:08 -06001149 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
1150 if (bit && dohow != '-') mode |= where;
1151 }
1152 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001153
Rob Landley7aa651a2012-11-13 17:14:08 -06001154 if (!*str) break;
1155 }
1156 return mode;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001157barf:
Rob Landley7aa651a2012-11-13 17:14:08 -06001158 error_exit("bad mode '%s'", modestr);
Daniel Walter05744b32012-03-19 19:57:56 -05001159}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001160
1161
1162char* make_human_readable(unsigned long long size, unsigned long unit)
1163{
Rob Landley7aa651a2012-11-13 17:14:08 -06001164 unsigned int frac = 0;
1165 if(unit) {
1166 size = (size/(unit)) + (size%(unit)?1:0);
1167 return xmsprintf("%llu", size);
1168 }
1169 else {
1170 static char units[] = {'\0', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
1171 int index = 0;
1172 while(size >= 1024) {
1173 frac = size%1024;
1174 size /= 1024;
1175 index++;
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001176 }
Rob Landley7aa651a2012-11-13 17:14:08 -06001177 frac = (frac/102) + ((frac%102)?1:0);
1178 if(frac >= 10) {
1179 size += 1;
1180 frac = 0;
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001181 }
Rob Landley7aa651a2012-11-13 17:14:08 -06001182 if(frac) return xmsprintf("%llu.%u%c", size, frac, units[index]);
1183 else return xmsprintf("%llu%c", size, units[index]);
1184 }
1185 return NULL; //not reached
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001186}
Rob Landley734b5302012-11-16 12:26:48 -06001187
Jonathan Clairembault939fa742012-11-23 00:06:28 +01001188// strtoul with exit on error
1189unsigned long xstrtoul(const char *nptr, char **endptr, int base)
1190{
1191 unsigned long l;
1192 errno = 0;
1193 l = strtoul(nptr, endptr, base);
1194 if (errno)
1195 perror_exit("xstrtoul");
1196 return l;
1197}
1198
Rob Landley734b5302012-11-16 12:26:48 -06001199/*
1200 * used to get the interger value.
1201 */
1202unsigned long get_int_value(const char *numstr, unsigned lowrange, unsigned highrange)
1203{
1204 unsigned long rvalue = 0;
1205 char *ptr;
1206 if(*numstr == '-' || *numstr == '+' || isspace(*numstr)) perror_exit("invalid number '%s'", numstr);
1207 errno = 0;
1208 rvalue = strtoul(numstr, &ptr, 10);
1209 if(errno || numstr == ptr) perror_exit("invalid number '%s'", numstr);
1210 if(*ptr) perror_exit("invalid number '%s'", numstr);
1211 if(rvalue >= lowrange && rvalue <= highrange) return rvalue;
1212 else {
1213 perror_exit("invalid number '%s'", numstr);
1214 return rvalue; //Not reachable; to avoid waring message.
1215 }
1216}