blob: b89f2db8399b5d63d5d0898957847149f944f195 [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.
Rob Landleybe93c912013-04-20 23:33:48 -050014void xstrncpy(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 Landley36ffc5a2013-04-14 21:43:22 -050055 if (CFG_TOYBOX_HELP && toys.exithelp) show_help();
Rob Landleyd06c58d2007-10-11 15:36:36 -050056
Rob Landley7aa651a2012-11-13 17:14:08 -060057 va_start(va, msg);
58 verror_msg(msg, 0, va);
59 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050060
Rob Landleycaf39c22012-11-16 00:35:46 -060061 if (toys.rebound) longjmp(*toys.rebound, 1);
62 else exit(toys.exitval);
landley09ea7ac2006-10-30 01:38:00 -050063}
64
Rob Landley055cfcb2007-01-14 20:20:06 -050065
landley09ea7ac2006-10-30 01:38:00 -050066// Die with an error message and strerror(errno)
67void perror_exit(char *msg, ...)
68{
Rob Landley7aa651a2012-11-13 17:14:08 -060069 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050070
Rob Landley7aa651a2012-11-13 17:14:08 -060071 va_start(va, msg);
72 verror_msg(msg, errno, va);
73 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050074
Rob Landleycaf39c22012-11-16 00:35:46 -060075 if (toys.rebound) longjmp(*toys.rebound, 1);
76 else exit(toys.exitval);
landley4f344e32006-10-05 16:18:03 -040077}
78
landley4f344e32006-10-05 16:18:03 -040079// Die unless we can allocate memory.
80void *xmalloc(size_t size)
81{
Rob Landley7aa651a2012-11-13 17:14:08 -060082 void *ret = malloc(size);
83 if (!ret) error_exit("xmalloc");
landleycd9dfc32006-10-18 18:38:16 -040084
Rob Landley7aa651a2012-11-13 17:14:08 -060085 return ret;
landley4f344e32006-10-05 16:18:03 -040086}
87
landleycd9dfc32006-10-18 18:38:16 -040088// Die unless we can allocate prezeroed memory.
89void *xzalloc(size_t size)
90{
Rob Landley7aa651a2012-11-13 17:14:08 -060091 void *ret = xmalloc(size);
92 memset(ret, 0, size);
93 return ret;
landleycd9dfc32006-10-18 18:38:16 -040094}
95
96// Die unless we can change the size of an existing allocation, possibly
97// moving it. (Notice different arguments from libc function.)
Rob Landley0c93f6c2007-04-29 19:55:21 -040098void *xrealloc(void *ptr, size_t size)
landleycd9dfc32006-10-18 18:38:16 -040099{
Rob Landley7aa651a2012-11-13 17:14:08 -0600100 ptr = realloc(ptr, size);
101 if (!ptr) error_exit("xrealloc");
Rob Landley0c93f6c2007-04-29 19:55:21 -0400102
Rob Landley7aa651a2012-11-13 17:14:08 -0600103 return ptr;
landleycd9dfc32006-10-18 18:38:16 -0400104}
105
Rob Landleyfa98d012006-11-02 02:57:27 -0500106// Die unless we can allocate a copy of this many bytes of string.
Rob Landley1e01cd12010-01-05 10:48:32 -0600107char *xstrndup(char *s, size_t n)
landley4f344e32006-10-05 16:18:03 -0400108{
Rob Landley7aa651a2012-11-13 17:14:08 -0600109 char *ret = xmalloc(++n);
110 strncpy(ret, s, n);
111 ret[--n]=0;
Rob Landley2c226852007-11-15 18:30:30 -0600112
Rob Landley7aa651a2012-11-13 17:14:08 -0600113 return ret;
landley4f344e32006-10-05 16:18:03 -0400114}
115
Rob Landleyfa98d012006-11-02 02:57:27 -0500116// Die unless we can allocate a copy of this string.
Rob Landley1e01cd12010-01-05 10:48:32 -0600117char *xstrdup(char *s)
Rob Landleyfa98d012006-11-02 02:57:27 -0500118{
Rob Landley7aa651a2012-11-13 17:14:08 -0600119 return xstrndup(s, strlen(s));
Rob Landleyfa98d012006-11-02 02:57:27 -0500120}
121
landley00f87f12006-10-25 18:38:37 -0400122// Die unless we can allocate enough space to sprintf() into.
123char *xmsprintf(char *format, ...)
124{
Rob Landley7aa651a2012-11-13 17:14:08 -0600125 va_list va, va2;
126 int len;
127 char *ret;
Rob Landley2c226852007-11-15 18:30:30 -0600128
Rob Landley7aa651a2012-11-13 17:14:08 -0600129 va_start(va, format);
130 va_copy(va2, va);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400131
Rob Landley7aa651a2012-11-13 17:14:08 -0600132 // How long is it?
133 len = vsnprintf(0, 0, format, va);
134 len++;
135 va_end(va);
landley00f87f12006-10-25 18:38:37 -0400136
Rob Landley7aa651a2012-11-13 17:14:08 -0600137 // Allocate and do the sprintf()
138 ret = xmalloc(len);
139 vsnprintf(ret, len, format, va2);
140 va_end(va2);
landley00f87f12006-10-25 18:38:37 -0400141
Rob Landley7aa651a2012-11-13 17:14:08 -0600142 return ret;
landley00f87f12006-10-25 18:38:37 -0400143}
144
Rob Landley24d1d452007-01-20 18:04:20 -0500145void xprintf(char *format, ...)
146{
Rob Landley7aa651a2012-11-13 17:14:08 -0600147 va_list va;
148 va_start(va, format);
Rob Landley24d1d452007-01-20 18:04:20 -0500149
Rob Landley7aa651a2012-11-13 17:14:08 -0600150 vprintf(format, va);
151 if (ferror(stdout)) perror_exit("write");
Rob Landley24d1d452007-01-20 18:04:20 -0500152}
153
Rob Landley5084fea2007-06-18 00:14:03 -0400154void xputs(char *s)
155{
Elie De Brauwerca4035b2012-12-16 13:43:36 +0100156 if (EOF == puts(s) || fflush(stdout)) perror_exit("write");
Rob Landley5084fea2007-06-18 00:14:03 -0400157}
158
Rob Landley24d1d452007-01-20 18:04:20 -0500159void xputc(char c)
160{
Rob Landley7aa651a2012-11-13 17:14:08 -0600161 if (EOF == fputc(c, stdout) || fflush(stdout)) perror_exit("write");
Rob Landley24d1d452007-01-20 18:04:20 -0500162}
163
164void xflush(void)
165{
Rob Landley7aa651a2012-11-13 17:14:08 -0600166 if (fflush(stdout)) perror_exit("write");;
Rob Landley24d1d452007-01-20 18:04:20 -0500167}
168
landleycd9dfc32006-10-18 18:38:16 -0400169// Die unless we can exec argv[] (or run builtin command). Note that anything
170// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500171void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400172{
Rob Landley7aa651a2012-11-13 17:14:08 -0600173 toy_exec(argv);
174 execvp(argv[0], argv);
Rob Landley26e7b5e2012-02-02 07:27:35 -0600175
Rob Landley7aa651a2012-11-13 17:14:08 -0600176 perror_exit("exec %s", argv[0]);
landley4f344e32006-10-05 16:18:03 -0400177}
178
Rob Landleyd3e9d642007-01-08 03:25:47 -0500179void xaccess(char *path, int flags)
180{
Rob Landley7aa651a2012-11-13 17:14:08 -0600181 if (access(path, flags)) perror_exit("Can't access '%s'", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500182}
183
Rob Landleye745d8e2007-12-20 06:30:19 -0600184// Die unless we can delete a file. (File must exist to be deleted.)
185void xunlink(char *path)
186{
Rob Landley7aa651a2012-11-13 17:14:08 -0600187 if (unlink(path)) perror_exit("unlink '%s'", path);
Rob Landleye745d8e2007-12-20 06:30:19 -0600188}
189
landley4f344e32006-10-05 16:18:03 -0400190// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500191int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400192{
Rob Landley7aa651a2012-11-13 17:14:08 -0600193 int fd = open(path, flags, mode);
194 if (fd == -1) perror_exit("%s", path);
195 return fd;
landley4f344e32006-10-05 16:18:03 -0400196}
197
Rob Landley1322beb2007-01-07 22:51:12 -0500198// Die unless we can open a file, returning file descriptor.
199int xopen(char *path, int flags)
200{
Rob Landley7aa651a2012-11-13 17:14:08 -0600201 return xcreate(path, flags, 0);
Rob Landley1322beb2007-01-07 22:51:12 -0500202}
203
Rob Landleybc078652007-12-15 21:47:25 -0600204void xclose(int fd)
205{
Rob Landley7aa651a2012-11-13 17:14:08 -0600206 if (close(fd)) perror_exit("xclose");
Rob Landleybc078652007-12-15 21:47:25 -0600207}
208
Rob Landleyeb7ea222012-04-14 22:30:41 -0500209int xdup(int fd)
210{
Rob Landley7aa651a2012-11-13 17:14:08 -0600211 if (fd != -1) {
212 fd = dup(fd);
213 if (fd == -1) perror_exit("xdup");
214 }
215 return fd;
Rob Landleyeb7ea222012-04-14 22:30:41 -0500216}
217
landley4f344e32006-10-05 16:18:03 -0400218// Die unless we can open/create a file, returning FILE *.
219FILE *xfopen(char *path, char *mode)
220{
Rob Landley7aa651a2012-11-13 17:14:08 -0600221 FILE *f = fopen(path, mode);
222 if (!f) perror_exit("No file %s", path);
223 return f;
landley4f344e32006-10-05 16:18:03 -0400224}
landley00f87f12006-10-25 18:38:37 -0400225
landley64b2e232006-10-30 10:01:19 -0500226// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500227ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500228{
Rob Landley7aa651a2012-11-13 17:14:08 -0600229 size_t count = 0;
Rob Landley15b23152008-07-18 04:15:59 -0500230
Rob Landley7aa651a2012-11-13 17:14:08 -0600231 while (count<len) {
232 int i = read(fd, buf+count, len-count);
233 if (!i) break;
234 if (i<0) return i;
235 count += i;
236 }
landley64b2e232006-10-30 10:01:19 -0500237
Rob Landley7aa651a2012-11-13 17:14:08 -0600238 return count;
landley64b2e232006-10-30 10:01:19 -0500239}
240
Rob Landleyf3e452a2007-01-08 02:49:39 -0500241// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500242ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500243{
Rob Landley7aa651a2012-11-13 17:14:08 -0600244 size_t count = 0;
245 while (count<len) {
246 int i = write(fd, buf+count, len-count);
247 if (i<1) return i;
248 count += i;
249 }
Rob Landleyf3e452a2007-01-08 02:49:39 -0500250
Rob Landley7aa651a2012-11-13 17:14:08 -0600251 return count;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500252}
253
Rob Landley055cfcb2007-01-14 20:20:06 -0500254// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500255size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500256{
Rob Landley7aa651a2012-11-13 17:14:08 -0600257 ssize_t ret = read(fd, buf, len);
258 if (ret < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500259
Rob Landley7aa651a2012-11-13 17:14:08 -0600260 return ret;
Rob Landley055cfcb2007-01-14 20:20:06 -0500261}
262
Rob Landley90163772007-01-18 21:54:08 -0500263void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500264{
Rob Landley7aa651a2012-11-13 17:14:08 -0600265 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500266}
landley00f87f12006-10-25 18:38:37 -0400267
Rob Landley90163772007-01-18 21:54:08 -0500268// There's no xwriteall(), just xwrite(). When we read, there may or may not
269// be more data waiting. When we write, there is data and it had better go
270// somewhere.
271
272void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500273{
Rob Landley7aa651a2012-11-13 17:14:08 -0600274 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500275}
276
Rob Landley52476712009-01-18 16:19:25 -0600277// Die if lseek fails, probably due to being called on a pipe.
278
279off_t xlseek(int fd, off_t offset, int whence)
280{
Rob Landley7aa651a2012-11-13 17:14:08 -0600281 offset = lseek(fd, offset, whence);
282 if (offset<0) perror_exit("lseek");
Rob Landley52476712009-01-18 16:19:25 -0600283
Rob Landley7aa651a2012-11-13 17:14:08 -0600284 return offset;
Rob Landley52476712009-01-18 16:19:25 -0600285}
286
Rob Landley2037b832012-07-15 16:56:20 -0500287off_t lskip(int fd, off_t offset)
288{
Rob Landley7aa651a2012-11-13 17:14:08 -0600289 off_t and = lseek(fd, offset, SEEK_CUR);
Rob Landley2037b832012-07-15 16:56:20 -0500290
Rob Landley7aa651a2012-11-13 17:14:08 -0600291 if (and != -1 && offset >= lseek(fd, offset, SEEK_END)
292 && offset+and == lseek(fd, offset+and, SEEK_SET)) return 0;
293 else {
294 char buf[4096];
295 while (offset>0) {
296 int try = offset>sizeof(buf) ? sizeof(buf) : offset, or;
Rob Landley2037b832012-07-15 16:56:20 -0500297
Rob Landley7aa651a2012-11-13 17:14:08 -0600298 or = readall(fd, buf, try);
299 if (or < 0) perror_msg("lskip to %lld", (long long)offset);
300 else offset -= try;
301 if (or < try) break;
302 }
Rob Landley2037b832012-07-15 16:56:20 -0500303
Rob Landley7aa651a2012-11-13 17:14:08 -0600304 return offset;
305 }
Rob Landley2037b832012-07-15 16:56:20 -0500306}
307
landley00f87f12006-10-25 18:38:37 -0400308char *xgetcwd(void)
309{
Rob Landley7aa651a2012-11-13 17:14:08 -0600310 char *buf = getcwd(NULL, 0);
311 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500312
Rob Landley7aa651a2012-11-13 17:14:08 -0600313 return buf;
landley00f87f12006-10-25 18:38:37 -0400314}
315
Rob Landleyd25f7e42007-02-03 14:11:26 -0500316void xstat(char *path, struct stat *st)
317{
Rob Landley7aa651a2012-11-13 17:14:08 -0600318 if(stat(path, st)) perror_exit("Can't stat %s", path);
Rob Landleyd25f7e42007-02-03 14:11:26 -0500319}
320
Rob Landleyfe91e682012-11-22 21:18:09 -0600321// Split a path into linked list of components, tracking head and tail of list.
322// Filters out // entries with no contents.
323struct string_list **splitpath(char *path, struct string_list **list)
landley00f87f12006-10-25 18:38:37 -0400324{
Rob Landleyfe91e682012-11-22 21:18:09 -0600325 char *new = path;
landley00f87f12006-10-25 18:38:37 -0400326
Rob Landleyfe91e682012-11-22 21:18:09 -0600327 *list = 0;
328 do {
329 int len;
landley00f87f12006-10-25 18:38:37 -0400330
Rob Landleyfe91e682012-11-22 21:18:09 -0600331 if (*path && *path != '/') continue;
332 len = path-new;
333 if (len > 0) {
334 *list = xmalloc(sizeof(struct string_list) + len + 1);
335 (*list)->next = 0;
336 strncpy((*list)->str, new, len);
337 (*list)->str[len] = 0;
338 list = &(*list)->next;
339 }
340 new = path+1;
341 } while (*path++);
342
343 return list;
344}
345
346// Cannonicalize path, even to file with one or more missing components at end.
347// if exact, require last path component to exist
348char *xabspath(char *path, int exact)
349{
350 struct string_list *todo, *done = 0;
351 int try = 9999, dirfd = open("/", 0);;
352 char buf[4096], *ret;
353
354 // If this isn't an absolute path, start with cwd.
355 if (*path != '/') {
356 char *temp = xgetcwd();
357
358 splitpath(path, splitpath(temp, &todo));
Rob Landleybd2e2272012-11-20 09:21:52 -0600359 free(temp);
Rob Landleyfe91e682012-11-22 21:18:09 -0600360 } else splitpath(path, &todo);
361
362 // Iterate through path components
363 while (todo) {
364 struct string_list *new = llist_pop(&todo), **tail;
365 ssize_t len;
366
367 if (!try--) {
368 errno = ELOOP;
369 goto error;
370 }
371
372 // Removable path componenents.
373 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
Rob Landley7c0e2802013-01-17 23:16:38 -0600374 int x = new->str[1];
375
Rob Landleyfe91e682012-11-22 21:18:09 -0600376 free(new);
Rob Landley7c0e2802013-01-17 23:16:38 -0600377 if (x) {
378 if (done) free(llist_pop(&done));
379 len = 0;
380 } else continue;
Rob Landleyfe91e682012-11-22 21:18:09 -0600381
382 // Is this a symlink?
Rob Landley7c0e2802013-01-17 23:16:38 -0600383 } else len=readlinkat(dirfd, new->str, buf, 4096);
384
Rob Landleyfe91e682012-11-22 21:18:09 -0600385 if (len>4095) goto error;
386 if (len<1) {
387 int fd;
Rob Landley7c0e2802013-01-17 23:16:38 -0600388 char *s = "..";
Rob Landleyfe91e682012-11-22 21:18:09 -0600389
Rob Landley7c0e2802013-01-17 23:16:38 -0600390 // For .. just move dirfd
391 if (len) {
392 // Not a symlink: add to linked list, move dirfd, fail if error
393 if ((exact || todo) && errno != EINVAL) goto error;
394 new->next = done;
395 done = new;
396 s = new->str;
397 }
398 fd = openat(dirfd, s, 0);
399 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
Rob Landleyfe91e682012-11-22 21:18:09 -0600400 close(dirfd);
401 dirfd = fd;
402 continue;
403 }
404
405 // If this symlink is to an absolute path, discard existing resolved path
406 buf[len] = 0;
407 if (*buf == '/') {
408 llist_traverse(done, free);
409 done=0;
410 close(dirfd);
411 dirfd = open("/", 0);
412 }
413 free(new);
414
415 // prepend components of new path. Note symlink to "/" will leave new NULL
416 tail = splitpath(buf, &new);
417
418 // symlink to "/" will return null and leave tail alone
419 if (new) {
420 *tail = todo;
421 todo = new;
422 }
423 }
424 close(dirfd);
425
426 // At this point done has the path, in reverse order. Reverse list while
427 // calculating buffer length.
428
429 try = 2;
430 while (done) {
431 struct string_list *temp = llist_pop(&done);;
432
433 if (todo) try++;
434 try += strlen(temp->str);
435 temp->next = todo;
436 todo = temp;
Rob Landley7aa651a2012-11-13 17:14:08 -0600437 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500438
Rob Landleyfe91e682012-11-22 21:18:09 -0600439 // Assemble return buffer
440
441 ret = xmalloc(try);
442 *ret = '/';
443 ret [try = 1] = 0;
444 while (todo) {
445 if (try>1) ret[try++] = '/';
446 try = stpcpy(ret+try, todo->str) - ret;
447 free(llist_pop(&todo));
Rob Landleybd2e2272012-11-20 09:21:52 -0600448 }
449
Rob Landleyfe91e682012-11-22 21:18:09 -0600450 return ret;
451
452error:
453 close(dirfd);
454 llist_traverse(todo, free);
455 llist_traverse(done, free);
456
457 return NULL;
Rob Landleyfa98d012006-11-02 02:57:27 -0500458}
459
Rob Landleyeec46372012-06-01 13:50:41 -0500460// Resolve all symlinks, returning malloc() memory.
461char *xrealpath(char *path)
462{
Rob Landley7aa651a2012-11-13 17:14:08 -0600463 char *new = realpath(path, NULL);
464 if (!new) perror_exit("realpath '%s'", path);
465 return new;
Rob Landleyeec46372012-06-01 13:50:41 -0500466}
467
Rob Landley988abb32008-05-12 00:52:27 -0500468void xchdir(char *path)
469{
Rob Landley7aa651a2012-11-13 17:14:08 -0600470 if (chdir(path)) error_exit("chdir '%s'", path);
Rob Landley988abb32008-05-12 00:52:27 -0500471}
472
Rob Landley35483412007-12-27 21:36:33 -0600473// Ensure entire path exists.
474// If mode != -1 set permissions on newly created dirs.
475// Requires that path string be writable (for temporary null terminators).
476void xmkpath(char *path, int mode)
477{
Rob Landley7aa651a2012-11-13 17:14:08 -0600478 char *p, old;
479 mode_t mask;
480 int rc;
481 struct stat st;
Rob Landley35483412007-12-27 21:36:33 -0600482
Rob Landley7aa651a2012-11-13 17:14:08 -0600483 for (p = path; ; p++) {
484 if (!*p || *p == '/') {
485 old = *p;
486 *p = rc = 0;
487 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
488 if (mode != -1) {
489 mask=umask(0);
490 rc = mkdir(path, mode);
491 umask(mask);
492 } else rc = mkdir(path, 0777);
493 }
494 *p = old;
495 if(rc) perror_exit("mkpath '%s'", path);
496 }
497 if (!*p) break;
498 }
Rob Landley35483412007-12-27 21:36:33 -0600499}
Rob Landleye0377fb2010-01-05 12:17:05 -0600500
501// setuid() can fail (for example, too many processes belonging to that user),
502// which opens a security hole if the process continues as the original user.
503
504void xsetuid(uid_t uid)
505{
Rob Landley7aa651a2012-11-13 17:14:08 -0600506 if (setuid(uid)) perror_exit("xsetuid");
Rob Landleye0377fb2010-01-05 12:17:05 -0600507}
508
509
Rob Landley0a04b3e2006-11-03 00:05:52 -0500510// Find all file in a colon-separated path with access type "type" (generally
511// X_OK or R_OK). Returns a list of absolute paths to each file found, in
512// order.
513
514struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500515{
Rob Landley7aa651a2012-11-13 17:14:08 -0600516 struct string_list *rlist = NULL, **prlist=&rlist;
517 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500518
Rob Landley7aa651a2012-11-13 17:14:08 -0600519 for (;;) {
520 char *next = path ? strchr(path, ':') : NULL;
521 int len = next ? next-path : strlen(path);
522 struct string_list *rnext;
523 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500524
Rob Landley7aa651a2012-11-13 17:14:08 -0600525 rnext = xmalloc(sizeof(void *) + strlen(filename)
526 + (len ? len : strlen(cwd)) + 2);
527 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
528 else {
529 char *res = rnext->str;
530 strncpy(res, path, len);
531 res += len;
532 *(res++) = '/';
533 strcpy(res, filename);
534 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500535
Rob Landley7aa651a2012-11-13 17:14:08 -0600536 // Confirm it's not a directory.
537 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
538 *prlist = rnext;
539 rnext->next = NULL;
540 prlist = &(rnext->next);
541 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500542
Rob Landley7aa651a2012-11-13 17:14:08 -0600543 if (!next) break;
544 path += len;
545 path++;
546 }
547 free(cwd);
landley00f87f12006-10-25 18:38:37 -0400548
Rob Landley7aa651a2012-11-13 17:14:08 -0600549 return rlist;
landley00f87f12006-10-25 18:38:37 -0400550}
landley09ea7ac2006-10-30 01:38:00 -0500551
552// Convert unsigned int to ascii, writing into supplied buffer. A truncated
553// result contains the first few digits of the result ala strncpy, and is
554// always null terminated (unless buflen is 0).
555void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
556{
Rob Landley7aa651a2012-11-13 17:14:08 -0600557 int i, out = 0;
landley09ea7ac2006-10-30 01:38:00 -0500558
Rob Landley7aa651a2012-11-13 17:14:08 -0600559 if (buflen) {
560 for (i=1000000000; i; i/=10) {
561 int res = n/i;
landley09ea7ac2006-10-30 01:38:00 -0500562
Rob Landley7aa651a2012-11-13 17:14:08 -0600563 if ((res || out || i == 1) && --buflen>0) {
564 out++;
565 n -= res*i;
566 *buf++ = '0' + res;
567 }
568 }
569 *buf = 0;
570 }
landley09ea7ac2006-10-30 01:38:00 -0500571}
572
573// Convert signed integer to ascii, using utoa_to_buf()
574void itoa_to_buf(int n, char *buf, unsigned buflen)
575{
Rob Landley7aa651a2012-11-13 17:14:08 -0600576 if (buflen && n<0) {
577 n = -n;
578 *buf++ = '-';
579 buflen--;
580 }
581 utoa_to_buf((unsigned)n, buf, buflen);
landley09ea7ac2006-10-30 01:38:00 -0500582}
583
584// This static buffer is used by both utoa() and itoa(), calling either one a
585// second time will overwrite the previous results.
586//
587// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
588// Note that int is always 32 bits on any remotely unix-like system, see
589// http://www.unix.org/whitepapers/64bit.html for details.
590
591static char itoa_buf[12];
592
593// Convert unsigned integer to ascii, returning a static buffer.
594char *utoa(unsigned n)
595{
Rob Landley7aa651a2012-11-13 17:14:08 -0600596 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
landley09ea7ac2006-10-30 01:38:00 -0500597
Rob Landley7aa651a2012-11-13 17:14:08 -0600598 return itoa_buf;
landley09ea7ac2006-10-30 01:38:00 -0500599}
600
601char *itoa(int n)
602{
Rob Landley7aa651a2012-11-13 17:14:08 -0600603 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
landley09ea7ac2006-10-30 01:38:00 -0500604
Rob Landley7aa651a2012-11-13 17:14:08 -0600605 return itoa_buf;
landley09ea7ac2006-10-30 01:38:00 -0500606}
Rob Landley055cfcb2007-01-14 20:20:06 -0500607
Rob Landleyf5757162007-02-16 21:08:22 -0500608// atol() with the kilo/mega/giga/tera/peta/exa extensions.
609// (zetta and yotta don't fit in 64 bits.)
Rob Landley5e6dca62012-02-09 06:09:27 -0600610long atolx(char *numstr)
Rob Landleyf5757162007-02-16 21:08:22 -0500611{
Rob Landley7aa651a2012-11-13 17:14:08 -0600612 char *c, *suffixes="bkmgtpe", *end;
613 long val = strtol(numstr, &c, 0);
Rob Landleyf5757162007-02-16 21:08:22 -0500614
Rob Landley7aa651a2012-11-13 17:14:08 -0600615 if (*c) {
616 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
617 int shift = end-suffixes;
618 if (shift--) val *= 1024L<<(shift*10);
619 } else {
620 while (isspace(*c)) c++;
621 if (*c) error_exit("not integer: %s", numstr);
622 }
623 }
Rob Landleyad63f4b2011-12-12 15:19:52 -0600624
Rob Landley7aa651a2012-11-13 17:14:08 -0600625 return val;
Rob Landleyf5757162007-02-16 21:08:22 -0500626}
627
Rob Landleyeb7ea222012-04-14 22:30:41 -0500628int numlen(long l)
629{
Rob Landley7aa651a2012-11-13 17:14:08 -0600630 int len = 0;
631 while (l) {
632 l /= 10;
633 len++;
634 }
635 return len;
Rob Landleyeb7ea222012-04-14 22:30:41 -0500636}
637
Rob Landley2037b832012-07-15 16:56:20 -0500638int stridx(char *haystack, char needle)
639{
Rob Landley7aa651a2012-11-13 17:14:08 -0600640 char *off;
Rob Landley2037b832012-07-15 16:56:20 -0500641
Rob Landley7aa651a2012-11-13 17:14:08 -0600642 if (!needle) return -1;
643 off = strchr(haystack, needle);
644 if (!off) return -1;
Rob Landley2037b832012-07-15 16:56:20 -0500645
Rob Landley7aa651a2012-11-13 17:14:08 -0600646 return off-haystack;
Rob Landley2037b832012-07-15 16:56:20 -0500647}
648
Rob Landley055cfcb2007-01-14 20:20:06 -0500649// Return how long the file at fd is, if there's any way to determine it.
650off_t fdlength(int fd)
651{
Rob Landley7aa651a2012-11-13 17:14:08 -0600652 off_t bottom = 0, top = 0, pos, old;
653 int size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500654
Rob Landley7aa651a2012-11-13 17:14:08 -0600655 // If the ioctl works for this, return it.
Rob Landley055cfcb2007-01-14 20:20:06 -0500656
Rob Landley7aa651a2012-11-13 17:14:08 -0600657 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500658
Rob Landley7aa651a2012-11-13 17:14:08 -0600659 // If not, do a binary search for the last location we can read. (Some
660 // block devices don't do BLKGETSIZE right.) This should probably have
661 // a CONFIG option...
Rob Landley055cfcb2007-01-14 20:20:06 -0500662
Rob Landley7aa651a2012-11-13 17:14:08 -0600663 old = lseek(fd, 0, SEEK_CUR);
664 do {
665 char temp;
Rob Landley055cfcb2007-01-14 20:20:06 -0500666
Rob Landley7aa651a2012-11-13 17:14:08 -0600667 pos = bottom + (top - bottom) / 2;
Rob Landley055cfcb2007-01-14 20:20:06 -0500668
Rob Landley7aa651a2012-11-13 17:14:08 -0600669 // If we can read from the current location, it's bigger.
Rob Landley055cfcb2007-01-14 20:20:06 -0500670
Rob Landley7aa651a2012-11-13 17:14:08 -0600671 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
672 if (bottom == top) bottom = top = (top+1) * 2;
673 else bottom = pos;
Rob Landley055cfcb2007-01-14 20:20:06 -0500674
Rob Landley7aa651a2012-11-13 17:14:08 -0600675 // If we can't, it's smaller.
Rob Landley055cfcb2007-01-14 20:20:06 -0500676
Rob Landley7aa651a2012-11-13 17:14:08 -0600677 } else {
678 if (bottom == top) {
679 if (!top) return 0;
680 bottom = top/2;
681 } else top = pos;
682 }
683 } while (bottom + 1 != top);
Rob Landley055cfcb2007-01-14 20:20:06 -0500684
Rob Landley7aa651a2012-11-13 17:14:08 -0600685 lseek(fd, old, SEEK_SET);
Rob Landleyf15387d2008-07-18 05:43:44 -0500686
Rob Landley7aa651a2012-11-13 17:14:08 -0600687 return pos + 1;
Rob Landley055cfcb2007-01-14 20:20:06 -0500688}
689
Rob Landley0c93f6c2007-04-29 19:55:21 -0400690// This can return null (meaning file not found). It just won't return null
691// for memory allocation reasons.
692char *xreadlink(char *name)
693{
Rob Landley7aa651a2012-11-13 17:14:08 -0600694 int len, size = 0;
695 char *buf = 0;
Rob Landley0c93f6c2007-04-29 19:55:21 -0400696
Rob Landley7aa651a2012-11-13 17:14:08 -0600697 // Grow by 64 byte chunks until it's big enough.
698 for(;;) {
699 size +=64;
700 buf = xrealloc(buf, size);
701 len = readlink(name, buf, size);
Rob Landley0c93f6c2007-04-29 19:55:21 -0400702
Rob Landley7aa651a2012-11-13 17:14:08 -0600703 if (len<0) {
704 free(buf);
705 return 0;
706 }
707 if (len<size) {
708 buf[len]=0;
709 return buf;
710 }
711 }
Rob Landley0c93f6c2007-04-29 19:55:21 -0400712}
713
Rob Landleyb3a33822007-01-25 16:10:37 -0500714/*
715 This might be of use or might not. Unknown yet...
716
Rob Landley055cfcb2007-01-14 20:20:06 -0500717// Read contents of file as a single freshly allocated nul-terminated string.
718char *readfile(char *name)
719{
Rob Landley7aa651a2012-11-13 17:14:08 -0600720 off_t len;
721 int fd;
722 char *buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500723
Rob Landley7aa651a2012-11-13 17:14:08 -0600724 fd = open(name, O_RDONLY);
725 if (fd == -1) return 0;
726 len = fdlength(fd);
727 buf = xmalloc(len+1);
728 buf[readall(fd, buf, len)] = 0;
Rob Landley055cfcb2007-01-14 20:20:06 -0500729
Rob Landley7aa651a2012-11-13 17:14:08 -0600730 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500731}
732
733char *xreadfile(char *name)
734{
Rob Landley7aa651a2012-11-13 17:14:08 -0600735 char *buf = readfile(name);
736 if (!buf) perror_exit("xreadfile %s", name);
737 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500738}
739
740*/
741
Rob Landleyf0153442013-04-26 02:41:05 -0500742
743// Sleep for this many thousandths of a second
744void msleep(long miliseconds)
745{
746 struct timespec ts;
747
748 ts.tv_sec = miliseconds/1000;
749 ts.tv_nsec = (miliseconds%1000)*1000000;
750 nanosleep(&ts, &ts);
751}
752
753int xioctl(int fd, int request, void *data)
754{
755 int rc;
756
757 errno = 0;
758 rc = ioctl(fd, request, data);
759 if (rc == -1 && errno) perror_exit("ioctl %d", request);
760
761 return rc;
762}
763
Rob Landley055cfcb2007-01-14 20:20:06 -0500764// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
765// exists and is this executable.
766void xpidfile(char *name)
767{
Rob Landley7aa651a2012-11-13 17:14:08 -0600768 char pidfile[256], spid[32];
769 int i, fd;
770 pid_t pid;
Rob Landley055cfcb2007-01-14 20:20:06 -0500771
Rob Landley7aa651a2012-11-13 17:14:08 -0600772 sprintf(pidfile, "/var/run/%s.pid", name);
773 // Try three times to open the sucker.
774 for (i=0; i<3; i++) {
775 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
776 if (fd != -1) break;
Rob Landley055cfcb2007-01-14 20:20:06 -0500777
Rob Landley7aa651a2012-11-13 17:14:08 -0600778 // If it already existed, read it. Loop for race condition.
779 fd = open(pidfile, O_RDONLY);
780 if (fd == -1) continue;
Rob Landley055cfcb2007-01-14 20:20:06 -0500781
Rob Landley7aa651a2012-11-13 17:14:08 -0600782 // Is the old program still there?
783 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
784 close(fd);
785 pid = atoi(spid);
786 if (pid < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
Rob Landley2c226852007-11-15 18:30:30 -0600787
Rob Landley7aa651a2012-11-13 17:14:08 -0600788 // An else with more sanity checking might be nice here.
789 }
Rob Landley055cfcb2007-01-14 20:20:06 -0500790
Rob Landley7aa651a2012-11-13 17:14:08 -0600791 if (i == 3) error_exit("xpidfile %s", name);
792
793 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
794 close(fd);
Rob Landley055cfcb2007-01-14 20:20:06 -0500795}
Rob Landley7634b552007-11-29 17:49:50 -0600796
Rob Landley2bfaaf22008-07-03 19:19:00 -0500797// Iterate through an array of files, opening each one and calling a function
798// on that filehandle and name. The special filename "-" means stdin if
799// flags is O_RDONLY, stdout otherwise. An empty argument list calls
800// function() on just stdin/stdout.
801//
802// Note: read only filehandles are automatically closed when function()
803// returns, but writeable filehandles must be close by function()
Rob Landleyad63f4b2011-12-12 15:19:52 -0600804void loopfiles_rw(char **argv, int flags, int permissions, int failok,
Rob Landley7aa651a2012-11-13 17:14:08 -0600805 void (*function)(int fd, char *name))
Rob Landley7634b552007-11-29 17:49:50 -0600806{
Rob Landley7aa651a2012-11-13 17:14:08 -0600807 int fd;
Rob Landley7634b552007-11-29 17:49:50 -0600808
Rob Landley7aa651a2012-11-13 17:14:08 -0600809 // If no arguments, read from stdin.
810 if (!*argv) function(flags ? 1 : 0, "-");
811 else do {
812 // Filename "-" means read from stdin.
813 // Inability to open a file prints a warning, but doesn't exit.
Rob Landley7634b552007-11-29 17:49:50 -0600814
Rob Landley7aa651a2012-11-13 17:14:08 -0600815 if (!strcmp(*argv,"-")) fd=0;
816 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
817 perror_msg("%s", *argv);
818 toys.exitval = 1;
819 continue;
820 }
821 function(fd, *argv);
822 if (flags == O_RDONLY) close(fd);
823 } while (*++argv);
Rob Landley7634b552007-11-29 17:49:50 -0600824}
Rob Landleybc078652007-12-15 21:47:25 -0600825
Rob Landleyad63f4b2011-12-12 15:19:52 -0600826// Call loopfiles_rw with O_RDONLY and !failok (common case).
Rob Landley2bfaaf22008-07-03 19:19:00 -0500827void loopfiles(char **argv, void (*function)(int fd, char *name))
828{
Rob Landley7aa651a2012-11-13 17:14:08 -0600829 loopfiles_rw(argv, O_RDONLY, 0, 0, function);
Rob Landley2bfaaf22008-07-03 19:19:00 -0500830}
831
Rob Landleybc078652007-12-15 21:47:25 -0600832// Slow, but small.
833
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500834char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600835{
Rob Landley7aa651a2012-11-13 17:14:08 -0600836 char c, *buf = NULL;
837 long len = 0;
Rob Landleybc078652007-12-15 21:47:25 -0600838
Rob Landley7aa651a2012-11-13 17:14:08 -0600839 for (;;) {
840 if (1>read(fd, &c, 1)) break;
841 if (!(len & 63)) buf=xrealloc(buf, len+65);
842 if ((buf[len++]=c) == end) break;
843 }
844 if (buf) buf[len]=0;
845 if (plen) *plen = len;
Rob Landleybc078652007-12-15 21:47:25 -0600846
Rob Landley7aa651a2012-11-13 17:14:08 -0600847 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600848}
849
850char *get_line(int fd)
851{
Rob Landley7aa651a2012-11-13 17:14:08 -0600852 long len;
853 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600854
Rob Landley7aa651a2012-11-13 17:14:08 -0600855 if (buf && buf[--len]=='\n') buf[len]=0;
Rob Landleybc078652007-12-15 21:47:25 -0600856
Rob Landley7aa651a2012-11-13 17:14:08 -0600857 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600858}
859
860// Copy the rest of in to out and close both files.
861
862void xsendfile(int in, int out)
863{
Rob Landley7aa651a2012-11-13 17:14:08 -0600864 long len;
865 char buf[4096];
Rob Landleybc078652007-12-15 21:47:25 -0600866
Rob Landley7aa651a2012-11-13 17:14:08 -0600867 if (in<0) return;
868 for (;;) {
869 len = xread(in, buf, 4096);
870 if (len<1) break;
871 xwrite(out, buf, len);
872 }
Rob Landley42ecbab2007-12-18 02:02:21 -0600873}
874
Rob Landley67a069d2012-06-03 00:32:12 -0500875int wfchmodat(int fd, char *name, mode_t mode)
876{
Rob Landley7aa651a2012-11-13 17:14:08 -0600877 int rc = fchmodat(fd, name, mode, 0);
Rob Landley67a069d2012-06-03 00:32:12 -0500878
Rob Landley7aa651a2012-11-13 17:14:08 -0600879 if (rc) {
880 perror_msg("chmod '%s' to %04o", name, mode);
881 toys.exitval=1;
882 }
883 return rc;
Rob Landley67a069d2012-06-03 00:32:12 -0500884}
885
Rob Landleyc52db602012-07-30 01:01:33 -0500886static char *tempfile2zap;
887static void tempfile_handler(int i)
888{
Rob Landley7aa651a2012-11-13 17:14:08 -0600889 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
890 _exit(1);
Rob Landleyc52db602012-07-30 01:01:33 -0500891}
892
Rob Landley42ecbab2007-12-18 02:02:21 -0600893// Open a temporary file to copy an existing file into.
894int copy_tempfile(int fdin, char *name, char **tempname)
895{
Rob Landley7aa651a2012-11-13 17:14:08 -0600896 struct stat statbuf;
897 int fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600898
Rob Landley7aa651a2012-11-13 17:14:08 -0600899 *tempname = xstrndup(name, strlen(name)+6);
900 strcat(*tempname,"XXXXXX");
901 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
902 if (!tempfile2zap) sigatexit(tempfile_handler);
903 tempfile2zap = *tempname;
Rob Landley42ecbab2007-12-18 02:02:21 -0600904
Rob Landley7aa651a2012-11-13 17:14:08 -0600905 // Set permissions of output file
Rob Landley42ecbab2007-12-18 02:02:21 -0600906
Rob Landley7aa651a2012-11-13 17:14:08 -0600907 fstat(fdin, &statbuf);
908 fchmod(fd, statbuf.st_mode);
Rob Landley42ecbab2007-12-18 02:02:21 -0600909
Rob Landley7aa651a2012-11-13 17:14:08 -0600910 return fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600911}
912
913// Abort the copy and delete the temporary file.
914void delete_tempfile(int fdin, int fdout, char **tempname)
915{
Rob Landley7aa651a2012-11-13 17:14:08 -0600916 close(fdin);
917 close(fdout);
918 unlink(*tempname);
919 tempfile2zap = (char *)1;
920 free(*tempname);
921 *tempname = NULL;
Rob Landley42ecbab2007-12-18 02:02:21 -0600922}
923
924// Copy the rest of the data and replace the original with the copy.
925void replace_tempfile(int fdin, int fdout, char **tempname)
926{
Rob Landley7aa651a2012-11-13 17:14:08 -0600927 char *temp = xstrdup(*tempname);
Rob Landley42ecbab2007-12-18 02:02:21 -0600928
Rob Landley7aa651a2012-11-13 17:14:08 -0600929 temp[strlen(temp)-6]=0;
930 if (fdin != -1) {
931 xsendfile(fdin, fdout);
932 xclose(fdin);
933 }
934 xclose(fdout);
935 rename(*tempname, temp);
936 tempfile2zap = (char *)1;
937 free(*tempname);
938 free(temp);
939 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600940}
Rob Landley7e849c52009-01-03 18:15:18 -0600941
942// Create a 256 entry CRC32 lookup table.
943
Rob Landleyb15b8fa2009-01-05 01:05:43 -0600944void crc_init(unsigned int *crc_table, int little_endian)
Rob Landley7e849c52009-01-03 18:15:18 -0600945{
Rob Landley7aa651a2012-11-13 17:14:08 -0600946 unsigned int i;
Rob Landley7e849c52009-01-03 18:15:18 -0600947
Rob Landley7aa651a2012-11-13 17:14:08 -0600948 // Init the CRC32 table (big endian)
949 for (i=0; i<256; i++) {
950 unsigned int j, c = little_endian ? i : i<<24;
951 for (j=8; j; j--)
952 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
953 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
954 crc_table[i] = c;
955 }
Rob Landley7e849c52009-01-03 18:15:18 -0600956}
Rob Landley26e7b5e2012-02-02 07:27:35 -0600957
958// Quick and dirty query size of terminal, doesn't do ANSI probe fallback.
959// set *x=0 and *y=0 before calling to detect failure to set either, or
960// x=80 y=25 to provide defaults
961
962void terminal_size(unsigned *x, unsigned *y)
963{
Rob Landley7aa651a2012-11-13 17:14:08 -0600964 struct winsize ws;
965 int i;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600966
Rob Landley7aa651a2012-11-13 17:14:08 -0600967 //memset(&ws, 0, sizeof(ws));
968 for (i=0; i<3; i++) {
969 if (ioctl(i, TIOCGWINSZ, &ws)) continue;
970 if (x) *x = ws.ws_col;
971 if (y) *y = ws.ws_row;
972 }
973 if (x) {
974 char *s = getenv("COLUMNS");
Rob Landley26e7b5e2012-02-02 07:27:35 -0600975
Rob Landley7aa651a2012-11-13 17:14:08 -0600976 i = s ? atoi(s) : 0;
977 if (i>0) *x = i;
978 }
979 if (y) {
980 char *s = getenv("ROWS");
Rob Landley26e7b5e2012-02-02 07:27:35 -0600981
Rob Landley7aa651a2012-11-13 17:14:08 -0600982 i = s ? atoi(s) : 0;
983 if (i>0) *y = i;
984 }
Rob Landley26e7b5e2012-02-02 07:27:35 -0600985}
986
Rob Landleyf793d532012-02-27 21:56:49 -0600987int yesno(char *prompt, int def)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600988{
Rob Landley7aa651a2012-11-13 17:14:08 -0600989 char buf;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600990
Rob Landleydb8eb322012-12-08 02:25:32 -0600991 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
992 fflush(stderr);
993 while (fread(&buf, 1, 1, stdin)) {
994 int new;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600995
Rob Landley22791082013-01-31 04:13:07 -0600996 // The letter changes the value, the newline (or space) returns it.
Rob Landleydb8eb322012-12-08 02:25:32 -0600997 if (isspace(buf)) break;
998 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
Rob Landley7aa651a2012-11-13 17:14:08 -0600999 }
Rob Landleyee00a7f2012-03-19 19:19:21 -05001000
Rob Landley7aa651a2012-11-13 17:14:08 -06001001 return def;
Rob Landley26e7b5e2012-02-02 07:27:35 -06001002}
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001003
1004// Execute a callback for each PID that matches a process name from a list.
Elie De Brauwerca4035b2012-12-16 13:43:36 +01001005void for_each_pid_with_name_in(char **names, int (*callback)(pid_t pid, char *name))
Rob Landleyf42e11b2012-02-18 18:09:14 -06001006{
Rob Landley7aa651a2012-11-13 17:14:08 -06001007 DIR *dp;
1008 struct dirent *entry;
1009 char cmd[sizeof(toybuf)], path[64];
1010 char **curname;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001011
Rob Landley7aa651a2012-11-13 17:14:08 -06001012 if (!(dp = opendir("/proc"))) perror_exit("opendir");
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001013
Rob Landley7aa651a2012-11-13 17:14:08 -06001014 while ((entry = readdir(dp))) {
1015 int fd, n;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001016
Rob Landley7aa651a2012-11-13 17:14:08 -06001017 if (!isdigit(*entry->d_name)) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001018
Rob Landley7aa651a2012-11-13 17:14:08 -06001019 if (sizeof(path) <= snprintf(path, sizeof(path), "/proc/%s/cmdline",
1020 entry->d_name)) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001021
Rob Landley7aa651a2012-11-13 17:14:08 -06001022 if (-1 == (fd=open(path, O_RDONLY))) continue;
1023 n = read(fd, cmd, sizeof(cmd));
1024 close(fd);
1025 if (n<1) continue;
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001026
Rob Landley7aa651a2012-11-13 17:14:08 -06001027 for (curname = names; *curname; curname++)
Elie De Brauwer7c6209d2012-12-08 20:10:05 +01001028 if (!strcmp(basename(cmd), *curname))
Elie De Brauwerca4035b2012-12-16 13:43:36 +01001029 if (!callback(atol(entry->d_name), *curname)) goto done;
Rob Landley7aa651a2012-11-13 17:14:08 -06001030 }
Elie De Brauwer7c6209d2012-12-08 20:10:05 +01001031done:
Rob Landley7aa651a2012-11-13 17:14:08 -06001032 closedir(dp);
Rob Landleyff9ee8f2012-02-18 15:12:41 -06001033}
Rob Landley2dd50ad2012-02-26 13:48:00 -06001034
1035struct signame {
Rob Landley7aa651a2012-11-13 17:14:08 -06001036 int num;
1037 char *name;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001038};
1039
1040// Signals required by POSIX 2008:
1041// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
1042
1043#define SIGNIFY(x) {SIG##x, #x}
1044
1045static struct signame signames[] = {
Rob Landley7aa651a2012-11-13 17:14:08 -06001046 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
1047 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
1048 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
1049 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
1050 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
Rob Landleyc52db602012-07-30 01:01:33 -05001051
Rob Landley7aa651a2012-11-13 17:14:08 -06001052 // Start of non-terminal signals
Rob Landleyc52db602012-07-30 01:01:33 -05001053
Rob Landley7aa651a2012-11-13 17:14:08 -06001054 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
1055 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
Rob Landley2dd50ad2012-02-26 13:48:00 -06001056};
1057
1058// not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
1059// obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
1060
Rob Landleyc52db602012-07-30 01:01:33 -05001061// Install the same handler on every signal that defaults to killing the process
1062void sigatexit(void *handler)
1063{
Rob Landley7aa651a2012-11-13 17:14:08 -06001064 int i;
1065 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
Rob Landleyc52db602012-07-30 01:01:33 -05001066}
Rob Landley2dd50ad2012-02-26 13:48:00 -06001067// Convert name to signal number. If name == NULL print names.
1068int sig_to_num(char *pidstr)
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 if (pidstr) {
1073 char *s;
1074 i = strtol(pidstr, &s, 10);
1075 if (!*s) return i;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001076
Rob Landley7aa651a2012-11-13 17:14:08 -06001077 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
1078 }
1079 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
1080 if (!pidstr) xputs(signames[i].name);
1081 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001082
Rob Landley7aa651a2012-11-13 17:14:08 -06001083 return -1;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001084}
1085
1086char *num_to_sig(int sig)
1087{
Rob Landley7aa651a2012-11-13 17:14:08 -06001088 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001089
Rob Landley7aa651a2012-11-13 17:14:08 -06001090 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
1091 if (signames[i].num == sig) return signames[i].name;
1092 return NULL;
Rob Landley2dd50ad2012-02-26 13:48:00 -06001093}
Daniel Walter05744b32012-03-19 19:57:56 -05001094
Rob Landleyc52db602012-07-30 01:01:33 -05001095// premute mode bits based on posix mode strings.
Rob Landleyb6f601e2012-05-16 21:11:43 -05001096mode_t string_to_mode(char *modestr, mode_t mode)
Daniel Walter05744b32012-03-19 19:57:56 -05001097{
Rob Landley7aa651a2012-11-13 17:14:08 -06001098 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu";
1099 char *s, *str = modestr;
Rob Landleycf6bcb22012-03-19 20:56:18 -05001100
Rob Landley7aa651a2012-11-13 17:14:08 -06001101 // Handle octal mode
1102 if (isdigit(*str)) {
1103 mode = strtol(str, &s, 8);
1104 if (*s || (mode & ~(07777))) goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001105
Rob Landley7aa651a2012-11-13 17:14:08 -06001106 return mode;
1107 }
Rob Landleycf6bcb22012-03-19 20:56:18 -05001108
Rob Landley7aa651a2012-11-13 17:14:08 -06001109 // Gaze into the bin of permission...
1110 for (;;) {
1111 int i, j, dowho, dohow, dowhat, amask;
Rob Landleycf6bcb22012-03-19 20:56:18 -05001112
Rob Landley7aa651a2012-11-13 17:14:08 -06001113 dowho = dohow = dowhat = amask = 0;
Daniel Walter05744b32012-03-19 19:57:56 -05001114
Rob Landley7aa651a2012-11-13 17:14:08 -06001115 // Find the who, how, and what stanzas, in that order
1116 while (*str && (s = strchr(whos, *str))) {
1117 dowho |= 1<<(s-whos);
1118 str++;
1119 }
1120 // If who isn't specified, like "a" but honoring umask.
1121 if (!dowho) {
1122 dowho = 8;
1123 umask(amask=umask(0));
1124 }
1125 if (!*str || !(s = strchr(hows, *str))) goto barf;
1126 dohow = *(str++);
Rob Landley67a069d2012-06-03 00:32:12 -05001127
Rob Landley7aa651a2012-11-13 17:14:08 -06001128 if (!dohow) goto barf;
1129 while (*str && (s = strchr(whats, *str))) {
1130 dowhat |= 1<<(s-whats);
1131 str++;
1132 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001133
Rob Landley7aa651a2012-11-13 17:14:08 -06001134 // Convert X to x for directory or if already executable somewhere
1135 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001136
Rob Landley7aa651a2012-11-13 17:14:08 -06001137 // Copy mode from another category?
1138 if (!dowhat && *str && (s = strchr(whys, *str))) {
1139 dowhat = (mode>>(3*(s-whys)))&7;
1140 str++;
1141 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001142
Rob Landley7aa651a2012-11-13 17:14:08 -06001143 // Are we ready to do a thing yet?
1144 if (*str && *(str++) != ',') goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001145
Rob Landley7aa651a2012-11-13 17:14:08 -06001146 // Ok, apply the bits to the mode.
1147 for (i=0; i<4; i++) {
1148 for (j=0; j<3; j++) {
1149 mode_t bit = 0;
1150 int where = 1<<((3*i)+j);
Rob Landley31f49e72012-07-21 22:45:05 -05001151
Rob Landley7aa651a2012-11-13 17:14:08 -06001152 if (amask & where) continue;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001153
Rob Landley7aa651a2012-11-13 17:14:08 -06001154 // Figure out new value at this location
1155 if (i == 3) {
1156 // suid/sticky bit.
1157 if (j) {
1158 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
1159 } else if (dowhat & 16) bit++;
1160 } else {
1161 if (!(dowho&(8|(1<<i)))) continue;
1162 if (dowhat&(1<<j)) bit++;
1163 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001164
Rob Landley7aa651a2012-11-13 17:14:08 -06001165 // When selection active, modify bit
Rob Landleyb6f601e2012-05-16 21:11:43 -05001166
Rob Landley7aa651a2012-11-13 17:14:08 -06001167 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
1168 if (bit && dohow != '-') mode |= where;
1169 }
1170 }
Rob Landleyb6f601e2012-05-16 21:11:43 -05001171
Rob Landley7aa651a2012-11-13 17:14:08 -06001172 if (!*str) break;
1173 }
1174 return mode;
Rob Landleyb6f601e2012-05-16 21:11:43 -05001175barf:
Rob Landley7aa651a2012-11-13 17:14:08 -06001176 error_exit("bad mode '%s'", modestr);
Daniel Walter05744b32012-03-19 19:57:56 -05001177}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001178
Felix Janda5a221e62013-04-22 22:29:43 +02001179// Format a mode for ls and stat
1180void format_mode(char (*buf)[11], mode_t mode)
1181{
1182 char c, d;
1183 int i, bit;
1184
1185 (*buf)[10]=0;
1186 for (i=0; i<9; i++) {
1187 bit = mode & (1<<i);
1188 c = i%3;
1189 if (!c && (mode & (1<<((d=i/3)+9)))) {
1190 c = "tss"[d];
1191 if (!bit) c &= ~0x20;
1192 } else c = bit ? "xwr"[c] : '-';
1193 (*buf)[9-i] = c;
1194 }
1195
1196 if (S_ISDIR(mode)) c = 'd';
1197 else if (S_ISBLK(mode)) c = 'b';
1198 else if (S_ISCHR(mode)) c = 'c';
1199 else if (S_ISLNK(mode)) c = 'l';
1200 else if (S_ISFIFO(mode)) c = 'p';
1201 else if (S_ISSOCK(mode)) c = 's';
1202 else c = '-';
1203 **buf = c;
1204}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001205
1206char* make_human_readable(unsigned long long size, unsigned long unit)
1207{
Rob Landley7aa651a2012-11-13 17:14:08 -06001208 unsigned int frac = 0;
1209 if(unit) {
1210 size = (size/(unit)) + (size%(unit)?1:0);
1211 return xmsprintf("%llu", size);
1212 }
1213 else {
1214 static char units[] = {'\0', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
1215 int index = 0;
1216 while(size >= 1024) {
1217 frac = size%1024;
1218 size /= 1024;
1219 index++;
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001220 }
Rob Landley7aa651a2012-11-13 17:14:08 -06001221 frac = (frac/102) + ((frac%102)?1:0);
1222 if(frac >= 10) {
1223 size += 1;
1224 frac = 0;
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001225 }
Rob Landley7aa651a2012-11-13 17:14:08 -06001226 if(frac) return xmsprintf("%llu.%u%c", size, frac, units[index]);
1227 else return xmsprintf("%llu%c", size, units[index]);
1228 }
1229 return NULL; //not reached
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -05001230}
Rob Landley734b5302012-11-16 12:26:48 -06001231
Jonathan Clairembault939fa742012-11-23 00:06:28 +01001232// strtoul with exit on error
1233unsigned long xstrtoul(const char *nptr, char **endptr, int base)
1234{
1235 unsigned long l;
1236 errno = 0;
1237 l = strtoul(nptr, endptr, base);
1238 if (errno)
1239 perror_exit("xstrtoul");
1240 return l;
1241}
1242
Rob Landley734b5302012-11-16 12:26:48 -06001243/*
1244 * used to get the interger value.
1245 */
1246unsigned long get_int_value(const char *numstr, unsigned lowrange, unsigned highrange)
1247{
1248 unsigned long rvalue = 0;
1249 char *ptr;
1250 if(*numstr == '-' || *numstr == '+' || isspace(*numstr)) perror_exit("invalid number '%s'", numstr);
1251 errno = 0;
1252 rvalue = strtoul(numstr, &ptr, 10);
1253 if(errno || numstr == ptr) perror_exit("invalid number '%s'", numstr);
1254 if(*ptr) perror_exit("invalid number '%s'", numstr);
1255 if(rvalue >= lowrange && rvalue <= highrange) return rvalue;
1256 else {
1257 perror_exit("invalid number '%s'", numstr);
1258 return rvalue; //Not reachable; to avoid waring message.
1259 }
1260}