blob: fa0b777ff988b03d0a98c1e657f89b6fbc3d6765 [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);
158
159 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;
180 strncpy((*list)->str, new, len);
181 (*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;
197 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500198
Rob Landley7aa651a2012-11-13 17:14:08 -0600199 for (;;) {
200 char *next = path ? strchr(path, ':') : NULL;
201 int len = next ? next-path : strlen(path);
202 struct string_list *rnext;
203 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500204
Rob Landley7aa651a2012-11-13 17:14:08 -0600205 rnext = xmalloc(sizeof(void *) + strlen(filename)
206 + (len ? len : strlen(cwd)) + 2);
207 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
208 else {
209 char *res = rnext->str;
210 strncpy(res, path, len);
211 res += len;
212 *(res++) = '/';
213 strcpy(res, filename);
214 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500215
Rob Landley7aa651a2012-11-13 17:14:08 -0600216 // Confirm it's not a directory.
217 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
218 *prlist = rnext;
219 rnext->next = NULL;
220 prlist = &(rnext->next);
221 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500222
Rob Landley7aa651a2012-11-13 17:14:08 -0600223 if (!next) break;
224 path += len;
225 path++;
226 }
227 free(cwd);
landley00f87f12006-10-25 18:38:37 -0400228
Rob Landley7aa651a2012-11-13 17:14:08 -0600229 return rlist;
landley00f87f12006-10-25 18:38:37 -0400230}
landley09ea7ac2006-10-30 01:38:00 -0500231
Rob Landleyf5757162007-02-16 21:08:22 -0500232// atol() with the kilo/mega/giga/tera/peta/exa extensions.
233// (zetta and yotta don't fit in 64 bits.)
Rob Landley5e6dca62012-02-09 06:09:27 -0600234long atolx(char *numstr)
Rob Landleyf5757162007-02-16 21:08:22 -0500235{
Rob Landley7aa651a2012-11-13 17:14:08 -0600236 char *c, *suffixes="bkmgtpe", *end;
237 long val = strtol(numstr, &c, 0);
Rob Landleyf5757162007-02-16 21:08:22 -0500238
Rob Landley7aa651a2012-11-13 17:14:08 -0600239 if (*c) {
240 if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
241 int shift = end-suffixes;
242 if (shift--) val *= 1024L<<(shift*10);
243 } else {
244 while (isspace(*c)) c++;
245 if (*c) error_exit("not integer: %s", numstr);
246 }
247 }
Rob Landleyad63f4b2011-12-12 15:19:52 -0600248
Rob Landley7aa651a2012-11-13 17:14:08 -0600249 return val;
Rob Landleyf5757162007-02-16 21:08:22 -0500250}
251
Rob Landleyb5e74162013-11-28 21:11:34 -0600252long atolx_range(char *numstr, long low, long high)
253{
254 long val = atolx(numstr);
255
256 if (val < low) error_exit("%ld < %ld", val, low);
257 if (val > high) error_exit("%ld > %ld", val, high);
258
259 return val;
260}
261
Rob Landleyeb7ea222012-04-14 22:30:41 -0500262int numlen(long l)
263{
Rob Landley7aa651a2012-11-13 17:14:08 -0600264 int len = 0;
265 while (l) {
266 l /= 10;
267 len++;
268 }
269 return len;
Rob Landleyeb7ea222012-04-14 22:30:41 -0500270}
271
Rob Landley2037b832012-07-15 16:56:20 -0500272int stridx(char *haystack, char needle)
273{
Rob Landley7aa651a2012-11-13 17:14:08 -0600274 char *off;
Rob Landley2037b832012-07-15 16:56:20 -0500275
Rob Landley7aa651a2012-11-13 17:14:08 -0600276 if (!needle) return -1;
277 off = strchr(haystack, needle);
278 if (!off) return -1;
Rob Landley2037b832012-07-15 16:56:20 -0500279
Rob Landley7aa651a2012-11-13 17:14:08 -0600280 return off-haystack;
Rob Landley2037b832012-07-15 16:56:20 -0500281}
282
Rob Landley8115fc12014-06-09 07:12:49 -0500283// If *a starts with b, advance *a past it and return 1, else return 0;
284int strstart(char **a, char *b)
285{
286 int len = strlen(b), i = !strncmp(*a, b, len);
287
288 if (i) *a += len;
289
290 return i;
291}
292
Rob Landley055cfcb2007-01-14 20:20:06 -0500293// Return how long the file at fd is, if there's any way to determine it.
294off_t fdlength(int fd)
295{
Rob Landley035f27a2013-08-08 02:46:45 -0500296 struct stat st;
297 off_t base = 0, range = 1, expand = 1, old;
298
299 if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500300
Rob Landley7aa651a2012-11-13 17:14:08 -0600301 // If the ioctl works for this, return it.
Rob Landley035f27a2013-08-08 02:46:45 -0500302 // TODO: is blocksize still always 512, or do we stat for it?
303 // unsigned int size;
304 // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500305
Rob Landley7aa651a2012-11-13 17:14:08 -0600306 // If not, do a binary search for the last location we can read. (Some
307 // block devices don't do BLKGETSIZE right.) This should probably have
308 // a CONFIG option...
Rob Landley055cfcb2007-01-14 20:20:06 -0500309
Rob Landley035f27a2013-08-08 02:46:45 -0500310 // If not, do a binary search for the last location we can read.
311
Rob Landley7aa651a2012-11-13 17:14:08 -0600312 old = lseek(fd, 0, SEEK_CUR);
313 do {
314 char temp;
Rob Landley035f27a2013-08-08 02:46:45 -0500315 off_t pos = base + range / 2;
Rob Landley055cfcb2007-01-14 20:20:06 -0500316
Rob Landley7aa651a2012-11-13 17:14:08 -0600317 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley035f27a2013-08-08 02:46:45 -0500318 off_t delta = (pos + 1) - base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500319
Rob Landley035f27a2013-08-08 02:46:45 -0500320 base += delta;
321 if (expand) range = (expand <<= 1) - base;
322 else range -= delta;
Rob Landley7aa651a2012-11-13 17:14:08 -0600323 } else {
Rob Landley035f27a2013-08-08 02:46:45 -0500324 expand = 0;
325 range = pos - base;
Rob Landley7aa651a2012-11-13 17:14:08 -0600326 }
Rob Landley035f27a2013-08-08 02:46:45 -0500327 } while (range > 0);
Rob Landley055cfcb2007-01-14 20:20:06 -0500328
Rob Landley7aa651a2012-11-13 17:14:08 -0600329 lseek(fd, old, SEEK_SET);
Rob Landleyf15387d2008-07-18 05:43:44 -0500330
Rob Landley035f27a2013-08-08 02:46:45 -0500331 return base;
Rob Landley055cfcb2007-01-14 20:20:06 -0500332}
333
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500334// Read contents of file as a single nul-terminated string.
335// malloc new one if buf=len=0
Ashwini Sharma26b21882014-05-02 06:24:11 -0500336char *readfile(char *name, char *ibuf, off_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500337{
Rob Landley7aa651a2012-11-13 17:14:08 -0600338 int fd;
Ashwini Sharma26b21882014-05-02 06:24:11 -0500339 char *buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500340
Rob Landley7aa651a2012-11-13 17:14:08 -0600341 fd = open(name, O_RDONLY);
342 if (fd == -1) return 0;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500343
344 if (len<1) {
345 len = fdlength(fd);
346 // proc files don't report a length, so try 1 page minimum.
347 if (len<4096) len = 4096;
348 }
Ashwini Sharma26b21882014-05-02 06:24:11 -0500349 if (!ibuf) buf = xmalloc(len+1);
350 else buf = ibuf;
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500351
352 len = readall(fd, buf, len-1);
353 close(fd);
354 if (len<0) {
Ashwini Sharma26b21882014-05-02 06:24:11 -0500355 if (ibuf != buf) free(buf);
Rob Landley8fdcfdb2013-09-03 17:56:28 -0500356 buf = 0;
357 } else buf[len] = 0;
Rob Landley055cfcb2007-01-14 20:20:06 -0500358
Rob Landley7aa651a2012-11-13 17:14:08 -0600359 return buf;
Rob Landley055cfcb2007-01-14 20:20:06 -0500360}
361
Rob Landleyf0153442013-04-26 02:41:05 -0500362// Sleep for this many thousandths of a second
363void msleep(long miliseconds)
364{
365 struct timespec ts;
366
367 ts.tv_sec = miliseconds/1000;
368 ts.tv_nsec = (miliseconds%1000)*1000000;
369 nanosleep(&ts, &ts);
370}
371
Rob Landley6b283412013-06-01 20:41:35 -0500372int64_t peek(void *ptr, int size)
373{
374 if (size & 8) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500375 volatile int64_t *p = (int64_t *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500376 return *p;
377 } else if (size & 4) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500378 volatile int *p = (int *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500379 return *p;
380 } else if (size & 2) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500381 volatile short *p = (short *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500382 return *p;
383 } else {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500384 volatile char *p = (char *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500385 return *p;
386 }
387}
388
389void poke(void *ptr, uint64_t val, int size)
390{
391 if (size & 8) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500392 volatile uint64_t *p = (uint64_t *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500393 *p = val;
394 } else if (size & 4) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500395 volatile int *p = (int *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500396 *p = val;
397 } else if (size & 2) {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500398 volatile short *p = (short *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500399 *p = val;
400 } else {
Rob Landleya8b88fe2014-03-11 18:11:12 -0500401 volatile char *p = (char *)ptr;
Rob Landley6b283412013-06-01 20:41:35 -0500402 *p = val;
403 }
404}
405
Rob Landley2bfaaf22008-07-03 19:19:00 -0500406// Iterate through an array of files, opening each one and calling a function
407// on that filehandle and name. The special filename "-" means stdin if
408// flags is O_RDONLY, stdout otherwise. An empty argument list calls
409// function() on just stdin/stdout.
410//
411// Note: read only filehandles are automatically closed when function()
412// returns, but writeable filehandles must be close by function()
Rob Landleyad63f4b2011-12-12 15:19:52 -0600413void loopfiles_rw(char **argv, int flags, int permissions, int failok,
Rob Landley7aa651a2012-11-13 17:14:08 -0600414 void (*function)(int fd, char *name))
Rob Landley7634b552007-11-29 17:49:50 -0600415{
Rob Landley7aa651a2012-11-13 17:14:08 -0600416 int fd;
Rob Landley7634b552007-11-29 17:49:50 -0600417
Rob Landley7aa651a2012-11-13 17:14:08 -0600418 // If no arguments, read from stdin.
419 if (!*argv) function(flags ? 1 : 0, "-");
420 else do {
421 // Filename "-" means read from stdin.
422 // Inability to open a file prints a warning, but doesn't exit.
Rob Landley7634b552007-11-29 17:49:50 -0600423
Rob Landley7aa651a2012-11-13 17:14:08 -0600424 if (!strcmp(*argv,"-")) fd=0;
425 else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
426 perror_msg("%s", *argv);
427 toys.exitval = 1;
428 continue;
429 }
430 function(fd, *argv);
431 if (flags == O_RDONLY) close(fd);
432 } while (*++argv);
Rob Landley7634b552007-11-29 17:49:50 -0600433}
Rob Landleybc078652007-12-15 21:47:25 -0600434
Rob Landleyad63f4b2011-12-12 15:19:52 -0600435// Call loopfiles_rw with O_RDONLY and !failok (common case).
Rob Landley2bfaaf22008-07-03 19:19:00 -0500436void loopfiles(char **argv, void (*function)(int fd, char *name))
437{
Rob Landley7aa651a2012-11-13 17:14:08 -0600438 loopfiles_rw(argv, O_RDONLY, 0, 0, function);
Rob Landley2bfaaf22008-07-03 19:19:00 -0500439}
440
Rob Landleybc078652007-12-15 21:47:25 -0600441// Slow, but small.
442
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500443char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600444{
Rob Landley7aa651a2012-11-13 17:14:08 -0600445 char c, *buf = NULL;
446 long len = 0;
Rob Landleybc078652007-12-15 21:47:25 -0600447
Rob Landley7aa651a2012-11-13 17:14:08 -0600448 for (;;) {
449 if (1>read(fd, &c, 1)) break;
450 if (!(len & 63)) buf=xrealloc(buf, len+65);
451 if ((buf[len++]=c) == end) break;
452 }
453 if (buf) buf[len]=0;
454 if (plen) *plen = len;
Rob Landleybc078652007-12-15 21:47:25 -0600455
Rob Landley7aa651a2012-11-13 17:14:08 -0600456 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600457}
458
459char *get_line(int fd)
460{
Rob Landley7aa651a2012-11-13 17:14:08 -0600461 long len;
462 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600463
Rob Landley7aa651a2012-11-13 17:14:08 -0600464 if (buf && buf[--len]=='\n') buf[len]=0;
Rob Landleybc078652007-12-15 21:47:25 -0600465
Rob Landley7aa651a2012-11-13 17:14:08 -0600466 return buf;
Rob Landleybc078652007-12-15 21:47:25 -0600467}
468
Rob Landley67a069d2012-06-03 00:32:12 -0500469int wfchmodat(int fd, char *name, mode_t mode)
470{
Rob Landley7aa651a2012-11-13 17:14:08 -0600471 int rc = fchmodat(fd, name, mode, 0);
Rob Landley67a069d2012-06-03 00:32:12 -0500472
Rob Landley7aa651a2012-11-13 17:14:08 -0600473 if (rc) {
474 perror_msg("chmod '%s' to %04o", name, mode);
475 toys.exitval=1;
476 }
477 return rc;
Rob Landley67a069d2012-06-03 00:32:12 -0500478}
479
Rob Landleyc52db602012-07-30 01:01:33 -0500480static char *tempfile2zap;
481static void tempfile_handler(int i)
482{
Rob Landley7aa651a2012-11-13 17:14:08 -0600483 if (1 < (long)tempfile2zap) unlink(tempfile2zap);
484 _exit(1);
Rob Landleyc52db602012-07-30 01:01:33 -0500485}
486
Rob Landley42ecbab2007-12-18 02:02:21 -0600487// Open a temporary file to copy an existing file into.
488int copy_tempfile(int fdin, char *name, char **tempname)
489{
Rob Landley7aa651a2012-11-13 17:14:08 -0600490 struct stat statbuf;
491 int fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600492
Rob Landley7aa651a2012-11-13 17:14:08 -0600493 *tempname = xstrndup(name, strlen(name)+6);
494 strcat(*tempname,"XXXXXX");
495 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
496 if (!tempfile2zap) sigatexit(tempfile_handler);
497 tempfile2zap = *tempname;
Rob Landley42ecbab2007-12-18 02:02:21 -0600498
Rob Landley7aa651a2012-11-13 17:14:08 -0600499 // Set permissions of output file
Rob Landley42ecbab2007-12-18 02:02:21 -0600500
Rob Landley7aa651a2012-11-13 17:14:08 -0600501 fstat(fdin, &statbuf);
502 fchmod(fd, statbuf.st_mode);
Rob Landley42ecbab2007-12-18 02:02:21 -0600503
Rob Landley7aa651a2012-11-13 17:14:08 -0600504 return fd;
Rob Landley42ecbab2007-12-18 02:02:21 -0600505}
506
507// Abort the copy and delete the temporary file.
508void delete_tempfile(int fdin, int fdout, char **tempname)
509{
Rob Landley7aa651a2012-11-13 17:14:08 -0600510 close(fdin);
511 close(fdout);
512 unlink(*tempname);
513 tempfile2zap = (char *)1;
514 free(*tempname);
515 *tempname = NULL;
Rob Landley42ecbab2007-12-18 02:02:21 -0600516}
517
518// Copy the rest of the data and replace the original with the copy.
519void replace_tempfile(int fdin, int fdout, char **tempname)
520{
Rob Landley7aa651a2012-11-13 17:14:08 -0600521 char *temp = xstrdup(*tempname);
Rob Landley42ecbab2007-12-18 02:02:21 -0600522
Rob Landley7aa651a2012-11-13 17:14:08 -0600523 temp[strlen(temp)-6]=0;
524 if (fdin != -1) {
525 xsendfile(fdin, fdout);
526 xclose(fdin);
527 }
528 xclose(fdout);
529 rename(*tempname, temp);
530 tempfile2zap = (char *)1;
531 free(*tempname);
532 free(temp);
533 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600534}
Rob Landley7e849c52009-01-03 18:15:18 -0600535
536// Create a 256 entry CRC32 lookup table.
537
Rob Landleyb15b8fa2009-01-05 01:05:43 -0600538void crc_init(unsigned int *crc_table, int little_endian)
Rob Landley7e849c52009-01-03 18:15:18 -0600539{
Rob Landley7aa651a2012-11-13 17:14:08 -0600540 unsigned int i;
Rob Landley7e849c52009-01-03 18:15:18 -0600541
Rob Landley7aa651a2012-11-13 17:14:08 -0600542 // Init the CRC32 table (big endian)
543 for (i=0; i<256; i++) {
544 unsigned int j, c = little_endian ? i : i<<24;
545 for (j=8; j; j--)
546 if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
547 else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
548 crc_table[i] = c;
549 }
Rob Landley7e849c52009-01-03 18:15:18 -0600550}
Rob Landley26e7b5e2012-02-02 07:27:35 -0600551
552// Quick and dirty query size of terminal, doesn't do ANSI probe fallback.
Rob Landley10bdaa42013-11-07 09:04:50 -0600553// set x=80 y=25 before calling to provide defaults. Returns 0 if couldn't
554// determine size.
Rob Landley26e7b5e2012-02-02 07:27:35 -0600555
Rob Landley10bdaa42013-11-07 09:04:50 -0600556int terminal_size(unsigned *xx, unsigned *yy)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600557{
Rob Landley7aa651a2012-11-13 17:14:08 -0600558 struct winsize ws;
Rob Landley10bdaa42013-11-07 09:04:50 -0600559 unsigned i, x = 0, y = 0;
Rob Landleyc9cc5302013-10-27 00:02:56 -0500560 char *s;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600561
Rob Landley10bdaa42013-11-07 09:04:50 -0600562 // stdin, stdout, stderr
Rob Landley7aa651a2012-11-13 17:14:08 -0600563 for (i=0; i<3; i++) {
Rob Landleyc9cc5302013-10-27 00:02:56 -0500564 memset(&ws, 0, sizeof(ws));
565 if (!ioctl(i, TIOCGWINSZ, &ws)) {
566 if (ws.ws_col) x = ws.ws_col;
567 if (ws.ws_row) y = ws.ws_row;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600568
Rob Landleyc9cc5302013-10-27 00:02:56 -0500569 break;
570 }
Rob Landley7aa651a2012-11-13 17:14:08 -0600571 }
Rob Landleyc9cc5302013-10-27 00:02:56 -0500572 s = getenv("COLUMNS");
573 if (s) sscanf(s, "%u", &x);
574 s = getenv("ROWS");
575 if (s) sscanf(s, "%u", &y);
Rob Landley26e7b5e2012-02-02 07:27:35 -0600576
Rob Landley10bdaa42013-11-07 09:04:50 -0600577 // Never return 0 for either value, leave it at default instead.
578 if (xx && x) *xx = x;
579 if (yy && y) *yy = y;
580
581 return x || y;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600582}
583
Rob Landleyf793d532012-02-27 21:56:49 -0600584int yesno(char *prompt, int def)
Rob Landley26e7b5e2012-02-02 07:27:35 -0600585{
Rob Landley7aa651a2012-11-13 17:14:08 -0600586 char buf;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600587
Rob Landleydb8eb322012-12-08 02:25:32 -0600588 fprintf(stderr, "%s (%c/%c):", prompt, def ? 'Y' : 'y', def ? 'n' : 'N');
589 fflush(stderr);
590 while (fread(&buf, 1, 1, stdin)) {
591 int new;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600592
Rob Landley22791082013-01-31 04:13:07 -0600593 // The letter changes the value, the newline (or space) returns it.
Rob Landleydb8eb322012-12-08 02:25:32 -0600594 if (isspace(buf)) break;
595 if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
Rob Landley7aa651a2012-11-13 17:14:08 -0600596 }
Rob Landleyee00a7f2012-03-19 19:19:21 -0500597
Rob Landley7aa651a2012-11-13 17:14:08 -0600598 return def;
Rob Landley26e7b5e2012-02-02 07:27:35 -0600599}
Rob Landleyff9ee8f2012-02-18 15:12:41 -0600600
Rob Landley2dd50ad2012-02-26 13:48:00 -0600601struct signame {
Rob Landley7aa651a2012-11-13 17:14:08 -0600602 int num;
603 char *name;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600604};
605
606// Signals required by POSIX 2008:
607// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
608
609#define SIGNIFY(x) {SIG##x, #x}
610
611static struct signame signames[] = {
Rob Landley7aa651a2012-11-13 17:14:08 -0600612 SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
613 SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
614 SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
615 SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
616 SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
Rob Landleyc52db602012-07-30 01:01:33 -0500617
Rob Landley7aa651a2012-11-13 17:14:08 -0600618 // Start of non-terminal signals
Rob Landleyc52db602012-07-30 01:01:33 -0500619
Rob Landley7aa651a2012-11-13 17:14:08 -0600620 SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
621 SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
Rob Landley2dd50ad2012-02-26 13:48:00 -0600622};
623
624// not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
625// obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
626
Rob Landley1bc52242014-05-21 07:24:16 -0500627// Handler that sets toys.signal, and writes to toys.signalfd if set
628void generic_signal(int sig)
629{
630 if (toys.signalfd) {
631 char c = sig;
632
633 writeall(toys.signalfd, &c, 1);
634 }
635 toys.signal = sig;
636}
637
Rob Landleyc52db602012-07-30 01:01:33 -0500638// Install the same handler on every signal that defaults to killing the process
639void sigatexit(void *handler)
640{
Rob Landley7aa651a2012-11-13 17:14:08 -0600641 int i;
642 for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
Rob Landleyc52db602012-07-30 01:01:33 -0500643}
Rob Landley1bc52242014-05-21 07:24:16 -0500644
Rob Landley2dd50ad2012-02-26 13:48:00 -0600645// Convert name to signal number. If name == NULL print names.
646int sig_to_num(char *pidstr)
647{
Rob Landley7aa651a2012-11-13 17:14:08 -0600648 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600649
Rob Landley7aa651a2012-11-13 17:14:08 -0600650 if (pidstr) {
651 char *s;
652 i = strtol(pidstr, &s, 10);
653 if (!*s) return i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600654
Rob Landley7aa651a2012-11-13 17:14:08 -0600655 if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
656 }
657 for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
658 if (!pidstr) xputs(signames[i].name);
659 else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600660
Rob Landley7aa651a2012-11-13 17:14:08 -0600661 return -1;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600662}
663
664char *num_to_sig(int sig)
665{
Rob Landley7aa651a2012-11-13 17:14:08 -0600666 int i;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600667
Rob Landley7aa651a2012-11-13 17:14:08 -0600668 for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
669 if (signames[i].num == sig) return signames[i].name;
670 return NULL;
Rob Landley2dd50ad2012-02-26 13:48:00 -0600671}
Daniel Walter05744b32012-03-19 19:57:56 -0500672
Rob Landleyc52db602012-07-30 01:01:33 -0500673// premute mode bits based on posix mode strings.
Rob Landleyb6f601e2012-05-16 21:11:43 -0500674mode_t string_to_mode(char *modestr, mode_t mode)
Daniel Walter05744b32012-03-19 19:57:56 -0500675{
Rob Landley7aa651a2012-11-13 17:14:08 -0600676 char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu";
677 char *s, *str = modestr;
Rob Landleycf6bcb22012-03-19 20:56:18 -0500678
Rob Landley7aa651a2012-11-13 17:14:08 -0600679 // Handle octal mode
680 if (isdigit(*str)) {
681 mode = strtol(str, &s, 8);
682 if (*s || (mode & ~(07777))) goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500683
Rob Landley7aa651a2012-11-13 17:14:08 -0600684 return mode;
685 }
Rob Landleycf6bcb22012-03-19 20:56:18 -0500686
Rob Landley7aa651a2012-11-13 17:14:08 -0600687 // Gaze into the bin of permission...
688 for (;;) {
689 int i, j, dowho, dohow, dowhat, amask;
Rob Landleycf6bcb22012-03-19 20:56:18 -0500690
Rob Landley7aa651a2012-11-13 17:14:08 -0600691 dowho = dohow = dowhat = amask = 0;
Daniel Walter05744b32012-03-19 19:57:56 -0500692
Rob Landley7aa651a2012-11-13 17:14:08 -0600693 // Find the who, how, and what stanzas, in that order
694 while (*str && (s = strchr(whos, *str))) {
695 dowho |= 1<<(s-whos);
696 str++;
697 }
698 // If who isn't specified, like "a" but honoring umask.
699 if (!dowho) {
700 dowho = 8;
701 umask(amask=umask(0));
702 }
703 if (!*str || !(s = strchr(hows, *str))) goto barf;
704 dohow = *(str++);
Rob Landley67a069d2012-06-03 00:32:12 -0500705
Rob Landley7aa651a2012-11-13 17:14:08 -0600706 if (!dohow) goto barf;
707 while (*str && (s = strchr(whats, *str))) {
708 dowhat |= 1<<(s-whats);
709 str++;
710 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500711
Rob Landley7aa651a2012-11-13 17:14:08 -0600712 // Convert X to x for directory or if already executable somewhere
713 if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500714
Rob Landley7aa651a2012-11-13 17:14:08 -0600715 // Copy mode from another category?
716 if (!dowhat && *str && (s = strchr(whys, *str))) {
717 dowhat = (mode>>(3*(s-whys)))&7;
718 str++;
719 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500720
Rob Landley7aa651a2012-11-13 17:14:08 -0600721 // Are we ready to do a thing yet?
722 if (*str && *(str++) != ',') goto barf;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500723
Rob Landley7aa651a2012-11-13 17:14:08 -0600724 // Ok, apply the bits to the mode.
725 for (i=0; i<4; i++) {
726 for (j=0; j<3; j++) {
727 mode_t bit = 0;
728 int where = 1<<((3*i)+j);
Rob Landley31f49e72012-07-21 22:45:05 -0500729
Rob Landley7aa651a2012-11-13 17:14:08 -0600730 if (amask & where) continue;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500731
Rob Landley7aa651a2012-11-13 17:14:08 -0600732 // Figure out new value at this location
733 if (i == 3) {
734 // suid/sticky bit.
735 if (j) {
736 if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
737 } else if (dowhat & 16) bit++;
738 } else {
739 if (!(dowho&(8|(1<<i)))) continue;
740 if (dowhat&(1<<j)) bit++;
741 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500742
Rob Landley7aa651a2012-11-13 17:14:08 -0600743 // When selection active, modify bit
Rob Landleyb6f601e2012-05-16 21:11:43 -0500744
Rob Landley7aa651a2012-11-13 17:14:08 -0600745 if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
746 if (bit && dohow != '-') mode |= where;
747 }
748 }
Rob Landleyb6f601e2012-05-16 21:11:43 -0500749
Rob Landley7aa651a2012-11-13 17:14:08 -0600750 if (!*str) break;
751 }
752 return mode;
Rob Landleyb6f601e2012-05-16 21:11:43 -0500753barf:
Rob Landley7aa651a2012-11-13 17:14:08 -0600754 error_exit("bad mode '%s'", modestr);
Daniel Walter05744b32012-03-19 19:57:56 -0500755}
Ashwini Kumar1a0eedf2012-08-26 21:17:00 -0500756
Rob Landley5a26a862013-06-02 00:24:24 -0500757// Format access mode into a drwxrwxrwx string
758void mode_to_string(mode_t mode, char *buf)
Felix Janda5a221e62013-04-22 22:29:43 +0200759{
760 char c, d;
761 int i, bit;
762
Rob Landley5a26a862013-06-02 00:24:24 -0500763 buf[10]=0;
Felix Janda5a221e62013-04-22 22:29:43 +0200764 for (i=0; i<9; i++) {
765 bit = mode & (1<<i);
766 c = i%3;
767 if (!c && (mode & (1<<((d=i/3)+9)))) {
768 c = "tss"[d];
769 if (!bit) c &= ~0x20;
770 } else c = bit ? "xwr"[c] : '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500771 buf[9-i] = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200772 }
773
774 if (S_ISDIR(mode)) c = 'd';
775 else if (S_ISBLK(mode)) c = 'b';
776 else if (S_ISCHR(mode)) c = 'c';
777 else if (S_ISLNK(mode)) c = 'l';
778 else if (S_ISFIFO(mode)) c = 'p';
779 else if (S_ISSOCK(mode)) c = 's';
780 else c = '-';
Rob Landley5a26a862013-06-02 00:24:24 -0500781 *buf = c;
Felix Janda5a221e62013-04-22 22:29:43 +0200782}
Rob Landleydb1009d2013-12-19 09:32:30 -0600783
784// Execute a callback for each PID that matches a process name from a list.
785void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
786{
787 DIR *dp;
788 struct dirent *entry;
789
790 if (!(dp = opendir("/proc"))) perror_exit("opendir");
791
792 while ((entry = readdir(dp))) {
793 unsigned u;
794 char *cmd, **curname;
795
796 if (!(u = atoi(entry->d_name))) continue;
797 sprintf(libbuf, "/proc/%u/cmdline", u);
798 if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
799
800 for (curname = names; *curname; curname++)
801 if (**curname == '/' ? !strcmp(cmd, *curname)
802 : !strcmp(basename(cmd), basename(*curname)))
803 if (callback(u, *curname)) break;
804 if (*curname) break;
805 }
806 closedir(dp);
807}
Rob Landley48c172b2014-05-06 06:31:28 -0500808
809// display first few digits of number with power of two units, except we're
810// actually just counting decimal digits and showing mil/bil/trillions.
811int human_readable(char *buf, unsigned long long num)
812{
813 int end, len;
814
815 len = sprintf(buf, "%lld", num);
816 end = ((len-1)%3)+1;
817 len /= 3;
818
819 if (len && end == 1) {
820 buf[2] = buf[1];
821 buf[1] = '.';
822 end = 3;
823 }
824 buf[end++] = ' ';
825 if (len) buf[end++] = " KMGTPE"[len];
826 buf[end++] = 'B';
827 buf[end++] = 0;
828
829 return end;
830}