blob: ea65f77ad0a1d0dead95d5fec0a1c7a0ec7deb82 [file] [log] [blame]
Rob Landleyd3904932013-07-16 00:04:56 -05001/* lib.c - various reusable stuff.
landley09ea7ac2006-10-30 01:38:00 -05002 *
3 * Copyright 2006 Rob Landley <rob@landley.net>
landley4f344e32006-10-05 16:18:03 -04004 */
5
6#include "toys.h"
7
landley09ea7ac2006-10-30 01:38:00 -05008void verror_msg(char *msg, int err, va_list va)
9{
Rob Landley7aa651a2012-11-13 17:14:08 -060010 char *s = ": %s";
Rob Landley12138e42008-01-27 15:26:08 -060011
Rob Landley7aa651a2012-11-13 17:14:08 -060012 fprintf(stderr, "%s: ", toys.which->name);
13 if (msg) vfprintf(stderr, msg, va);
14 else s+=2;
15 if (err) fprintf(stderr, s, strerror(err));
16 putc('\n', stderr);
Rob Landley662a2672013-01-02 02:00:35 -060017 if (!toys.exitval) toys.exitval++;
landley09ea7ac2006-10-30 01:38:00 -050018}
19
20void error_msg(char *msg, ...)
21{
Rob Landley7aa651a2012-11-13 17:14:08 -060022 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050023
Rob Landley7aa651a2012-11-13 17:14:08 -060024 va_start(va, msg);
25 verror_msg(msg, 0, va);
26 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050027}
28
29void perror_msg(char *msg, ...)
30{
Rob Landley7aa651a2012-11-13 17:14:08 -060031 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050032
Rob Landley7aa651a2012-11-13 17:14:08 -060033 va_start(va, msg);
34 verror_msg(msg, errno, va);
35 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050036}
37
landley4f344e32006-10-05 16:18:03 -040038// Die with an error message.
39void error_exit(char *msg, ...)
40{
Rob Landley7aa651a2012-11-13 17:14:08 -060041 va_list va;
landley4f344e32006-10-05 16:18:03 -040042
Rob Landley36ffc5a2013-04-14 21:43:22 -050043 if (CFG_TOYBOX_HELP && toys.exithelp) show_help();
Rob Landleyd06c58d2007-10-11 15:36:36 -050044
Rob Landley7aa651a2012-11-13 17:14:08 -060045 va_start(va, msg);
46 verror_msg(msg, 0, va);
47 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050048
Rob Landley55830302013-06-16 19:59:51 -050049 xexit();
landley09ea7ac2006-10-30 01:38:00 -050050}
51
52// Die with an error message and strerror(errno)
53void perror_exit(char *msg, ...)
54{
Rob Landley7aa651a2012-11-13 17:14:08 -060055 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050056
Rob Landley7aa651a2012-11-13 17:14:08 -060057 va_start(va, msg);
58 verror_msg(msg, errno, va);
59 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050060
Rob Landley55830302013-06-16 19:59:51 -050061 xexit();
landley4f344e32006-10-05 16:18:03 -040062}
63
landley64b2e232006-10-30 10:01:19 -050064// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -050065ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -050066{
Rob Landley7aa651a2012-11-13 17:14:08 -060067 size_t count = 0;
Rob Landley15b23152008-07-18 04:15:59 -050068
Rob Landley7aa651a2012-11-13 17:14:08 -060069 while (count<len) {
Rob Landleydbbd3d62013-12-08 13:26:05 -060070 int i = read(fd, (char *)buf+count, len-count);
Rob Landley7aa651a2012-11-13 17:14:08 -060071 if (!i) break;
72 if (i<0) return i;
73 count += i;
74 }
landley64b2e232006-10-30 10:01:19 -050075
Rob Landley7aa651a2012-11-13 17:14:08 -060076 return count;
landley64b2e232006-10-30 10:01:19 -050077}
78
Rob Landleyf3e452a2007-01-08 02:49:39 -050079// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -050080ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -050081{
Rob Landley7aa651a2012-11-13 17:14:08 -060082 size_t count = 0;
83 while (count<len) {
Rob Landley1fb3ae72014-02-16 11:09:23 -060084 int i = write(fd, count+(char *)buf, len-count);
Rob Landley7aa651a2012-11-13 17:14:08 -060085 if (i<1) return i;
86 count += i;
87 }
Rob Landleyf3e452a2007-01-08 02:49:39 -050088
Rob Landley7aa651a2012-11-13 17:14:08 -060089 return count;
Rob Landleyf3e452a2007-01-08 02:49:39 -050090}
91
Rob Landleybc382be2013-09-16 23:41:51 -050092// skip this many bytes of input. Return 0 for success, >0 means this much
93// left after input skipped.
Rob Landley2037b832012-07-15 16:56:20 -050094off_t lskip(int fd, off_t offset)
95{
Rob Landleybc382be2013-09-16 23:41:51 -050096 off_t cur = lseek(fd, 0, SEEK_CUR);
Rob Landley2037b832012-07-15 16:56:20 -050097
Rob Landleybc382be2013-09-16 23:41:51 -050098 if (cur != -1) {
99 off_t end = lseek(fd, 0, SEEK_END) - cur;
Rob Landley2037b832012-07-15 16:56:20 -0500100
Rob Landleybc382be2013-09-16 23:41:51 -0500101 if (end > 0 && end < offset) return offset - end;
102 end = offset+cur;
103 if (end == lseek(fd, end, SEEK_SET)) return 0;
104 perror_exit("lseek");
Rob Landley7aa651a2012-11-13 17:14:08 -0600105 }
Rob Landleybc382be2013-09-16 23:41:51 -0500106
107 while (offset>0) {
108 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
109
110 or = readall(fd, libbuf, try);
111 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
Rob Landley4dd800c2014-02-28 23:10:03 -0600112 else offset -= or;
Rob Landleybc382be2013-09-16 23:41:51 -0500113 if (or < try) break;
114 }
115
116 return offset;
Rob Landley2037b832012-07-15 16:56:20 -0500117}
118
Rob Landleyca1b60e2014-03-11 20:44:55 -0500119// flags: 1=make last dir (with mode lastmode, otherwise skips last component)
120// 2=make path (already exists is ok)
121// 4=verbose
122// returns 0 = path ok, 1 = error
123int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
124{
125 struct stat buf;
126 char *s;
127
128 // mkdir -p one/two/three is not an error if the path already exists,
129 // but is if "three" is a file. The others we dereference and catch
130 // not-a-directory along the way, but the last one we must explicitly
131 // test for. Might as well do it up front.
132
133 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
134 errno = EEXIST;
135 return 1;
136 }
137
Rob Landley02f5a302014-03-24 06:26:49 -0500138 for (s = dir; ;s++) {
Rob Landleyca1b60e2014-03-11 20:44:55 -0500139 char save = 0;
140 mode_t mode = (0777&~toys.old_umask)|0300;
141
Rob Landley02f5a302014-03-24 06:26:49 -0500142 // find next '/', but don't try to mkdir "" at start of absolute path
143 if (*s == '/' && (flags&2) && s != dir) {
Rob Landleyca1b60e2014-03-11 20:44:55 -0500144 save = *s;
145 *s = 0;
146 } else if (*s) continue;
147
148 // Use the mode from the -m option only for the last directory.
149 if (!save) {
150 if (flags&1) mode = lastmode;
151 else break;
152 }
153
154 if (mkdirat(atfd, dir, mode)) {
155 if (!(flags&2) || errno != EEXIST) return 1;
156 } else if (flags&4)
157 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
Rob Landley2c1cf4a2015-01-18 14:06:14 -0600158
Rob Landleyca1b60e2014-03-11 20:44:55 -0500159 if (!(*s = save)) break;
160 }
161
162 return 0;
163}
164
Rob Landleyfe91e682012-11-22 21:18:09 -0600165// Split a path into linked list of components, tracking head and tail of list.
166// Filters out // entries with no contents.
167struct string_list **splitpath(char *path, struct string_list **list)
landley00f87f12006-10-25 18:38:37 -0400168{
Rob Landleyfe91e682012-11-22 21:18:09 -0600169 char *new = path;
landley00f87f12006-10-25 18:38:37 -0400170
Rob Landleyfe91e682012-11-22 21:18:09 -0600171 *list = 0;
172 do {
173 int len;
landley00f87f12006-10-25 18:38:37 -0400174
Rob Landleyfe91e682012-11-22 21:18:09 -0600175 if (*path && *path != '/') continue;
176 len = path-new;
177 if (len > 0) {
178 *list = xmalloc(sizeof(struct string_list) + len + 1);
179 (*list)->next = 0;
Rob Landley87fbe122014-12-13 11:56:41 -0600180 memcpy((*list)->str, new, len);
Rob Landleyfe91e682012-11-22 21:18:09 -0600181 (*list)->str[len] = 0;
182 list = &(*list)->next;
183 }
184 new = path+1;
185 } while (*path++);
186
187 return list;
188}
189
Rob Landley0a04b3e2006-11-03 00:05:52 -0500190// Find all file in a colon-separated path with access type "type" (generally
191// X_OK or R_OK). Returns a list of absolute paths to each file found, in
192// order.
193
194struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500195{
Rob Landley7aa651a2012-11-13 17:14:08 -0600196 struct string_list *rlist = NULL, **prlist=&rlist;
Rob Landley0aad9e42014-06-24 08:19:24 -0500197 char *cwd;
Rob Landleyfa98d012006-11-02 02:57:27 -0500198
Rob Landley0aad9e42014-06-24 08:19:24 -0500199 if (!path) return 0;
200
201 cwd = xgetcwd();
Rob Landley7aa651a2012-11-13 17:14:08 -0600202 for (;;) {
Rob Landley0aad9e42014-06-24 08:19:24 -0500203 char *next = strchr(path, ':');
Rob Landley7aa651a2012-11-13 17:14:08 -0600204 int len = next ? next-path : strlen(path);
205 struct string_list *rnext;
206 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500207
Rob Landley7aa651a2012-11-13 17:14:08 -0600208 rnext = xmalloc(sizeof(void *) + strlen(filename)
209 + (len ? len : strlen(cwd)) + 2);
210 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
211 else {
212 char *res = rnext->str;
Rob Landley87fbe122014-12-13 11:56:41 -0600213
214 memcpy(res, path, len);
Rob Landley7aa651a2012-11-13 17:14:08 -0600215 res += len;
216 *(res++) = '/';
217 strcpy(res, filename);
218 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500219
Rob Landley7aa651a2012-11-13 17:14:08 -0600220 // Confirm it's not a directory.
221 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
222 *prlist = rnext;
223 rnext->next = NULL;
224 prlist = &(rnext->next);
225 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500226
Rob Landley7aa651a2012-11-13 17:14:08 -0600227 if (!next) break;
228 path += len;
229 path++;
230 }
231 free(cwd);
landley00f87f12006-10-25 18:38:37 -0400232
Rob Landley7aa651a2012-11-13 17:14:08 -0600233 return rlist;
landley00f87f12006-10-25 18:38:37 -0400234}
landley09ea7ac2006-10-30 01:38:00 -0500235
Rob Landley86c747a2015-01-01 16:28:51 -0600236long estrtol(char *str, char **end, int base)
237{
238 errno = 0;
239
240 return strtol(str, end, base);
241}
242
243long xstrtol(char *str, char **end, int base)
244{
245 long l = estrtol(str, end, base);
246
247 if (errno) perror_exit("%s", str);
248
249 return l;
250}
251
Rob Landleyf5757162007-02-16 21:08:22 -0500252// atol() with the kilo/mega/giga/tera/peta/exa extensions.
253// (zetta and yotta don't fit in 64 bits.)
Rob Landley5e6dca62012-02-09 06:09:27 -0600254long atolx(char *numstr)
Rob Landleyf5757162007-02-16 21:08:22 -0500255{
Rob Landley87c06e12014-07-19 20:54:29 -0500256 char *c, *suffixes="cbkmgtpe", *end;
Rob Landley86c747a2015-01-01 16:28:51 -0600257 long val;
Rob Landleyf5757162007-02-16 21:08:22 -0500258
Rob Landley86c747a2015-01-01 16:28:51 -0600259 val = xstrtol(numstr, &c, 0);
Rob Landley7aa651a2012-11-13 17:14:08 -0600260 if (*c) {
261 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
Rob Landley87c06e12014-07-19 20:54:29 -0500262 int shift = end-suffixes-2;
263 if (shift >= 0) val *= 1024L<<(shift*10);
Rob Landley7aa651a2012-11-13 17:14:08 -0600264 } else {
265 while (isspace(*c)) c++;
266 if (*c) error_exit("not integer: %s", numstr);
267 }
268 }
Rob Landleyad63f4b2011-12-12 15:19:52 -0600269
Rob Landley7aa651a2012-11-13 17:14:08 -0600270 return val;
Rob Landleyf5757162007-02-16 21:08:22 -0500271}
272
Rob Landleyb5e74162013-11-28 21:11:34 -0600273long atolx_range(char *numstr, long low, long high)
274{
275 long val = atolx(numstr);
276
277 if (val < low) error_exit("%ld < %ld", val, low);
278 if (val > high) error_exit("%ld > %ld", val, high);
279
280 return val;
281}
282
Rob Landley2037b832012-07-15 16:56:20 -0500283int stridx(char *haystack, char needle)
284{
Rob Landley7aa651a2012-11-13 17:14:08 -0600285 char *off;
Rob Landley2037b832012-07-15 16:56:20 -0500286
Rob Landley7aa651a2012-11-13 17:14:08 -0600287 if (!needle) return -1;
288 off = strchr(haystack, needle);
289 if (!off) return -1;
Rob Landley2037b832012-07-15 16:56:20 -0500290
Rob Landley7aa651a2012-11-13 17:14:08 -0600291 return off-haystack;
Rob Landley2037b832012-07-15 16:56:20 -0500292}
293
Rob Landley5fcc7152014-10-18 17:14:12 -0500294int unescape(char c)
295{
296 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
297 int idx = stridx(from, c);
298
299 return (idx == -1) ? 0 : to[idx];
300}
301
Rob Landley8115fc12014-06-09 07:12:49 -0500302// If *a starts with b, advance *a past it and return 1, else return 0;
303int strstart(char **a, char *b)
304{
305 int len = strlen(b), i = !strncmp(*a, b, len);
306
307 if (i) *a += len;
308
309 return i;
310}
311
Rob Landley055cfcb2007-01-14 20:20:06 -0500312// Return how long the file at fd is, if there's any way to determine it.
313off_t fdlength(int fd)
314{
Rob Landley035f27a2013-08-08 02:46:45 -0500315 struct stat st;
316 off_t base = 0, range = 1, expand = 1, old;
317
318 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500319
Rob Landley7aa651a2012-11-13 17:14:08 -0600320 // If the ioctl works for this, return it.
Rob Landley035f27a2013-08-08 02:46:45 -0500321 // TODO: is blocksize still always 512, or do we stat for it?
322 // unsigned int size;
323 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500324
Rob Landley7aa651a2012-11-13 17:14:08 -0600325 // If not, do a binary search for the last location we can read. (Some
326 // block devices don't do BLKGETSIZE right.) This should probably have
327 // a CONFIG option...
Rob Landley055cfcb2007-01-14 20:20:06 -0500328
Rob Landley035f27a2013-08-08 02:46:45 -0500329 // If not, do a binary search for the last location we can read.
330
Rob Landley7aa651a2012-11-13 17:14:08 -0600331 old = lseek(fd, 0, SEEK_CUR);
332 do {
333 char temp;
Rob Landley035f27a2013-08-08 02:46:45 -0500334 off_t pos = base + range / 2;
Rob Landley055cfcb2007-01-14 20:20:06 -0500335
Rob Landley7aa651a2012-11-13 17:14:08 -0600336 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley035f27a2013-08-08 02:46:45 -0500337 off_t delta = (pos + 1) - base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500338
Rob Landley035f27a2013-08-08 02:46:45 -0500339 base += delta;
340 if (expand) range = (expand <<= 1) - base;
341 else range -= delta;
Rob Landley7aa651a2012-11-13 17:14:08 -0600342 } else {
Rob Landley035f27a2013-08-08 02:46:45 -0500343 expand = 0;
344 range = pos - base;
Rob Landley7aa651a2012-11-13 17:14:08 -0600345 }
Rob Landley035f27a2013-08-08 02:46:45 -0500346 } while (range > 0);
Rob Landley055cfcb2007-01-14 20:20:06 -0500347
Rob Landley7aa651a2012-11-13 17:14:08 -0600348 lseek(fd, old, SEEK_SET);
Rob Landleyf15387d2008-07-18 05:43:44 -0500349
Rob Landley035f27a2013-08-08 02:46:45 -0500350 return base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500351}
352
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500353// Read contents of file as a single nul-terminated string.
354// malloc new one if buf=len=0
Rob Landleye10483f2015-04-03 11:49:31 -0500355char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500356{
Rob Landley7aa651a2012-11-13 17:14:08 -0600357 int fd;
Ashwini Sharma26b21882014-05-02 06:24:11 -0500358 char *buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500359
Rob Landleye10483f2015-04-03 11:49:31 -0500360 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500361 if (len<1) {
362 len = fdlength(fd);
363 // proc files don't report a length, so try 1 page minimum.
364 if (len<4096) len = 4096;
365 }
Ashwini Sharma26b21882014-05-02 06:24:11 -0500366 if (!ibuf) buf = xmalloc(len+1);
367 else buf = ibuf;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500368
369 len = readall(fd, buf, len-1);
370 close(fd);
371 if (len<0) {
Ashwini Sharma26b21882014-05-02 06:24:11 -0500372 if (ibuf != buf) free(buf);
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500373 buf = 0;
374 } else buf[len] = 0;
Rob Landley055cfcb2007-01-14 20:20:06 -0500375
Rob Landley7aa651a2012-11-13 17:14:08 -0600376 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500377}
378
Rob Landleye10483f2015-04-03 11:49:31 -0500379char *readfile(char *name, char *ibuf, off_t len)
380{
381 return readfileat(AT_FDCWD, name, ibuf, len);
382}
383
Rob Landleyf0153442013-04-26 02:41:05 -0500384// Sleep for this many thousandths of a second
385void msleep(long miliseconds)
386{
387 struct timespec ts;
388
389 ts.tv_sec = miliseconds/1000;
390 ts.tv_nsec = (miliseconds%1000)*1000000;
391 nanosleep(&ts, &ts);
392}
393
Rob Landley546b2932014-07-21 19:56:53 -0500394// Inefficient, but deals with unaligned access
395int64_t peek_le(void *ptr, unsigned size)
Rob Landley6b283412013-06-01 20:41:35 -0500396{
Rob Landley546b2932014-07-21 19:56:53 -0500397 int64_t ret = 0;
398 char *c = ptr;
399 int i;
400
401 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
402
403 return ret;
404}
405
406int64_t peek_be(void *ptr, unsigned size)
407{
408 int64_t ret = 0;
409 char *c = ptr;
410
411 while (size--) ret = (ret<<8)|c[size];
412
413 return ret;
414}
415
416int64_t peek(void *ptr, unsigned size)
417{
418 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
Rob Landley6b283412013-06-01 20:41:35 -0500419}
420
421void poke(void *ptr, uint64_t val, int size)
422{
423 if (size & 8) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500424 volatile uint64_t *p = (uint64_t *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500425 *p = val;
426 } else if (size & 4) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500427 volatile int *p = (int *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500428 *p = val;
429 } else if (size & 2) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500430 volatile short *p = (short *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500431 *p = val;
432 } else {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500433 volatile char *p = (char *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500434 *p = val;
435 }
436}
437
Rob Landley2bfaaf22008-07-03 19:19:00 -0500438// Iterate through an array of files, opening each one and calling a function
439// on that filehandle and name. The special filename "-" means stdin if
440// flags is O_RDONLY, stdout otherwise. An empty argument list calls
441// function() on just stdin/stdout.
442//
Rob Landley784eb9c2014-10-14 14:16:34 -0500443// Note: pass O_CLOEXEC to automatically close filehandles when function()
444// returns, otherwise filehandles must be closed by function()
Rob Landleyad63f4b2011-12-12 15:19:52 -0600445void loopfiles_rw(char **argv, int flags, int permissions, int failok,
Rob Landley7aa651a2012-11-13 17:14:08 -0600446 void (*function)(int fd, char *name))
Rob Landley7634b552007-11-29 17:49:50 -0600447{
Rob Landley7aa651a2012-11-13 17:14:08 -0600448 int fd;
Rob Landley7634b552007-11-29 17:49:50 -0600449
Rob Landley7aa651a2012-11-13 17:14:08 -0600450 // If no arguments, read from stdin.
Rob Landley45b38822014-10-27 18:08:59 -0500451 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
Rob Landley7aa651a2012-11-13 17:14:08 -0600452 else do {
453 // Filename "-" means read from stdin.
454 // Inability to open a file prints a warning, but doesn't exit.
Rob Landley7634b552007-11-29 17:49:50 -0600455
Rob Landley45b38822014-10-27 18:08:59 -0500456 if (!strcmp(*argv, "-")) fd=0;
Rob Landley7aa651a2012-11-13 17:14:08 -0600457 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
458 perror_msg("%s", *argv);
459 toys.exitval = 1;
460 continue;
461 }
462 function(fd, *argv);
Rob Landley784eb9c2014-10-14 14:16:34 -0500463 if (flags & O_CLOEXEC) close(fd);
Rob Landley7aa651a2012-11-13 17:14:08 -0600464 } while (*++argv);
Rob Landley7634b552007-11-29 17:49:50 -0600465}
Rob Landleybc078652007-12-15 21:47:25 -0600466
Rob Landley784eb9c2014-10-14 14:16:34 -0500467// Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
Rob Landley2bfaaf22008-07-03 19:19:00 -0500468void loopfiles(char **argv, void (*function)(int fd, char *name))
469{
Rob Landley784eb9c2014-10-14 14:16:34 -0500470 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
Rob Landley2bfaaf22008-07-03 19:19:00 -0500471}
472
Rob Landleybc078652007-12-15 21:47:25 -0600473// Slow, but small.
474
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500475char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600476{
Rob Landley7aa651a2012-11-13 17:14:08 -0600477 char c, *buf = NULL;
478 long len = 0;
Rob Landleybc078652007-12-15 21:47:25 -0600479
Rob Landley7aa651a2012-11-13 17:14:08 -0600480 for (;;) {
481 if (1>read(fd, &c, 1)) break;
482 if (!(len & 63)) buf=xrealloc(buf, len+65);
483 if ((buf[len++]=c) == end) break;
484 }
485 if (buf) buf[len]=0;
486 if (plen) *plen = len;
Rob Landleybc078652007-12-15 21:47:25 -0600487
Rob Landley7aa651a2012-11-13 17:14:08 -0600488 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600489}
490
491char *get_line(int fd)
492{
Rob Landley7aa651a2012-11-13 17:14:08 -0600493 long len;
494 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600495
Rob Landley7aa651a2012-11-13 17:14:08 -0600496 if (buf && buf[--len]=='\n') buf[len]=0;
Rob Landleybc078652007-12-15 21:47:25 -0600497
Rob Landley7aa651a2012-11-13 17:14:08 -0600498 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600499}
500
Rob Landley67a069d2012-06-03 00:32:12 -0500501int wfchmodat(int fd, char *name, mode_t mode)
502{
Rob Landley7aa651a2012-11-13 17:14:08 -0600503 int rc = fchmodat(fd, name, mode, 0);
Rob Landley67a069d2012-06-03 00:32:12 -0500504
Rob Landley7aa651a2012-11-13 17:14:08 -0600505 if (rc) {
506 perror_msg("chmod '%s' to %04o", name, mode);
507 toys.exitval=1;
508 }
509 return rc;
Rob Landley67a069d2012-06-03 00:32:12 -0500510}
511
Rob Landleyc52db602012-07-30 01:01:33 -0500512static char *tempfile2zap;
513static void tempfile_handler(int i)
514{
Rob Landley7aa651a2012-11-13 17:14:08 -0600515 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
516 _exit(1);
Rob Landleyc52db602012-07-30 01:01:33 -0500517}
518
Rob Landley42ecbab2007-12-18 02:02:21 -0600519// Open a temporary file to copy an existing file into.
520int copy_tempfile(int fdin, char *name, char **tempname)
521{
Rob Landley7aa651a2012-11-13 17:14:08 -0600522 struct stat statbuf;
523 int fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600524
Rob Landley9b5000c2014-12-22 17:04:47 -0600525 *tempname = xmprintf("%s%s", name, "XXXXXX");
Rob Landley7aa651a2012-11-13 17:14:08 -0600526 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
527 if (!tempfile2zap) sigatexit(tempfile_handler);
528 tempfile2zap = *tempname;
Rob Landley42ecbab2007-12-18 02:02:21 -0600529
Rob Landley7aa651a2012-11-13 17:14:08 -0600530 // Set permissions of output file
Rob Landley42ecbab2007-12-18 02:02:21 -0600531
Rob Landley7aa651a2012-11-13 17:14:08 -0600532 fstat(fdin, &statbuf);
533 fchmod(fd, statbuf.st_mode);
Rob Landley42ecbab2007-12-18 02:02:21 -0600534
Rob Landley7aa651a2012-11-13 17:14:08 -0600535 return fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600536}
537
538// Abort the copy and delete the temporary file.
539void delete_tempfile(int fdin, int fdout, char **tempname)
540{
Rob Landley7aa651a2012-11-13 17:14:08 -0600541 close(fdin);
542 close(fdout);
543 unlink(*tempname);
544 tempfile2zap = (char *)1;
545 free(*tempname);
546 *tempname = NULL;
Rob Landley42ecbab2007-12-18 02:02:21 -0600547}
548
549// Copy the rest of the data and replace the original with the copy.
550void replace_tempfile(int fdin, int fdout, char **tempname)
551{
Rob Landley7aa651a2012-11-13 17:14:08 -0600552 char *temp = xstrdup(*tempname);
Rob Landley42ecbab2007-12-18 02:02:21 -0600553
Rob Landley7aa651a2012-11-13 17:14:08 -0600554 temp[strlen(temp)-6]=0;
555 if (fdin != -1) {
556 xsendfile(fdin, fdout);
557 xclose(fdin);
558 }
559 xclose(fdout);
560 rename(*tempname, temp);
561 tempfile2zap = (char *)1;
562 free(*tempname);
563 free(temp);
564 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600565}
Rob Landley7e849c52009-01-03 18:15:18 -0600566
567// Create a 256 entry CRC32 lookup table.
568
Rob Landleyb15b8fa2009-01-05 01:05:43 -0600569void crc_init(unsigned int *crc_table, int little_endian)
Rob Landley7e849c52009-01-03 18:15:18 -0600570{
Rob Landley7aa651a2012-11-13 17:14:08 -0600571 unsigned int i;
Rob Landley7e849c52009-01-03 18:15:18 -0600572
Rob Landley7aa651a2012-11-13 17:14:08 -0600573 // Init the CRC32 table (big endian)
574 for (i=0; i<256; i++) {
575 unsigned int j, c = little_endian ? i : i<<24;
576 for (j=8; j; j--)
577 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
578 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
579 crc_table[i] = c;
580 }
Rob Landley7e849c52009-01-03 18:15:18 -0600581}
Rob Landley26e7b5e2012-02-02 07:27:35 -0600582
Rob Landley0517eb72014-12-13 11:58:08 -0600583// Init base64 table
584
585void base64_init(char *p)
586{
587 int i;
588
589 for (i = 'A'; i != ':'; i++) {
590 if (i == 'Z'+1) i = 'a';
591 if (i == 'z'+1) i = '0';
592 *(p++) = i;
593 }
594 *(p++) = '+';
595 *(p++) = '/';
596}
597
Rob Landleyf793d532012-02-27 21:56:49 -0600598int yesno(char *prompt, int def)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600599{
Rob Landley7aa651a2012-11-13 17:14:08 -0600600 char buf;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600601
Rob Landleydb8eb322012-12-08 02:25:32 -0600602 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
603 fflush(stderr);
604 while (fread(&buf, 1, 1, stdin)) {
605 int new;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600606
Rob Landley22791082013-01-31 04:13:07 -0600607 // The letter changes the value, the newline (or space) returns it.
Rob Landleydb8eb322012-12-08 02:25:32 -0600608 if (isspace(buf)) break;
609 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
Rob Landley7aa651a2012-11-13 17:14:08 -0600610 }
Rob Landleyee00a7f2012-03-19 19:19:21 -0500611
Rob Landley7aa651a2012-11-13 17:14:08 -0600612 return def;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600613}
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600614
Rob Landley2dd50ad2012-02-26 13:48:00 -0600615struct signame {
Rob Landley7aa651a2012-11-13 17:14:08 -0600616 int num;
617 char *name;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600618};
619
620// Signals required by POSIX 2008:
621// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
622
623#define SIGNIFY(x) {SIG##x, #x}
624
625static struct signame signames[] = {
Rob Landley7aa651a2012-11-13 17:14:08 -0600626 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
627 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
628 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
629 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
630 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
Rob Landleyc52db602012-07-30 01:01:33 -0500631
Rob Landley7aa651a2012-11-13 17:14:08 -0600632 // Start of non-terminal signals
Rob Landleyc52db602012-07-30 01:01:33 -0500633
Rob Landley7aa651a2012-11-13 17:14:08 -0600634 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
635 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
Rob Landley2dd50ad2012-02-26 13:48:00 -0600636};
637
638// not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
639// obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
640
Rob Landley1bc52242014-05-21 07:24:16 -0500641// Handler that sets toys.signal, and writes to toys.signalfd if set
642void generic_signal(int sig)
643{
644 if (toys.signalfd) {
645 char c = sig;
646
647 writeall(toys.signalfd, &c, 1);
648 }
649 toys.signal = sig;
650}
651
Rob Landleyc52db602012-07-30 01:01:33 -0500652// Install the same handler on every signal that defaults to killing the process
653void sigatexit(void *handler)
654{
Rob Landley7aa651a2012-11-13 17:14:08 -0600655 int i;
656 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
Rob Landleyc52db602012-07-30 01:01:33 -0500657}
Rob Landley1bc52242014-05-21 07:24:16 -0500658
Rob Landley2dd50ad2012-02-26 13:48:00 -0600659// Convert name to signal number. If name == NULL print names.
660int sig_to_num(char *pidstr)
661{
Rob Landley7aa651a2012-11-13 17:14:08 -0600662 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600663
Rob Landley7aa651a2012-11-13 17:14:08 -0600664 if (pidstr) {
665 char *s;
Rob Landley86c747a2015-01-01 16:28:51 -0600666
667 i = estrtol(pidstr, &s, 10);
668 if (!errno && !*s) return i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600669
Rob Landley7aa651a2012-11-13 17:14:08 -0600670 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
671 }
672 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
673 if (!pidstr) xputs(signames[i].name);
674 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600675
Rob Landley7aa651a2012-11-13 17:14:08 -0600676 return -1;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600677}
678
679char *num_to_sig(int sig)
680{
Rob Landley7aa651a2012-11-13 17:14:08 -0600681 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600682
Rob Landley7aa651a2012-11-13 17:14:08 -0600683 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
684 if (signames[i].num == sig) return signames[i].name;
685 return NULL;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600686}
Daniel Walter05744b32012-03-19 19:57:56 -0500687
Rob Landleyc52db602012-07-30 01:01:33 -0500688// premute mode bits based on posix mode strings.
Rob Landleyb6f601e2012-05-16 21:11:43 -0500689mode_t string_to_mode(char *modestr, mode_t mode)
Daniel Walter05744b32012-03-19 19:57:56 -0500690{
Rob Landley3b5b19e2014-08-15 10:50:39 -0500691 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
692 *s, *str = modestr;
693 mode_t extrabits = mode & ~(07777);
Rob Landleycf6bcb22012-03-19 20:56:18 -0500694
Rob Landley7aa651a2012-11-13 17:14:08 -0600695 // Handle octal mode
696 if (isdigit(*str)) {
Rob Landley86c747a2015-01-01 16:28:51 -0600697 mode = estrtol(str, &s, 8);
698 if (errno || *s || (mode & ~(07777))) goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500699
Rob Landley3b5b19e2014-08-15 10:50:39 -0500700 return mode | extrabits;
Rob Landley7aa651a2012-11-13 17:14:08 -0600701 }
Rob Landleycf6bcb22012-03-19 20:56:18 -0500702
Rob Landley7aa651a2012-11-13 17:14:08 -0600703 // Gaze into the bin of permission...
704 for (;;) {
705 int i, j, dowho, dohow, dowhat, amask;
Rob Landleycf6bcb22012-03-19 20:56:18 -0500706
Rob Landley7aa651a2012-11-13 17:14:08 -0600707 dowho = dohow = dowhat = amask = 0;
Daniel Walter05744b32012-03-19 19:57:56 -0500708
Rob Landley7aa651a2012-11-13 17:14:08 -0600709 // Find the who, how, and what stanzas, in that order
710 while (*str && (s = strchr(whos, *str))) {
711 dowho |= 1<<(s-whos);
712 str++;
713 }
714 // If who isn't specified, like "a" but honoring umask.
715 if (!dowho) {
716 dowho = 8;
717 umask(amask=umask(0));
718 }
719 if (!*str || !(s = strchr(hows, *str))) goto barf;
720 dohow = *(str++);
Rob Landley67a069d2012-06-03 00:32:12 -0500721
Rob Landley7aa651a2012-11-13 17:14:08 -0600722 if (!dohow) goto barf;
723 while (*str && (s = strchr(whats, *str))) {
724 dowhat |= 1<<(s-whats);
725 str++;
726 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500727
Rob Landley7aa651a2012-11-13 17:14:08 -0600728 // Convert X to x for directory or if already executable somewhere
729 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500730
Rob Landley7aa651a2012-11-13 17:14:08 -0600731 // Copy mode from another category?
732 if (!dowhat && *str && (s = strchr(whys, *str))) {
733 dowhat = (mode>>(3*(s-whys)))&7;
734 str++;
735 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500736
Rob Landley7aa651a2012-11-13 17:14:08 -0600737 // Are we ready to do a thing yet?
738 if (*str && *(str++) != ',') goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500739
Rob Landley7aa651a2012-11-13 17:14:08 -0600740 // Ok, apply the bits to the mode.
741 for (i=0; i<4; i++) {
742 for (j=0; j<3; j++) {
743 mode_t bit = 0;
744 int where = 1<<((3*i)+j);
Rob Landley31f49e72012-07-21 22:45:05 -0500745
Rob Landley7aa651a2012-11-13 17:14:08 -0600746 if (amask & where) continue;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500747
Rob Landley7aa651a2012-11-13 17:14:08 -0600748 // Figure out new value at this location
749 if (i == 3) {
750 // suid/sticky bit.
751 if (j) {
752 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
753 } else if (dowhat & 16) bit++;
754 } else {
755 if (!(dowho&(8|(1<<i)))) continue;
756 if (dowhat&(1<<j)) bit++;
757 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500758
Rob Landley7aa651a2012-11-13 17:14:08 -0600759 // When selection active, modify bit
Rob Landleyb6f601e2012-05-16 21:11:43 -0500760
Rob Landley7aa651a2012-11-13 17:14:08 -0600761 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
762 if (bit && dohow != '-') mode |= where;
763 }
764 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500765
Rob Landley7aa651a2012-11-13 17:14:08 -0600766 if (!*str) break;
767 }
Rob Landley3b5b19e2014-08-15 10:50:39 -0500768
769 return mode|extrabits;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500770barf:
Rob Landley7aa651a2012-11-13 17:14:08 -0600771 error_exit("bad mode '%s'", modestr);
Daniel Walter05744b32012-03-19 19:57:56 -0500772}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -0500773
Rob Landley5a26a862013-06-02 00:24:24 -0500774// Format access mode into a drwxrwxrwx string
775void mode_to_string(mode_t mode, char *buf)
Felix Janda5a221e62013-04-22 22:29:43 +0200776{
777 char c, d;
778 int i, bit;
779
Rob Landley5a26a862013-06-02 00:24:24 -0500780 buf[10]=0;
Felix Janda5a221e62013-04-22 22:29:43 +0200781 for (i=0; i<9; i++) {
782 bit = mode & (1<<i);
783 c = i%3;
784 if (!c && (mode & (1<<((d=i/3)+9)))) {
785 c = "tss"[d];
786 if (!bit) c &= ~0x20;
787 } else c = bit ? "xwr"[c] : '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500788 buf[9-i] = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200789 }
790
791 if (S_ISDIR(mode)) c = 'd';
792 else if (S_ISBLK(mode)) c = 'b';
793 else if (S_ISCHR(mode)) c = 'c';
794 else if (S_ISLNK(mode)) c = 'l';
795 else if (S_ISFIFO(mode)) c = 'p';
796 else if (S_ISSOCK(mode)) c = 's';
797 else c = '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500798 *buf = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200799}
Rob Landleydb1009d2013-12-19 09:32:30 -0600800
801// Execute a callback for each PID that matches a process name from a list.
802void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
803{
804 DIR *dp;
805 struct dirent *entry;
806
807 if (!(dp = opendir("/proc"))) perror_exit("opendir");
808
809 while ((entry = readdir(dp))) {
810 unsigned u;
811 char *cmd, **curname;
812
813 if (!(u = atoi(entry->d_name))) continue;
814 sprintf(libbuf, "/proc/%u/cmdline", u);
815 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
816
817 for (curname = names; *curname; curname++)
818 if (**curname == '/' ? !strcmp(cmd, *curname)
819 : !strcmp(basename(cmd), basename(*curname)))
820 if (callback(u, *curname)) break;
821 if (*curname) break;
822 }
823 closedir(dp);
824}
Rob Landley48c172b2014-05-06 06:31:28 -0500825
826// display first few digits of number with power of two units, except we're
827// actually just counting decimal digits and showing mil/bil/trillions.
828int human_readable(char *buf, unsigned long long num)
829{
830 int end, len;
831
Rob Landley4b77d542015-03-23 11:49:58 -0500832 len = sprintf(buf, "%lld", num)-1;
833 end = (len%3)+1;
Rob Landley48c172b2014-05-06 06:31:28 -0500834 len /= 3;
835
836 if (len && end == 1) {
837 buf[2] = buf[1];
838 buf[1] = '.';
839 end = 3;
840 }
841 buf[end++] = ' ';
842 if (len) buf[end++] = " KMGTPE"[len];
843 buf[end++] = 'B';
844 buf[end++] = 0;
845
846 return end;
847}
Rob Landley5b493dc2015-04-19 21:50:51 -0500848
849// The qsort man page says you can use alphasort, the posix committee
850// disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
851// So just do our own. (The const is entirely to humor the stupid compiler.)
852int qstrcmp(const void *a, const void *b)
853{
854 return strcmp(*(char **)a, *(char **)b);
855}
Rob Landley2fd86242015-04-27 11:13:19 -0500856
857int xpoll(struct pollfd *fds, int nfds, int timeout)
858{
859 int i;
860
861 for (;;) {
862 if (0>(i = poll(fds, nfds, timeout))) {
863 if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
864 else if (timeout>0) timeout--;
865 } else return i;
866 }
867}