blob: b6277f3bb8223e8d37772c619a5fb841f6ecef1f [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));
Rob Landleye5354ca2015-09-11 16:35:14 -050016 if (msg || err) putc('\n', stderr);
Rob Landley662a2672013-01-02 02:00:35 -060017 if (!toys.exitval) toys.exitval++;
landley09ea7ac2006-10-30 01:38:00 -050018}
19
Rob Landleye5354ca2015-09-11 16:35:14 -050020// These functions don't collapse together because of the va_stuff.
21
landley09ea7ac2006-10-30 01:38:00 -050022void error_msg(char *msg, ...)
23{
Rob Landley7aa651a2012-11-13 17:14:08 -060024 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050025
Rob Landley7aa651a2012-11-13 17:14:08 -060026 va_start(va, msg);
27 verror_msg(msg, 0, va);
28 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050029}
30
31void perror_msg(char *msg, ...)
32{
Rob Landley7aa651a2012-11-13 17:14:08 -060033 va_list va;
landley09ea7ac2006-10-30 01:38:00 -050034
Rob Landley7aa651a2012-11-13 17:14:08 -060035 va_start(va, msg);
36 verror_msg(msg, errno, va);
37 va_end(va);
landley09ea7ac2006-10-30 01:38:00 -050038}
39
landley4f344e32006-10-05 16:18:03 -040040// Die with an error message.
41void error_exit(char *msg, ...)
42{
Rob Landley7aa651a2012-11-13 17:14:08 -060043 va_list va;
landley4f344e32006-10-05 16:18:03 -040044
Rob Landleye5354ca2015-09-11 16:35:14 -050045 va_start(va, msg);
46 verror_msg(msg, 0, va);
47 va_end(va);
48
49 xexit();
50}
51
Rob Landleyd3a435e2016-01-05 22:26:58 -060052// Die with an error message and strerror(errno)
53void perror_exit(char *msg, ...)
54{
55 va_list va;
56
57 va_start(va, msg);
58 verror_msg(msg, errno, va);
59 va_end(va);
60
61 xexit();
62}
63
Rob Landleye5354ca2015-09-11 16:35:14 -050064// Exit with an error message after showing help text.
65void help_exit(char *msg, ...)
66{
67 va_list va;
68
69 if (CFG_TOYBOX_HELP) show_help(stderr);
Rob Landleyd06c58d2007-10-11 15:36:36 -050070
Rob Landley8941e5f2015-09-29 05:32:57 -050071 if (msg) {
72 va_start(va, msg);
73 verror_msg(msg, 0, va);
74 va_end(va);
75 }
landley09ea7ac2006-10-30 01:38:00 -050076
Rob Landley55830302013-06-16 19:59:51 -050077 xexit();
landley09ea7ac2006-10-30 01:38:00 -050078}
79
Rob Landleyd3a435e2016-01-05 22:26:58 -060080// If you want to explicitly disable the printf() behavior (because you're
81// printing user-supplied data, or because android's static checker produces
82// false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
83// -Werror there for policy reasons).
84void error_msg_raw(char *msg)
landley09ea7ac2006-10-30 01:38:00 -050085{
Rob Landleyd3a435e2016-01-05 22:26:58 -060086 error_msg("%s", msg);
87}
landley09ea7ac2006-10-30 01:38:00 -050088
Rob Landleyd3a435e2016-01-05 22:26:58 -060089void perror_msg_raw(char *msg)
90{
91 perror_msg("%s", msg);
92}
landley09ea7ac2006-10-30 01:38:00 -050093
Rob Landleyd3a435e2016-01-05 22:26:58 -060094void error_exit_raw(char *msg)
95{
96 error_exit("%s", msg);
97}
98
99void perror_exit_raw(char *msg)
100{
Elliott Hughese8943582016-01-09 11:47:35 -0800101 perror_exit("%s", msg);
landley4f344e32006-10-05 16:18:03 -0400102}
103
landley64b2e232006-10-30 10:01:19 -0500104// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500105ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500106{
Rob Landley7aa651a2012-11-13 17:14:08 -0600107 size_t count = 0;
Rob Landley15b23152008-07-18 04:15:59 -0500108
Rob Landley7aa651a2012-11-13 17:14:08 -0600109 while (count<len) {
Rob Landleydbbd3d62013-12-08 13:26:05 -0600110 int i = read(fd, (char *)buf+count, len-count);
Rob Landley7aa651a2012-11-13 17:14:08 -0600111 if (!i) break;
112 if (i<0) return i;
113 count += i;
114 }
landley64b2e232006-10-30 10:01:19 -0500115
Rob Landley7aa651a2012-11-13 17:14:08 -0600116 return count;
landley64b2e232006-10-30 10:01:19 -0500117}
118
Rob Landleyf3e452a2007-01-08 02:49:39 -0500119// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500120ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500121{
Rob Landley7aa651a2012-11-13 17:14:08 -0600122 size_t count = 0;
123 while (count<len) {
Rob Landley1fb3ae72014-02-16 11:09:23 -0600124 int i = write(fd, count+(char *)buf, len-count);
Rob Landley7aa651a2012-11-13 17:14:08 -0600125 if (i<1) return i;
126 count += i;
127 }
Rob Landleyf3e452a2007-01-08 02:49:39 -0500128
Rob Landley7aa651a2012-11-13 17:14:08 -0600129 return count;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500130}
131
Rob Landleybc382be2013-09-16 23:41:51 -0500132// skip this many bytes of input. Return 0 for success, >0 means this much
133// left after input skipped.
Rob Landley2037b832012-07-15 16:56:20 -0500134off_t lskip(int fd, off_t offset)
135{
Rob Landleybc382be2013-09-16 23:41:51 -0500136 off_t cur = lseek(fd, 0, SEEK_CUR);
Rob Landley2037b832012-07-15 16:56:20 -0500137
Rob Landleybc382be2013-09-16 23:41:51 -0500138 if (cur != -1) {
139 off_t end = lseek(fd, 0, SEEK_END) - cur;
Rob Landley2037b832012-07-15 16:56:20 -0500140
Rob Landleybc382be2013-09-16 23:41:51 -0500141 if (end > 0 && end < offset) return offset - end;
142 end = offset+cur;
143 if (end == lseek(fd, end, SEEK_SET)) return 0;
144 perror_exit("lseek");
Rob Landley7aa651a2012-11-13 17:14:08 -0600145 }
Rob Landleybc382be2013-09-16 23:41:51 -0500146
147 while (offset>0) {
148 int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
149
150 or = readall(fd, libbuf, try);
151 if (or < 0) perror_exit("lskip to %lld", (long long)offset);
Rob Landley4dd800c2014-02-28 23:10:03 -0600152 else offset -= or;
Rob Landleybc382be2013-09-16 23:41:51 -0500153 if (or < try) break;
154 }
155
156 return offset;
Rob Landley2037b832012-07-15 16:56:20 -0500157}
158
Rob Landleyca1b60e2014-03-11 20:44:55 -0500159// flags: 1=make last dir (with mode lastmode, otherwise skips last component)
160// 2=make path (already exists is ok)
161// 4=verbose
162// returns 0 = path ok, 1 = error
163int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
164{
165 struct stat buf;
166 char *s;
167
168 // mkdir -p one/two/three is not an error if the path already exists,
169 // but is if "three" is a file. The others we dereference and catch
170 // not-a-directory along the way, but the last one we must explicitly
171 // test for. Might as well do it up front.
172
173 if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
174 errno = EEXIST;
175 return 1;
176 }
177
Rob Landley02f5a302014-03-24 06:26:49 -0500178 for (s = dir; ;s++) {
Rob Landleyca1b60e2014-03-11 20:44:55 -0500179 char save = 0;
180 mode_t mode = (0777&~toys.old_umask)|0300;
181
Rob Landley02f5a302014-03-24 06:26:49 -0500182 // find next '/', but don't try to mkdir "" at start of absolute path
183 if (*s == '/' && (flags&2) && s != dir) {
Rob Landleyca1b60e2014-03-11 20:44:55 -0500184 save = *s;
185 *s = 0;
186 } else if (*s) continue;
187
188 // Use the mode from the -m option only for the last directory.
189 if (!save) {
190 if (flags&1) mode = lastmode;
191 else break;
192 }
193
194 if (mkdirat(atfd, dir, mode)) {
195 if (!(flags&2) || errno != EEXIST) return 1;
196 } else if (flags&4)
197 fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
Rob Landley2c1cf4a2015-01-18 14:06:14 -0600198
Rob Landleyca1b60e2014-03-11 20:44:55 -0500199 if (!(*s = save)) break;
200 }
201
202 return 0;
203}
204
Rob Landleyfe91e682012-11-22 21:18:09 -0600205// Split a path into linked list of components, tracking head and tail of list.
206// Filters out // entries with no contents.
207struct string_list **splitpath(char *path, struct string_list **list)
landley00f87f12006-10-25 18:38:37 -0400208{
Rob Landleyfe91e682012-11-22 21:18:09 -0600209 char *new = path;
landley00f87f12006-10-25 18:38:37 -0400210
Rob Landleyfe91e682012-11-22 21:18:09 -0600211 *list = 0;
212 do {
213 int len;
landley00f87f12006-10-25 18:38:37 -0400214
Rob Landleyfe91e682012-11-22 21:18:09 -0600215 if (*path && *path != '/') continue;
216 len = path-new;
217 if (len > 0) {
218 *list = xmalloc(sizeof(struct string_list) + len + 1);
219 (*list)->next = 0;
Rob Landley87fbe122014-12-13 11:56:41 -0600220 memcpy((*list)->str, new, len);
Rob Landleyfe91e682012-11-22 21:18:09 -0600221 (*list)->str[len] = 0;
222 list = &(*list)->next;
223 }
224 new = path+1;
225 } while (*path++);
226
227 return list;
228}
229
Rob Landley0a04b3e2006-11-03 00:05:52 -0500230// Find all file in a colon-separated path with access type "type" (generally
231// X_OK or R_OK). Returns a list of absolute paths to each file found, in
232// order.
233
234struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500235{
Rob Landley7aa651a2012-11-13 17:14:08 -0600236 struct string_list *rlist = NULL, **prlist=&rlist;
Rob Landley0aad9e42014-06-24 08:19:24 -0500237 char *cwd;
Rob Landleyfa98d012006-11-02 02:57:27 -0500238
Rob Landley0aad9e42014-06-24 08:19:24 -0500239 if (!path) return 0;
240
241 cwd = xgetcwd();
Rob Landley7aa651a2012-11-13 17:14:08 -0600242 for (;;) {
Rob Landley0aad9e42014-06-24 08:19:24 -0500243 char *next = strchr(path, ':');
Rob Landley7aa651a2012-11-13 17:14:08 -0600244 int len = next ? next-path : strlen(path);
245 struct string_list *rnext;
246 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500247
Rob Landley7aa651a2012-11-13 17:14:08 -0600248 rnext = xmalloc(sizeof(void *) + strlen(filename)
249 + (len ? len : strlen(cwd)) + 2);
250 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
251 else {
252 char *res = rnext->str;
Rob Landley87fbe122014-12-13 11:56:41 -0600253
254 memcpy(res, path, len);
Rob Landley7aa651a2012-11-13 17:14:08 -0600255 res += len;
256 *(res++) = '/';
257 strcpy(res, filename);
258 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500259
Rob Landley7aa651a2012-11-13 17:14:08 -0600260 // Confirm it's not a directory.
261 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
262 *prlist = rnext;
263 rnext->next = NULL;
264 prlist = &(rnext->next);
265 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500266
Rob Landley7aa651a2012-11-13 17:14:08 -0600267 if (!next) break;
268 path += len;
269 path++;
270 }
271 free(cwd);
landley00f87f12006-10-25 18:38:37 -0400272
Rob Landley7aa651a2012-11-13 17:14:08 -0600273 return rlist;
landley00f87f12006-10-25 18:38:37 -0400274}
landley09ea7ac2006-10-30 01:38:00 -0500275
Rob Landley30454a42016-07-12 14:51:51 -0500276long long estrtol(char *str, char **end, int base)
Rob Landley86c747a2015-01-01 16:28:51 -0600277{
278 errno = 0;
279
Rob Landley30454a42016-07-12 14:51:51 -0500280 return strtoll(str, end, base);
Rob Landley86c747a2015-01-01 16:28:51 -0600281}
282
Rob Landley30454a42016-07-12 14:51:51 -0500283long long xstrtol(char *str, char **end, int base)
Rob Landley86c747a2015-01-01 16:28:51 -0600284{
Rob Landley30454a42016-07-12 14:51:51 -0500285 long long l = estrtol(str, end, base);
Rob Landley86c747a2015-01-01 16:28:51 -0600286
Rob Landleyd3a435e2016-01-05 22:26:58 -0600287 if (errno) perror_exit_raw(str);
Rob Landley86c747a2015-01-01 16:28:51 -0600288
289 return l;
290}
291
Rob Landleyf5757162007-02-16 21:08:22 -0500292// atol() with the kilo/mega/giga/tera/peta/exa extensions.
293// (zetta and yotta don't fit in 64 bits.)
Rob Landley30454a42016-07-12 14:51:51 -0500294long long atolx(char *numstr)
Rob Landleyf5757162007-02-16 21:08:22 -0500295{
Rob Landley30454a42016-07-12 14:51:51 -0500296 char *c = numstr, *suffixes="cbkmgtpe", *end;
297 long long val;
Rob Landleyf5757162007-02-16 21:08:22 -0500298
Rob Landley86c747a2015-01-01 16:28:51 -0600299 val = xstrtol(numstr, &c, 0);
Rob Landley93e044c2016-07-13 13:46:50 -0500300 if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
Rob Landley30454a42016-07-12 14:51:51 -0500301 int shift = end-suffixes-2;
302
303 if (shift >= 0) {
304 if (toupper(*++c)=='d') do val *= 1000; while (shift--);
305 else val *= 1024LL<<(shift*10);
Rob Landley7aa651a2012-11-13 17:14:08 -0600306 }
307 }
Rob Landley30454a42016-07-12 14:51:51 -0500308 while (isspace(*c)) c++;
309 if (c==numstr || *c) error_exit("not integer: %s", numstr);
Rob Landleyad63f4b2011-12-12 15:19:52 -0600310
Rob Landley7aa651a2012-11-13 17:14:08 -0600311 return val;
Rob Landleyf5757162007-02-16 21:08:22 -0500312}
313
Rob Landley30454a42016-07-12 14:51:51 -0500314long long atolx_range(char *numstr, long long low, long long high)
Rob Landleyb5e74162013-11-28 21:11:34 -0600315{
Rob Landley30454a42016-07-12 14:51:51 -0500316 long long val = atolx(numstr);
Rob Landleyb5e74162013-11-28 21:11:34 -0600317
Rob Landley30454a42016-07-12 14:51:51 -0500318 if (val < low) error_exit("%lld < %lld", val, low);
319 if (val > high) error_exit("%lld > %lld", val, high);
Rob Landleyb5e74162013-11-28 21:11:34 -0600320
321 return val;
322}
323
Rob Landley2037b832012-07-15 16:56:20 -0500324int stridx(char *haystack, char needle)
325{
Rob Landley7aa651a2012-11-13 17:14:08 -0600326 char *off;
Rob Landley2037b832012-07-15 16:56:20 -0500327
Rob Landley7aa651a2012-11-13 17:14:08 -0600328 if (!needle) return -1;
329 off = strchr(haystack, needle);
330 if (!off) return -1;
Rob Landley2037b832012-07-15 16:56:20 -0500331
Rob Landley7aa651a2012-11-13 17:14:08 -0600332 return off-haystack;
Rob Landley2037b832012-07-15 16:56:20 -0500333}
334
Rob Landley7cc95a72015-08-01 11:48:59 -0500335char *strlower(char *s)
336{
337 char *try, *new;
338
339 if (!CFG_TOYBOX_I18N) {
340 try = new = xstrdup(s);
341 for (; *s; s++) *(new++) = tolower(*s);
342 } else {
343 // I can't guarantee the string _won't_ expand during reencoding, so...?
344 try = new = xmalloc(strlen(s)*2+1);
345
346 while (*s) {
347 wchar_t c;
348 int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
349
350 if (len < 1) *(new++) = *(s++);
351 else {
352 s += len;
353 // squash title case too
354 c = towlower(c);
355
356 // if we had a valid utf8 sequence, convert it to lower case, and can't
357 // encode back to utf8, something is wrong with your libc. But just
358 // in case somebody finds an exploit...
359 len = wcrtomb(new, c, 0);
360 if (len < 1) error_exit("bad utf8 %x", (int)c);
361 new += len;
362 }
363 }
364 *new = 0;
365 }
366
367 return try;
368}
369
Rob Landley4d3ad672015-12-29 11:52:12 -0600370// strstr but returns pointer after match
371char *strafter(char *haystack, char *needle)
372{
373 char *s = strstr(haystack, needle);
374
375 return s ? s+strlen(needle) : s;
376}
377
Rob Landley45e0acc2015-11-02 01:34:58 -0600378// Remove trailing \n
Elliott Hughes11d60792015-10-31 12:15:25 -0700379char *chomp(char *s)
380{
381 char *p = strrchr(s, '\n');
382
Rob Landley45e0acc2015-11-02 01:34:58 -0600383 if (p && !p[1]) *p = 0;
Elliott Hughes11d60792015-10-31 12:15:25 -0700384 return s;
385}
386
Rob Landley5fcc7152014-10-18 17:14:12 -0500387int unescape(char c)
388{
389 char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
390 int idx = stridx(from, c);
391
392 return (idx == -1) ? 0 : to[idx];
393}
394
Rob Landleyd74b5622017-05-08 23:01:06 -0500395char *strend(char *str, char *suffix)
396{
397 long a = strlen(str), b = strlen(suffix);
398
399 if (a>b && !strcmp(str += a-b, suffix)) return str;
400
401 return 0;
402}
403
Rob Landley8115fc12014-06-09 07:12:49 -0500404// If *a starts with b, advance *a past it and return 1, else return 0;
405int strstart(char **a, char *b)
406{
407 int len = strlen(b), i = !strncmp(*a, b, len);
408
409 if (i) *a += len;
410
411 return i;
412}
413
Rob Landley055cfcb2007-01-14 20:20:06 -0500414// Return how long the file at fd is, if there's any way to determine it.
415off_t fdlength(int fd)
416{
Rob Landley035f27a2013-08-08 02:46:45 -0500417 struct stat st;
418 off_t base = 0, range = 1, expand = 1, old;
419
420 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500421
Rob Landley7aa651a2012-11-13 17:14:08 -0600422 // If the ioctl works for this, return it.
Rob Landley035f27a2013-08-08 02:46:45 -0500423 // TODO: is blocksize still always 512, or do we stat for it?
424 // unsigned int size;
425 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500426
Rob Landley7aa651a2012-11-13 17:14:08 -0600427 // If not, do a binary search for the last location we can read. (Some
428 // block devices don't do BLKGETSIZE right.) This should probably have
429 // a CONFIG option...
Rob Landley055cfcb2007-01-14 20:20:06 -0500430
Rob Landley035f27a2013-08-08 02:46:45 -0500431 // If not, do a binary search for the last location we can read.
432
Rob Landley7aa651a2012-11-13 17:14:08 -0600433 old = lseek(fd, 0, SEEK_CUR);
434 do {
435 char temp;
Rob Landley035f27a2013-08-08 02:46:45 -0500436 off_t pos = base + range / 2;
Rob Landley055cfcb2007-01-14 20:20:06 -0500437
Rob Landley7aa651a2012-11-13 17:14:08 -0600438 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley035f27a2013-08-08 02:46:45 -0500439 off_t delta = (pos + 1) - base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500440
Rob Landley035f27a2013-08-08 02:46:45 -0500441 base += delta;
442 if (expand) range = (expand <<= 1) - base;
443 else range -= delta;
Rob Landley7aa651a2012-11-13 17:14:08 -0600444 } else {
Rob Landley035f27a2013-08-08 02:46:45 -0500445 expand = 0;
446 range = pos - base;
Rob Landley7aa651a2012-11-13 17:14:08 -0600447 }
Rob Landley035f27a2013-08-08 02:46:45 -0500448 } while (range > 0);
Rob Landley055cfcb2007-01-14 20:20:06 -0500449
Rob Landley7aa651a2012-11-13 17:14:08 -0600450 lseek(fd, old, SEEK_SET);
Rob Landleyf15387d2008-07-18 05:43:44 -0500451
Rob Landley035f27a2013-08-08 02:46:45 -0500452 return base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500453}
454
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500455// Read contents of file as a single nul-terminated string.
Rob Landley12a487b2015-11-26 21:16:12 -0600456// measure file size if !len, allocate buffer if !buf
Rob Landley46409d52016-06-15 15:47:01 -0500457// Existing buffers need len in *plen
458// Returns amount of data read in *plen
Rob Landley12a487b2015-11-26 21:16:12 -0600459char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
Rob Landley055cfcb2007-01-14 20:20:06 -0500460{
Rob Landley59781de2016-01-20 16:48:01 -0600461 off_t len, rlen;
Rob Landley7aa651a2012-11-13 17:14:08 -0600462 int fd;
Rob Landley59781de2016-01-20 16:48:01 -0600463 char *buf, *rbuf;
464
465 // Unsafe to probe for size with a supplied buffer, don't ever do that.
466 if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
Rob Landley055cfcb2007-01-14 20:20:06 -0500467
Rob Landleye10483f2015-04-03 11:49:31 -0500468 if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
Rob Landley59781de2016-01-20 16:48:01 -0600469
470 // If we dunno the length, probe it. If we can't probe, start with 1 page.
471 if (!*plen) {
472 if ((len = fdlength(fd))>0) *plen = len;
473 else len = 4096;
474 } else len = *plen-1;
475
Ashwini Sharma26b21882014-05-02 06:24:11 -0500476 if (!ibuf) buf = xmalloc(len+1);
477 else buf = ibuf;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500478
Rob Landley59781de2016-01-20 16:48:01 -0600479 for (rbuf = buf;;) {
480 rlen = readall(fd, rbuf, len);
481 if (*plen || rlen<len) break;
482
483 // If reading unknown size, expand buffer by 1.5 each time we fill it up.
484 rlen += rbuf-buf;
485 buf = xrealloc(buf, len = (rlen*3)/2);
486 rbuf = buf+rlen;
487 len -= rlen;
488 }
Elliott Hughes81f31e42016-02-18 16:24:02 -0800489 *plen = len = rlen+(rbuf-buf);
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500490 close(fd);
Rob Landley59781de2016-01-20 16:48:01 -0600491
492 if (rlen<0) {
Ashwini Sharma26b21882014-05-02 06:24:11 -0500493 if (ibuf != buf) free(buf);
Elliott Hughes81f31e42016-02-18 16:24:02 -0800494 buf = 0;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500495 } else buf[len] = 0;
Rob Landley055cfcb2007-01-14 20:20:06 -0500496
Rob Landley7aa651a2012-11-13 17:14:08 -0600497 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500498}
499
Rob Landleye10483f2015-04-03 11:49:31 -0500500char *readfile(char *name, char *ibuf, off_t len)
501{
Rob Landley12a487b2015-11-26 21:16:12 -0600502 return readfileat(AT_FDCWD, name, ibuf, &len);
Rob Landleye10483f2015-04-03 11:49:31 -0500503}
504
Rob Landleyf0153442013-04-26 02:41:05 -0500505// Sleep for this many thousandths of a second
506void msleep(long miliseconds)
507{
508 struct timespec ts;
509
510 ts.tv_sec = miliseconds/1000;
511 ts.tv_nsec = (miliseconds%1000)*1000000;
512 nanosleep(&ts, &ts);
513}
514
Rob Landleyf86f2f42017-05-21 13:11:42 -0500515// return 1<<x of highest bit set
516int highest_bit(unsigned long l)
517{
518 int i;
519
520 for (i = 0; l; i++) l >>= 1;
521
522 return i-1;
523}
524
Rob Landley546b2932014-07-21 19:56:53 -0500525// Inefficient, but deals with unaligned access
526int64_t peek_le(void *ptr, unsigned size)
Rob Landley6b283412013-06-01 20:41:35 -0500527{
Rob Landley546b2932014-07-21 19:56:53 -0500528 int64_t ret = 0;
529 char *c = ptr;
530 int i;
531
Elliott Hughes9502a772016-02-13 09:50:20 -0800532 for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
Rob Landley546b2932014-07-21 19:56:53 -0500533 return ret;
534}
535
536int64_t peek_be(void *ptr, unsigned size)
537{
538 int64_t ret = 0;
539 char *c = ptr;
Elliott Hughes9502a772016-02-13 09:50:20 -0800540 int i;
Rob Landley546b2932014-07-21 19:56:53 -0500541
Elliott Hughes9502a772016-02-13 09:50:20 -0800542 for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
Rob Landley546b2932014-07-21 19:56:53 -0500543 return ret;
544}
545
546int64_t peek(void *ptr, unsigned size)
547{
548 return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
Rob Landley6b283412013-06-01 20:41:35 -0500549}
550
551void poke(void *ptr, uint64_t val, int size)
552{
553 if (size & 8) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500554 volatile uint64_t *p = (uint64_t *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500555 *p = val;
556 } else if (size & 4) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500557 volatile int *p = (int *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500558 *p = val;
559 } else if (size & 2) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500560 volatile short *p = (short *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500561 *p = val;
562 } else {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500563 volatile char *p = (char *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500564 *p = val;
565 }
566}
567
Rob Landley2bfaaf22008-07-03 19:19:00 -0500568// Iterate through an array of files, opening each one and calling a function
Rob Landleyeed9ed42016-09-05 00:55:24 -0500569// on that filehandle and name. The special filename "-" means stdin if
570// flags is O_RDONLY, stdout otherwise. An empty argument list calls
Rob Landley2bfaaf22008-07-03 19:19:00 -0500571// function() on just stdin/stdout.
572//
Rob Landley784eb9c2014-10-14 14:16:34 -0500573// Note: pass O_CLOEXEC to automatically close filehandles when function()
Rob Landleyeed9ed42016-09-05 00:55:24 -0500574// returns, otherwise filehandles must be closed by function().
575// pass WARN_ONLY to produce warning messages about files it couldn't
576// open/create, and skip them. Otherwise function is called with fd -1.
577void loopfiles_rw(char **argv, int flags, int permissions,
Rob Landley7aa651a2012-11-13 17:14:08 -0600578 void (*function)(int fd, char *name))
Rob Landley7634b552007-11-29 17:49:50 -0600579{
Rob Landleyeed9ed42016-09-05 00:55:24 -0500580 int fd, failok = !(flags&WARN_ONLY);
581
582 flags &= ~WARN_ONLY;
Rob Landley7634b552007-11-29 17:49:50 -0600583
Rob Landley7aa651a2012-11-13 17:14:08 -0600584 // If no arguments, read from stdin.
Rob Landley45b38822014-10-27 18:08:59 -0500585 if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
Rob Landley7aa651a2012-11-13 17:14:08 -0600586 else do {
587 // Filename "-" means read from stdin.
588 // Inability to open a file prints a warning, but doesn't exit.
Rob Landley7634b552007-11-29 17:49:50 -0600589
Rob Landleyeed9ed42016-09-05 00:55:24 -0500590 if (!strcmp(*argv, "-")) fd = 0;
591 else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
Rob Landleyd3a435e2016-01-05 22:26:58 -0600592 perror_msg_raw(*argv);
Elliott Hughes8784d8d2016-01-08 19:13:38 -0600593 continue;
Rob Landley7aa651a2012-11-13 17:14:08 -0600594 }
Elliott Hughes8784d8d2016-01-08 19:13:38 -0600595 function(fd, *argv);
Rob Landleyfff20ab2016-07-15 04:39:35 -0500596 if ((flags & O_CLOEXEC) && fd) close(fd);
Rob Landley7aa651a2012-11-13 17:14:08 -0600597 } while (*++argv);
Rob Landley7634b552007-11-29 17:49:50 -0600598}
Rob Landleybc078652007-12-15 21:47:25 -0600599
Rob Landleyeed9ed42016-09-05 00:55:24 -0500600// Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
Rob Landley2bfaaf22008-07-03 19:19:00 -0500601void loopfiles(char **argv, void (*function)(int fd, char *name))
602{
Rob Landleyeed9ed42016-09-05 00:55:24 -0500603 loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
Rob Landley2bfaaf22008-07-03 19:19:00 -0500604}
605
Rob Landleybc078652007-12-15 21:47:25 -0600606// Slow, but small.
607
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500608char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600609{
Rob Landley7aa651a2012-11-13 17:14:08 -0600610 char c, *buf = NULL;
611 long len = 0;
Rob Landleybc078652007-12-15 21:47:25 -0600612
Rob Landley7aa651a2012-11-13 17:14:08 -0600613 for (;;) {
614 if (1>read(fd, &c, 1)) break;
615 if (!(len & 63)) buf=xrealloc(buf, len+65);
616 if ((buf[len++]=c) == end) break;
617 }
618 if (buf) buf[len]=0;
619 if (plen) *plen = len;
Rob Landleybc078652007-12-15 21:47:25 -0600620
Rob Landley7aa651a2012-11-13 17:14:08 -0600621 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600622}
623
624char *get_line(int fd)
625{
Rob Landley7aa651a2012-11-13 17:14:08 -0600626 long len;
627 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600628
Rob Landley7aa651a2012-11-13 17:14:08 -0600629 if (buf && buf[--len]=='\n') buf[len]=0;
Rob Landleybc078652007-12-15 21:47:25 -0600630
Rob Landley7aa651a2012-11-13 17:14:08 -0600631 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600632}
633
Rob Landley67a069d2012-06-03 00:32:12 -0500634int wfchmodat(int fd, char *name, mode_t mode)
635{
Rob Landley7aa651a2012-11-13 17:14:08 -0600636 int rc = fchmodat(fd, name, mode, 0);
Rob Landley67a069d2012-06-03 00:32:12 -0500637
Rob Landley7aa651a2012-11-13 17:14:08 -0600638 if (rc) {
639 perror_msg("chmod '%s' to %04o", name, mode);
640 toys.exitval=1;
641 }
642 return rc;
Rob Landley67a069d2012-06-03 00:32:12 -0500643}
644
Rob Landleyc52db602012-07-30 01:01:33 -0500645static char *tempfile2zap;
Rob Landley0e055692016-03-29 03:59:20 -0500646static void tempfile_handler(void)
Rob Landleyc52db602012-07-30 01:01:33 -0500647{
Rob Landley7aa651a2012-11-13 17:14:08 -0600648 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
Rob Landleyc52db602012-07-30 01:01:33 -0500649}
650
Rob Landley42ecbab2007-12-18 02:02:21 -0600651// Open a temporary file to copy an existing file into.
652int copy_tempfile(int fdin, char *name, char **tempname)
653{
Rob Landley7aa651a2012-11-13 17:14:08 -0600654 struct stat statbuf;
655 int fd;
Elliott Hughesfd568762017-02-19 09:22:45 -0800656 int ignored __attribute__((__unused__));
Rob Landley42ecbab2007-12-18 02:02:21 -0600657
Rob Landley9b5000c2014-12-22 17:04:47 -0600658 *tempname = xmprintf("%s%s", name, "XXXXXX");
Rob Landley7aa651a2012-11-13 17:14:08 -0600659 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
660 if (!tempfile2zap) sigatexit(tempfile_handler);
661 tempfile2zap = *tempname;
Rob Landley42ecbab2007-12-18 02:02:21 -0600662
Rob Landley3366af72016-09-30 17:35:34 -0500663 // Set permissions of output file (ignoring errors, usually due to nonroot)
Rob Landley42ecbab2007-12-18 02:02:21 -0600664
Rob Landley7aa651a2012-11-13 17:14:08 -0600665 fstat(fdin, &statbuf);
666 fchmod(fd, statbuf.st_mode);
Rob Landley42ecbab2007-12-18 02:02:21 -0600667
Rob Landley4a4b3d62017-02-05 00:51:18 -0600668 // We chmod before chown, which strips the suid bit. Caller has to explicitly
669 // switch it back on if they want to keep suid.
670
Elliott Hughesfd568762017-02-19 09:22:45 -0800671 // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
672 // this but it's _supposed_ to fail when we're not root.
673 ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
Rob Landley3366af72016-09-30 17:35:34 -0500674
Rob Landley7aa651a2012-11-13 17:14:08 -0600675 return fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600676}
677
678// Abort the copy and delete the temporary file.
679void delete_tempfile(int fdin, int fdout, char **tempname)
680{
Rob Landley7aa651a2012-11-13 17:14:08 -0600681 close(fdin);
682 close(fdout);
Rob Landley11d2ff52015-08-08 19:21:42 -0500683 if (*tempname) unlink(*tempname);
Rob Landley7aa651a2012-11-13 17:14:08 -0600684 tempfile2zap = (char *)1;
685 free(*tempname);
686 *tempname = NULL;
Rob Landley42ecbab2007-12-18 02:02:21 -0600687}
688
689// Copy the rest of the data and replace the original with the copy.
690void replace_tempfile(int fdin, int fdout, char **tempname)
691{
Rob Landley7aa651a2012-11-13 17:14:08 -0600692 char *temp = xstrdup(*tempname);
Rob Landley42ecbab2007-12-18 02:02:21 -0600693
Rob Landley7aa651a2012-11-13 17:14:08 -0600694 temp[strlen(temp)-6]=0;
695 if (fdin != -1) {
696 xsendfile(fdin, fdout);
697 xclose(fdin);
698 }
699 xclose(fdout);
700 rename(*tempname, temp);
701 tempfile2zap = (char *)1;
702 free(*tempname);
703 free(temp);
704 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600705}
Rob Landley7e849c52009-01-03 18:15:18 -0600706
707// Create a 256 entry CRC32 lookup table.
708
Rob Landleyb15b8fa2009-01-05 01:05:43 -0600709void crc_init(unsigned int *crc_table, int little_endian)
Rob Landley7e849c52009-01-03 18:15:18 -0600710{
Rob Landley7aa651a2012-11-13 17:14:08 -0600711 unsigned int i;
Rob Landley7e849c52009-01-03 18:15:18 -0600712
Rob Landley7aa651a2012-11-13 17:14:08 -0600713 // Init the CRC32 table (big endian)
714 for (i=0; i<256; i++) {
715 unsigned int j, c = little_endian ? i : i<<24;
716 for (j=8; j; j--)
717 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
718 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
719 crc_table[i] = c;
720 }
Rob Landley7e849c52009-01-03 18:15:18 -0600721}
Rob Landley26e7b5e2012-02-02 07:27:35 -0600722
Rob Landley0517eb72014-12-13 11:58:08 -0600723// Init base64 table
724
725void base64_init(char *p)
726{
727 int i;
728
729 for (i = 'A'; i != ':'; i++) {
730 if (i == 'Z'+1) i = 'a';
731 if (i == 'z'+1) i = '0';
732 *(p++) = i;
733 }
734 *(p++) = '+';
735 *(p++) = '/';
736}
737
Rob Landleyb1353fb2015-09-07 17:12:57 -0500738int yesno(int def)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600739{
Rob Landley7aa651a2012-11-13 17:14:08 -0600740 char buf;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600741
Rob Landleyb1353fb2015-09-07 17:12:57 -0500742 fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
Rob Landleydb8eb322012-12-08 02:25:32 -0600743 fflush(stderr);
744 while (fread(&buf, 1, 1, stdin)) {
745 int new;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600746
Rob Landley22791082013-01-31 04:13:07 -0600747 // The letter changes the value, the newline (or space) returns it.
Rob Landleydb8eb322012-12-08 02:25:32 -0600748 if (isspace(buf)) break;
749 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
Rob Landley7aa651a2012-11-13 17:14:08 -0600750 }
Rob Landleyee00a7f2012-03-19 19:19:21 -0500751
Rob Landley7aa651a2012-11-13 17:14:08 -0600752 return def;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600753}
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600754
Rob Landley2dd50ad2012-02-26 13:48:00 -0600755struct signame {
Rob Landley7aa651a2012-11-13 17:14:08 -0600756 int num;
757 char *name;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600758};
759
760// Signals required by POSIX 2008:
761// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
762
763#define SIGNIFY(x) {SIG##x, #x}
764
765static struct signame signames[] = {
Rob Landley7aa651a2012-11-13 17:14:08 -0600766 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
767 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
768 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
769 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
770 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
Rob Landleyc52db602012-07-30 01:01:33 -0500771
Rob Landley7aa651a2012-11-13 17:14:08 -0600772 // Start of non-terminal signals
Rob Landleyc52db602012-07-30 01:01:33 -0500773
Rob Landley7aa651a2012-11-13 17:14:08 -0600774 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
775 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
Rob Landley2dd50ad2012-02-26 13:48:00 -0600776};
777
778// not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
779// obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
780
Rob Landley1bc52242014-05-21 07:24:16 -0500781// Handler that sets toys.signal, and writes to toys.signalfd if set
782void generic_signal(int sig)
783{
784 if (toys.signalfd) {
785 char c = sig;
786
787 writeall(toys.signalfd, &c, 1);
788 }
789 toys.signal = sig;
790}
791
Rob Landleyeb24df92016-03-13 20:23:41 -0500792void exit_signal(int sig)
793{
Rob Landley0e055692016-03-29 03:59:20 -0500794 if (sig) toys.exitval = sig|128;
Rob Landleyeb24df92016-03-13 20:23:41 -0500795 xexit();
796}
797
798// Install the same handler on every signal that defaults to killing the
Rob Landley0e055692016-03-29 03:59:20 -0500799// process, calling the handler on the way out. Calling multiple times
800// adds the handlers to a list, to be called in order.
Rob Landleyc52db602012-07-30 01:01:33 -0500801void sigatexit(void *handler)
802{
Rob Landleyeb24df92016-03-13 20:23:41 -0500803 struct arg_list *al = xmalloc(sizeof(struct arg_list));
Rob Landley7aa651a2012-11-13 17:14:08 -0600804 int i;
Rob Landleyeb24df92016-03-13 20:23:41 -0500805
806 for (i=0; signames[i].num != SIGCHLD; i++)
807 signal(signames[i].num, exit_signal);
808 al->next = toys.xexit;
809 al->arg = handler;
810 toys.xexit = al;
Rob Landleyc52db602012-07-30 01:01:33 -0500811}
Rob Landley1bc52242014-05-21 07:24:16 -0500812
Rob Landley2dd50ad2012-02-26 13:48:00 -0600813// Convert name to signal number. If name == NULL print names.
814int sig_to_num(char *pidstr)
815{
Rob Landley7aa651a2012-11-13 17:14:08 -0600816 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600817
Rob Landley7aa651a2012-11-13 17:14:08 -0600818 if (pidstr) {
819 char *s;
Rob Landley86c747a2015-01-01 16:28:51 -0600820
821 i = estrtol(pidstr, &s, 10);
822 if (!errno && !*s) return i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600823
Rob Landley7aa651a2012-11-13 17:14:08 -0600824 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
825 }
826 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
827 if (!pidstr) xputs(signames[i].name);
828 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600829
Rob Landley7aa651a2012-11-13 17:14:08 -0600830 return -1;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600831}
832
833char *num_to_sig(int sig)
834{
Rob Landley7aa651a2012-11-13 17:14:08 -0600835 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600836
Rob Landley7aa651a2012-11-13 17:14:08 -0600837 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
838 if (signames[i].num == sig) return signames[i].name;
839 return NULL;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600840}
Daniel Walter05744b32012-03-19 19:57:56 -0500841
Rob Landleyc52db602012-07-30 01:01:33 -0500842// premute mode bits based on posix mode strings.
Rob Landleyb6f601e2012-05-16 21:11:43 -0500843mode_t string_to_mode(char *modestr, mode_t mode)
Daniel Walter05744b32012-03-19 19:57:56 -0500844{
Rob Landley3b5b19e2014-08-15 10:50:39 -0500845 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
846 *s, *str = modestr;
847 mode_t extrabits = mode & ~(07777);
Rob Landleycf6bcb22012-03-19 20:56:18 -0500848
Rob Landley7aa651a2012-11-13 17:14:08 -0600849 // Handle octal mode
850 if (isdigit(*str)) {
Rob Landley86c747a2015-01-01 16:28:51 -0600851 mode = estrtol(str, &s, 8);
852 if (errno || *s || (mode & ~(07777))) goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500853
Rob Landley3b5b19e2014-08-15 10:50:39 -0500854 return mode | extrabits;
Rob Landley7aa651a2012-11-13 17:14:08 -0600855 }
Rob Landleycf6bcb22012-03-19 20:56:18 -0500856
Rob Landley7aa651a2012-11-13 17:14:08 -0600857 // Gaze into the bin of permission...
858 for (;;) {
859 int i, j, dowho, dohow, dowhat, amask;
Rob Landleycf6bcb22012-03-19 20:56:18 -0500860
Rob Landley7aa651a2012-11-13 17:14:08 -0600861 dowho = dohow = dowhat = amask = 0;
Daniel Walter05744b32012-03-19 19:57:56 -0500862
Rob Landley7aa651a2012-11-13 17:14:08 -0600863 // Find the who, how, and what stanzas, in that order
864 while (*str && (s = strchr(whos, *str))) {
865 dowho |= 1<<(s-whos);
866 str++;
867 }
868 // If who isn't specified, like "a" but honoring umask.
869 if (!dowho) {
870 dowho = 8;
871 umask(amask=umask(0));
872 }
873 if (!*str || !(s = strchr(hows, *str))) goto barf;
874 dohow = *(str++);
Rob Landley67a069d2012-06-03 00:32:12 -0500875
Rob Landley7aa651a2012-11-13 17:14:08 -0600876 if (!dohow) goto barf;
877 while (*str && (s = strchr(whats, *str))) {
878 dowhat |= 1<<(s-whats);
879 str++;
880 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500881
Rob Landley7aa651a2012-11-13 17:14:08 -0600882 // Convert X to x for directory or if already executable somewhere
883 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500884
Rob Landley7aa651a2012-11-13 17:14:08 -0600885 // Copy mode from another category?
886 if (!dowhat && *str && (s = strchr(whys, *str))) {
887 dowhat = (mode>>(3*(s-whys)))&7;
888 str++;
889 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500890
Rob Landley7aa651a2012-11-13 17:14:08 -0600891 // Are we ready to do a thing yet?
892 if (*str && *(str++) != ',') goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500893
Rob Landley7aa651a2012-11-13 17:14:08 -0600894 // Ok, apply the bits to the mode.
895 for (i=0; i<4; i++) {
896 for (j=0; j<3; j++) {
897 mode_t bit = 0;
898 int where = 1<<((3*i)+j);
Rob Landley31f49e72012-07-21 22:45:05 -0500899
Rob Landley7aa651a2012-11-13 17:14:08 -0600900 if (amask & where) continue;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500901
Rob Landley7aa651a2012-11-13 17:14:08 -0600902 // Figure out new value at this location
903 if (i == 3) {
904 // suid/sticky bit.
905 if (j) {
906 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
907 } else if (dowhat & 16) bit++;
908 } else {
909 if (!(dowho&(8|(1<<i)))) continue;
910 if (dowhat&(1<<j)) bit++;
911 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500912
Rob Landley7aa651a2012-11-13 17:14:08 -0600913 // When selection active, modify bit
Rob Landleyb6f601e2012-05-16 21:11:43 -0500914
Rob Landley7aa651a2012-11-13 17:14:08 -0600915 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
916 if (bit && dohow != '-') mode |= where;
917 }
918 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500919
Rob Landley7aa651a2012-11-13 17:14:08 -0600920 if (!*str) break;
921 }
Rob Landley3b5b19e2014-08-15 10:50:39 -0500922
923 return mode|extrabits;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500924barf:
Rob Landley7aa651a2012-11-13 17:14:08 -0600925 error_exit("bad mode '%s'", modestr);
Daniel Walter05744b32012-03-19 19:57:56 -0500926}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -0500927
Rob Landley5a26a862013-06-02 00:24:24 -0500928// Format access mode into a drwxrwxrwx string
929void mode_to_string(mode_t mode, char *buf)
Felix Janda5a221e62013-04-22 22:29:43 +0200930{
931 char c, d;
932 int i, bit;
933
Rob Landley5a26a862013-06-02 00:24:24 -0500934 buf[10]=0;
Felix Janda5a221e62013-04-22 22:29:43 +0200935 for (i=0; i<9; i++) {
936 bit = mode & (1<<i);
937 c = i%3;
938 if (!c && (mode & (1<<((d=i/3)+9)))) {
939 c = "tss"[d];
940 if (!bit) c &= ~0x20;
941 } else c = bit ? "xwr"[c] : '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500942 buf[9-i] = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200943 }
944
945 if (S_ISDIR(mode)) c = 'd';
946 else if (S_ISBLK(mode)) c = 'b';
947 else if (S_ISCHR(mode)) c = 'c';
948 else if (S_ISLNK(mode)) c = 'l';
949 else if (S_ISFIFO(mode)) c = 'p';
950 else if (S_ISSOCK(mode)) c = 's';
951 else c = '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500952 *buf = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200953}
Rob Landleydb1009d2013-12-19 09:32:30 -0600954
Rob Landley1c028ca2016-04-08 18:25:59 -0500955// basename() can modify its argument or return a pointer to a constant string
956// This just gives after the last '/' or the whole stirng if no /
957char *getbasename(char *name)
Rob Landley6292beb2015-07-10 14:52:14 -0500958{
959 char *s = strrchr(name, '/');
960
961 if (s) return s+1;
Rob Landley1c028ca2016-04-08 18:25:59 -0500962
Rob Landley6292beb2015-07-10 14:52:14 -0500963 return name;
964}
965
Rob Landleydb1009d2013-12-19 09:32:30 -0600966// Execute a callback for each PID that matches a process name from a list.
967void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
968{
969 DIR *dp;
970 struct dirent *entry;
971
972 if (!(dp = opendir("/proc"))) perror_exit("opendir");
973
974 while ((entry = readdir(dp))) {
975 unsigned u;
976 char *cmd, **curname;
977
978 if (!(u = atoi(entry->d_name))) continue;
979 sprintf(libbuf, "/proc/%u/cmdline", u);
980 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
981
982 for (curname = names; *curname; curname++)
983 if (**curname == '/' ? !strcmp(cmd, *curname)
Rob Landleycb49c302016-04-10 14:35:51 -0500984 : !strcmp(getbasename(cmd), getbasename(*curname)))
Rob Landleydb1009d2013-12-19 09:32:30 -0600985 if (callback(u, *curname)) break;
986 if (*curname) break;
987 }
988 closedir(dp);
989}
Rob Landley48c172b2014-05-06 06:31:28 -0500990
Rob Landleyd06ea372015-09-03 20:36:44 -0500991// display first few digits of number with power of two units
Elliott Hughes0fb46512015-08-08 21:10:44 -0500992int human_readable(char *buf, unsigned long long num, int style)
Rob Landley48c172b2014-05-06 06:31:28 -0500993{
Rob Landleyd06ea372015-09-03 20:36:44 -0500994 unsigned long long snap = 0;
Rob Landley960100a2015-09-06 20:10:04 -0500995 int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
Rob Landley48c172b2014-05-06 06:31:28 -0500996
Rob Landleyd06ea372015-09-03 20:36:44 -0500997 // Divide rounding up until we have 3 or fewer digits. Since the part we
998 // print is decimal, the test is 999 even when we divide by 1024.
999 // We can't run out of units because 2<<64 is 18 exabytes.
1000 // test 5675 is 5.5k not 5.6k.
1001 for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
1002 len = sprintf(buf, "%llu", num);
1003 if (unit && len == 1) {
Rob Landley960100a2015-09-06 20:10:04 -05001004 // Redo rounding for 1.2M case, this works with and without HR_1000.
Rob Landleyd06ea372015-09-03 20:36:44 -05001005 num = snap/divisor;
1006 snap -= num*divisor;
1007 snap = ((snap*100)+50)/divisor;
1008 snap /= 10;
1009 len = sprintf(buf, "%llu.%llu", num, snap);
Rob Landley48c172b2014-05-06 06:31:28 -05001010 }
Rob Landleyd06ea372015-09-03 20:36:44 -05001011 if (style & HR_SPACE) buf[len++] = ' ';
1012 if (unit) {
1013 unit = " kMGTPE"[unit];
Rob Landley48c172b2014-05-06 06:31:28 -05001014
Rob Landley960100a2015-09-06 20:10:04 -05001015 if (!(style&HR_1000)) unit = toupper(unit);
Rob Landleyd06ea372015-09-03 20:36:44 -05001016 buf[len++] = unit;
Rob Landley960100a2015-09-06 20:10:04 -05001017 } else if (style & HR_B) buf[len++] = 'B';
Rob Landleyd06ea372015-09-03 20:36:44 -05001018 buf[len] = 0;
1019
1020 return len;
Rob Landley48c172b2014-05-06 06:31:28 -05001021}
Rob Landley5b493dc2015-04-19 21:50:51 -05001022
1023// The qsort man page says you can use alphasort, the posix committee
1024// disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1025// So just do our own. (The const is entirely to humor the stupid compiler.)
1026int qstrcmp(const void *a, const void *b)
1027{
1028 return strcmp(*(char **)a, *(char **)b);
1029}
Rob Landley2fd86242015-04-27 11:13:19 -05001030
Rob Landley54939162016-01-16 16:59:47 -06001031// According to http://www.opengroup.org/onlinepubs/9629399/apdxa.htm
1032// we should generate a uuid structure by reading a clock with 100 nanosecond
1033// precision, normalizing it to the start of the gregorian calendar in 1582,
1034// and looking up our eth0 mac address.
1035//
1036// On the other hand, we have 128 bits to come up with a unique identifier, of
1037// which 6 have a defined value. /dev/urandom it is.
Rob Landley2fd86242015-04-27 11:13:19 -05001038
Rob Landley54939162016-01-16 16:59:47 -06001039void create_uuid(char *uuid)
1040{
1041 // Read 128 random bits
Rob Landley027a73a2016-08-04 10:16:59 -05001042 int fd = xopenro("/dev/urandom");
Rob Landley54939162016-01-16 16:59:47 -06001043 xreadall(fd, uuid, 16);
1044 close(fd);
1045
1046 // Claim to be a DCE format UUID.
1047 uuid[6] = (uuid[6] & 0x0F) | 0x40;
1048 uuid[8] = (uuid[8] & 0x3F) | 0x80;
1049
1050 // rfc2518 section 6.4.1 suggests if we're not using a macaddr, we should
1051 // set bit 1 of the node ID, which is the mac multicast bit. This means we
1052 // should never collide with anybody actually using a macaddr.
1053 uuid[11] |= 128;
Rob Landley2fd86242015-04-27 11:13:19 -05001054}
Rob Landleyba868642016-01-17 17:16:03 -06001055
1056char *show_uuid(char *uuid)
1057{
1058 char *out = libbuf;
1059 int i;
1060
1061 for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1062 *out = 0;
1063
1064 return libbuf;
1065}
Rob Landleycf0f0372016-01-22 21:35:48 -06001066
1067// Returns pointer to letter at end, 0 if none. *start = initial %
1068char *next_printf(char *s, char **start)
1069{
1070 for (; *s; s++) {
1071 if (*s != '%') continue;
1072 if (*++s == '%') continue;
1073 if (start) *start = s-1;
1074 while (0 <= stridx("0'#-+ ", *s)) s++;
1075 while (isdigit(*s)) s++;
1076 if (*s == '.') s++;
1077 while (isdigit(*s)) s++;
1078
1079 return s;
1080 }
1081
1082 return 0;
1083}
Rob Landleyf435f042016-02-10 21:05:22 -06001084
1085// Posix inexplicably hasn't got this, so find str in line.
1086char *strnstr(char *line, char *str)
1087{
1088 long len = strlen(str);
1089 char *s;
1090
1091 for (s = line; *s; s++) if (!strncasecmp(s, str, len)) break;
1092
1093 return *s ? s : 0;
1094}
Rob Landley7ca5dc42016-03-02 11:52:38 -06001095
1096int dev_minor(int dev)
1097{
1098 return ((dev&0xfff00000)>>12)|(dev&0xff);
1099}
1100
1101int dev_major(int dev)
1102{
1103 return (dev&0xfff00)>>8;
1104}
1105
1106int dev_makedev(int major, int minor)
1107{
1108 return (minor&0xff)|((major&0xfff)<<8)|((minor&0xfff00)<<12);
1109}
Rob Landley6d50d4c2016-05-17 12:10:07 -05001110
1111// Return cached passwd entries.
1112struct passwd *bufgetpwuid(uid_t uid)
1113{
1114 struct pwuidbuf_list {
1115 struct pwuidbuf_list *next;
1116 struct passwd pw;
1117 } *list;
1118 struct passwd *temp;
1119 static struct pwuidbuf_list *pwuidbuf;
1120
1121 for (list = pwuidbuf; list; list = list->next)
1122 if (list->pw.pw_uid == uid) return &(list->pw);
1123
1124 list = xmalloc(512);
1125 list->next = pwuidbuf;
1126
1127 errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1128 512-sizeof(*list), &temp);
1129 if (!temp) {
1130 free(list);
1131
1132 return 0;
1133 }
1134 pwuidbuf = list;
1135
1136 return &list->pw;
1137}
Rob Landleyb602f1c2016-05-20 14:28:13 -05001138
1139// Return cached passwd entries.
1140struct group *bufgetgrgid(gid_t gid)
1141{
1142 struct grgidbuf_list {
1143 struct grgidbuf_list *next;
1144 struct group gr;
1145 } *list;
1146 struct group *temp;
1147 static struct grgidbuf_list *grgidbuf;
1148
1149 for (list = grgidbuf; list; list = list->next)
1150 if (list->gr.gr_gid == gid) return &(list->gr);
1151
1152 list = xmalloc(512);
1153 list->next = grgidbuf;
1154
1155 errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1156 512-sizeof(*list), &temp);
1157 if (!temp) {
1158 free(list);
1159
1160 return 0;
1161 }
1162 grgidbuf = list;
1163
1164 return &list->gr;
1165}
Rob Landley46409d52016-06-15 15:47:01 -05001166
1167// Always null terminates, returns 0 for failure, len for success
1168int readlinkat0(int dirfd, char *path, char *buf, int len)
1169{
1170 if (!len) return 0;
1171
1172 len = readlinkat(dirfd, path, buf, len-1);
1173 if (len<1) return 0;
1174 buf[len] = 0;
1175
1176 return len;
1177}
1178
1179int readlink0(char *path, char *buf, int len)
1180{
1181 return readlinkat0(AT_FDCWD, path, buf, len);
1182}
Rob Landleyf20b10e2016-07-26 13:35:56 -05001183
1184// Do regex matching handling embedded NUL bytes in string (hence extra len
1185// argument). Note that neither the pattern nor the match can currently include
1186// NUL bytes (even with wildcards) and string must be null terminated at
1187// string[len]. But this can find a match after the first NUL.
1188int regexec0(regex_t *preg, char *string, long len, int nmatch,
1189 regmatch_t pmatch[], int eflags)
1190{
1191 char *s = string;
1192
1193 for (;;) {
1194 long ll = 0;
1195 int rc;
1196
1197 while (len && !*s) {
1198 s++;
1199 len--;
1200 }
1201 while (s[ll] && ll<len) ll++;
1202
1203 rc = regexec(preg, s, nmatch, pmatch, eflags);
1204 if (!rc) {
1205 for (rc = 0; rc<nmatch && pmatch[rc].rm_so!=-1; rc++) {
1206 pmatch[rc].rm_so += s-string;
1207 pmatch[rc].rm_eo += s-string;
1208 }
1209
1210 return 0;
1211 }
1212 if (ll==len) return rc;
1213
1214 s += ll;
1215 len -= ll;
1216 }
1217}
Rob Landleybc1ccac2016-08-13 15:19:29 -05001218
1219// Return user name or string representation of number, returned buffer
1220// lasts until next call.
1221char *getusername(uid_t uid)
1222{
1223 struct passwd *pw = bufgetpwuid(uid);
1224 static char unum[12];
1225
1226 sprintf(unum, "%u", (unsigned)uid);
1227 return pw ? pw->pw_name : unum;
1228}
1229
1230// Return group name or string representation of number, returned buffer
1231// lasts until next call.
1232char *getgroupname(gid_t gid)
1233{
1234 struct group *gr = bufgetgrgid(gid);
1235 static char gnum[12];
1236
1237 sprintf(gnum, "%u", (unsigned)gid);
1238 return gr ? gr->gr_name : gnum;
1239}
1240
Rob Landley7528a962016-09-03 15:41:55 -05001241// Iterate over lines in file, calling function. Function can write 0 to
1242// the line pointer if they want to keep it, or 1 to terminate processing,
1243// otherwise line is freed. Passed file descriptor is closed at the end.
1244void do_lines(int fd, void (*call)(char **pline, long len))
1245{
1246 FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1247
1248 for (;;) {
1249 char *line = 0;
1250 ssize_t len;
1251
1252 len = getline(&line, (void *)&len, fp);
1253 if (len > 0) {
1254 call(&line, len);
1255 if (line == (void *)1) break;
1256 free(line);
1257 } else break;
1258 }
1259
1260 if (fd) fclose(fp);
1261}