blob: 1f37eb59a9c3de2977e06ec6725d6ce4dc2a941c [file] [log] [blame]
landleycd9dfc32006-10-18 18:38:16 -04001/* vi: set sw=4 ts=4 :*/
landley4f344e32006-10-05 16:18:03 -04002/* functions.c - reusable stuff.
3 *
landleycd9dfc32006-10-18 18:38:16 -04004 * Functions with the x prefix are wrappers for library functions. They either
5 * succeed or kill the program with an error message, but never return failure.
6 * They usually have the same arguments and return value as the function they
7 * wrap.
landley09ea7ac2006-10-30 01:38:00 -05008 *
9 * Copyright 2006 Rob Landley <rob@landley.net>
landley4f344e32006-10-05 16:18:03 -040010 */
11
12#include "toys.h"
13
landley09ea7ac2006-10-30 01:38:00 -050014void verror_msg(char *msg, int err, va_list va)
15{
16 fprintf(stderr, "%s: ", toys.which->name);
17 vfprintf(stderr, msg, va);
18 if (err) fprintf(stderr, ": %s", strerror(err));
19 putc('\n', stderr);
20}
21
22void error_msg(char *msg, ...)
23{
24 va_list va;
25
26 va_start(va, msg);
27 verror_msg(msg, 0, va);
28 va_end(va);
29}
30
31void perror_msg(char *msg, ...)
32{
33 va_list va;
34
35 va_start(va, msg);
36 verror_msg(msg, errno, va);
37 va_end(va);
38}
39
landley4f344e32006-10-05 16:18:03 -040040// Die with an error message.
41void error_exit(char *msg, ...)
42{
landley09ea7ac2006-10-30 01:38:00 -050043 va_list va;
landley4f344e32006-10-05 16:18:03 -040044
landley09ea7ac2006-10-30 01:38:00 -050045 va_start(va, msg);
46 verror_msg(msg, 0, va);
47 va_end(va);
48
49 exit(toys.exitval);
50}
51
Rob Landley055cfcb2007-01-14 20:20:06 -050052
landley09ea7ac2006-10-30 01:38:00 -050053// Die with an error message and strerror(errno)
54void perror_exit(char *msg, ...)
55{
56 va_list va;
57
58 va_start(va, msg);
59 verror_msg(msg, errno, va);
60 va_end(va);
61
landley4f344e32006-10-05 16:18:03 -040062 exit(toys.exitval);
63}
64
Rob Landley055cfcb2007-01-14 20:20:06 -050065// Stub until the online help system goes in.
66void usage_exit(void)
67{
68 exit(1);
69}
70
landleycd9dfc32006-10-18 18:38:16 -040071// Like strncpy but always null terminated.
landley4f344e32006-10-05 16:18:03 -040072void strlcpy(char *dest, char *src, size_t size)
73{
74 strncpy(dest,src,size);
75 dest[size-1] = 0;
76}
77
78// Die unless we can allocate memory.
79void *xmalloc(size_t size)
80{
81 void *ret = malloc(size);
82 if (!ret) error_exit("xmalloc");
landleycd9dfc32006-10-18 18:38:16 -040083
84 return ret;
landley4f344e32006-10-05 16:18:03 -040085}
86
landleycd9dfc32006-10-18 18:38:16 -040087// Die unless we can allocate prezeroed memory.
88void *xzalloc(size_t size)
89{
90 void *ret = xmalloc(size);
91 bzero(ret,size);
92 return ret;
93}
94
95// Die unless we can change the size of an existing allocation, possibly
96// moving it. (Notice different arguments from libc function.)
Rob Landley0c93f6c2007-04-29 19:55:21 -040097void *xrealloc(void *ptr, size_t size)
landleycd9dfc32006-10-18 18:38:16 -040098{
Rob Landley0c93f6c2007-04-29 19:55:21 -040099 ptr = realloc(ptr, size);
100 if (!ptr) error_exit("xrealloc");
101
102 return ptr;
landleycd9dfc32006-10-18 18:38:16 -0400103}
104
Rob Landleyfa98d012006-11-02 02:57:27 -0500105// Die unless we can allocate a copy of this many bytes of string.
landley4f344e32006-10-05 16:18:03 -0400106void *xstrndup(char *s, size_t n)
107{
108 void *ret = xmalloc(++n);
109 strlcpy(ret, s, n);
110
111 return ret;
112}
113
Rob Landleyfa98d012006-11-02 02:57:27 -0500114// Die unless we can allocate a copy of this string.
115void *xstrdup(char *s)
116{
117 return xstrndup(s,strlen(s));
118}
119
landley00f87f12006-10-25 18:38:37 -0400120// Die unless we can allocate enough space to sprintf() into.
121char *xmsprintf(char *format, ...)
122{
123 va_list va;
124 int len;
125 char *ret;
126
127 // How long is it?
128
129 va_start(va, format);
130 len = vsnprintf(0, 0, format, va);
131 len++;
132 va_end(va);
133
134 // Allocate and do the sprintf()
135 ret = xmalloc(len);
136 va_start(va, format);
137 vsnprintf(ret, len, format, va);
138 va_end(va);
139
140 return ret;
141}
142
Rob Landley24d1d452007-01-20 18:04:20 -0500143void xprintf(char *format, ...)
144{
145 va_list va;
146 va_start(va, format);
147
148 vprintf(format, va);
149 if (ferror(stdout)) perror_exit("write");
150}
151
152void xputc(char c)
153{
154 if (EOF == fputc(c, stdout)) perror_exit("write");
155}
156
157void xflush(void)
158{
159 if (fflush(stdout)) perror_exit("write");;
160}
161
landleycd9dfc32006-10-18 18:38:16 -0400162// Die unless we can exec argv[] (or run builtin command). Note that anything
163// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500164void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400165{
landleycd9dfc32006-10-18 18:38:16 -0400166 toy_exec(argv);
landley4f344e32006-10-05 16:18:03 -0400167 execvp(argv[0], argv);
168 error_exit("No %s", argv[0]);
169}
170
Rob Landleyd3e9d642007-01-08 03:25:47 -0500171void xaccess(char *path, int flags)
172{
Rob Landley24d1d452007-01-20 18:04:20 -0500173 if (access(path, flags)) perror_exit("Can't access '%s'\n", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500174}
175
landley4f344e32006-10-05 16:18:03 -0400176// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500177int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400178{
179 int fd = open(path, flags, mode);
Rob Landley24d1d452007-01-20 18:04:20 -0500180 if (fd == -1) perror_exit("No file %s\n", path);
landley4f344e32006-10-05 16:18:03 -0400181 return fd;
182}
183
Rob Landley1322beb2007-01-07 22:51:12 -0500184// Die unless we can open a file, returning file descriptor.
185int xopen(char *path, int flags)
186{
187 return xcreate(path, flags, 0);
188}
189
landley4f344e32006-10-05 16:18:03 -0400190// Die unless we can open/create a file, returning FILE *.
191FILE *xfopen(char *path, char *mode)
192{
193 FILE *f = fopen(path, mode);
Rob Landley24d1d452007-01-20 18:04:20 -0500194 if (!f) perror_exit("No file %s\n", path);
landley4f344e32006-10-05 16:18:03 -0400195 return f;
196}
landley00f87f12006-10-25 18:38:37 -0400197
landley64b2e232006-10-30 10:01:19 -0500198// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500199ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500200{
Rob Landley90163772007-01-18 21:54:08 -0500201 size_t count = 0;
202 while (count<len) {
203 int i = read(fd, buf+count, len-count);
landley64b2e232006-10-30 10:01:19 -0500204 if (!i) return len;
205 if (i<0) return i;
206 count += i;
207 }
208
209 return count;
210}
211
Rob Landleyf3e452a2007-01-08 02:49:39 -0500212// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500213ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500214{
Rob Landley90163772007-01-18 21:54:08 -0500215 size_t count = 0;
216 while (count<len) {
217 int i = write(fd, buf+count, len-count);
218 if (i<1) return i;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500219 count += i;
220 }
221
222 return count;
223}
224
Rob Landley055cfcb2007-01-14 20:20:06 -0500225// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500226size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500227{
Rob Landley90163772007-01-18 21:54:08 -0500228 len = read(fd, buf, len);
229 if (len < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500230
Rob Landley90163772007-01-18 21:54:08 -0500231 return len;
Rob Landley055cfcb2007-01-14 20:20:06 -0500232}
233
Rob Landley90163772007-01-18 21:54:08 -0500234void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500235{
Rob Landley90163772007-01-18 21:54:08 -0500236 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500237}
landley00f87f12006-10-25 18:38:37 -0400238
Rob Landley90163772007-01-18 21:54:08 -0500239// There's no xwriteall(), just xwrite(). When we read, there may or may not
240// be more data waiting. When we write, there is data and it had better go
241// somewhere.
242
243void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500244{
Rob Landley90163772007-01-18 21:54:08 -0500245 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500246}
247
landley00f87f12006-10-25 18:38:37 -0400248char *xgetcwd(void)
249{
250 char *buf = getcwd(NULL, 0);
Rob Landley24d1d452007-01-20 18:04:20 -0500251 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500252
253 return buf;
landley00f87f12006-10-25 18:38:37 -0400254}
255
Rob Landleyd25f7e42007-02-03 14:11:26 -0500256void xstat(char *path, struct stat *st)
257{
258 if(stat(path, st)) perror_exit("Can't stat %s\n",path);
259}
260
Rob Landleyfa98d012006-11-02 02:57:27 -0500261// Cannonicalizes path by removing ".", "..", and "//" elements. This is not
Rob Landleyc6f481c2006-12-30 22:01:47 -0500262// the same as realpath(), where "dir/.." could wind up somewhere else by
263// following symlinks.
Rob Landleyfa98d012006-11-02 02:57:27 -0500264char *xabspath(char *path)
landley00f87f12006-10-25 18:38:37 -0400265{
Rob Landleyfa98d012006-11-02 02:57:27 -0500266 char *from, *to;
landley00f87f12006-10-25 18:38:37 -0400267
Rob Landleyfa98d012006-11-02 02:57:27 -0500268 // If this isn't an absolute path, make it one with cwd.
269 if (path[0]!='/') {
270 char *cwd=xgetcwd();
271 path = xmsprintf("%s/%s",cwd,path);
272 free(cwd);
273 } else path = xstrdup(path);
landley00f87f12006-10-25 18:38:37 -0400274
Rob Landleyfa98d012006-11-02 02:57:27 -0500275 // Loop through path elements
276 from = to = path;
277 while (*from) {
278
279 // Continue any current path component.
280 if (*from!='/') {
281 *(to++) = *(from++);
282 continue;
landley00f87f12006-10-25 18:38:37 -0400283 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500284
285 // Skip duplicate slashes.
286 while (*from=='/') from++;
287
288 // Start of a new filename. Handle . and ..
289 while (*from=='.') {
290 // Skip .
291 if (from[1]=='/') from += 2;
292 else if (!from[1]) from++;
293 // Back up for ..
294 else if (from[1]=='.') {
295 if (from[2]=='/') from +=3;
296 else if(!from[2]) from+=2;
297 else break;
298 while (to>path && *(--to)!='/');
299 } else break;
300 }
301 // Add directory separator slash.
302 *(to++) = '/';
303 }
304 *to = 0;
305
306 return path;
307}
308
Rob Landley0a04b3e2006-11-03 00:05:52 -0500309// Find all file in a colon-separated path with access type "type" (generally
310// X_OK or R_OK). Returns a list of absolute paths to each file found, in
311// order.
312
313struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500314{
Rob Landley0a04b3e2006-11-03 00:05:52 -0500315 struct string_list *rlist = NULL;
316 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500317
318 for (;;) {
319 char *next = path ? index(path, ':') : NULL;
320 int len = next ? next-path : strlen(path);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500321 struct string_list *rnext;
322 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500323
Rob Landley0a04b3e2006-11-03 00:05:52 -0500324 rnext = xmalloc(sizeof(void *) + strlen(filename)
325 + (len ? len : strlen(cwd)) + 2);
326 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500327 else {
Rob Landley0a04b3e2006-11-03 00:05:52 -0500328 char *res = rnext->str;
Rob Landleyfa98d012006-11-02 02:57:27 -0500329 strncpy(res, path, len);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500330 res += len;
331 *(res++) = '/';
332 strcpy(res, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500333 }
334
Rob Landley0a04b3e2006-11-03 00:05:52 -0500335 // Confirm it's not a directory.
336 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
337 rnext->next = rlist;
338 rlist = rnext;
339 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500340
Rob Landleyfa98d012006-11-02 02:57:27 -0500341 if (!next) break;
342 path += len;
343 path++;
landley00f87f12006-10-25 18:38:37 -0400344 }
345 free(cwd);
346
Rob Landley0a04b3e2006-11-03 00:05:52 -0500347 return rlist;
Rob Landleyfa98d012006-11-02 02:57:27 -0500348
landley00f87f12006-10-25 18:38:37 -0400349}
landley09ea7ac2006-10-30 01:38:00 -0500350
351// Convert unsigned int to ascii, writing into supplied buffer. A truncated
352// result contains the first few digits of the result ala strncpy, and is
353// always null terminated (unless buflen is 0).
354void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
355{
356 int i, out = 0;
357
358 if (buflen) {
359 for (i=1000000000; i; i/=10) {
360 int res = n/i;
361
362 if ((res || out || i == 1) && --buflen>0) {
363 out++;
364 n -= res*i;
365 *buf++ = '0' + res;
366 }
367 }
368 *buf = 0;
369 }
370}
371
372// Convert signed integer to ascii, using utoa_to_buf()
373void itoa_to_buf(int n, char *buf, unsigned buflen)
374{
375 if (buflen && n<0) {
376 n = -n;
377 *buf++ = '-';
378 buflen--;
379 }
380 utoa_to_buf((unsigned)n, buf, buflen);
381}
382
383// This static buffer is used by both utoa() and itoa(), calling either one a
384// second time will overwrite the previous results.
385//
386// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
387// Note that int is always 32 bits on any remotely unix-like system, see
388// http://www.unix.org/whitepapers/64bit.html for details.
389
390static char itoa_buf[12];
391
392// Convert unsigned integer to ascii, returning a static buffer.
393char *utoa(unsigned n)
394{
395 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
396
397 return itoa_buf;
398}
399
400char *itoa(int n)
401{
402 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
403
404 return itoa_buf;
405}
Rob Landley055cfcb2007-01-14 20:20:06 -0500406
Rob Landleyf5757162007-02-16 21:08:22 -0500407// atol() with the kilo/mega/giga/tera/peta/exa extensions.
408// (zetta and yotta don't fit in 64 bits.)
409long atolx(char *c)
410{
411 char *suffixes="kmgtpe", *end;
412 long val = strtol(c, &c, 0);
413
414 end = strchr(suffixes, tolower(*c));
415 if (end) val *= 1024<<((end-suffixes)*10);
416 return val;
417}
418
Rob Landley055cfcb2007-01-14 20:20:06 -0500419// Return how long the file at fd is, if there's any way to determine it.
420off_t fdlength(int fd)
421{
422 off_t bottom = 0, top = 0, pos;
Rob Landleye2580db2007-01-23 13:20:38 -0500423 int size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500424
425 // If the ioctl works for this, return it.
426
Rob Landleye2580db2007-01-23 13:20:38 -0500427 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500428
429 // If not, do a binary search for the last location we can read. (Some
430 // block devices don't do BLKGETSIZE right.) This should probably have
431 // a CONFIG option...
432
433 do {
434 char temp;
435
436 pos = bottom + (top - bottom) / 2;
437
438 // If we can read from the current location, it's bigger.
439
Rob Landleyb3a33822007-01-25 16:10:37 -0500440 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley055cfcb2007-01-14 20:20:06 -0500441 if (bottom == top) bottom = top = (top+1) * 2;
442 else bottom = pos;
443
444 // If we can't, it's smaller.
445
446 } else {
447 if (bottom == top) {
448 if (!top) return 0;
449 bottom = top/2;
450 } else top = pos;
451 }
452 } while (bottom + 1 != top);
453
454 return pos + 1;
455}
456
Rob Landley0c93f6c2007-04-29 19:55:21 -0400457// This can return null (meaning file not found). It just won't return null
458// for memory allocation reasons.
459char *xreadlink(char *name)
460{
461 int len, size = 0;
462 char *buf = 0;
463
464 // Grow by 64 byte chunks until it's big enough.
465 for(;;) {
466 size +=64;
467 buf = xrealloc(buf, size);
468 len = readlink(name, buf, size);
469
470 if (len<0) {
471 free(buf);
472 return 0;
473 }
474 if (len<size) {
475 buf[len]=0;
476 return buf;
477 }
478 }
479}
480
Rob Landleyb3a33822007-01-25 16:10:37 -0500481/*
482 This might be of use or might not. Unknown yet...
483
Rob Landley055cfcb2007-01-14 20:20:06 -0500484// Read contents of file as a single freshly allocated nul-terminated string.
485char *readfile(char *name)
486{
487 off_t len;
488 int fd;
489 char *buf;
490
491 fd = open(pidfile, O_RDONLY);
492 if (fd == -1) return 0;
493 len = fdlength(fd);
494 buf = xmalloc(len+1);
495 buf[xread(fd, buf, len)] = 0;
496
497 return buf;
498}
499
500char *xreadfile(char *name)
501{
502 char *buf = readfile(name);
Rob Landley24d1d452007-01-20 18:04:20 -0500503 if (!buf) perror_exit("xreadfile %s", name);
Rob Landley055cfcb2007-01-14 20:20:06 -0500504 return buf;
505}
506
507*/
508
509// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
510// exists and is this executable.
511void xpidfile(char *name)
512{
513 char pidfile[256], spid[32];
514 int i, fd;
515 pid_t pid;
516
517 sprintf(pidfile, "/var/run/%s.pid", name);
518 // Try three times to open the sucker.
519 for (i=0; i<3; i++) {
520 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
521 if (fd != -1) break;
522
523 // If it already existed, read it. Loop for race condition.
524 fd = open(pidfile, O_RDONLY);
525 if (fd == -1) continue;
526
527 // Is the old program still there?
528 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
529 close(fd);
530 pid = atoi(spid);
531 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
532
533 // An else with more sanity checking might be nice here.
534 }
535
536 if (i == 3) error_exit("xpidfile %s", name);
537
538 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
539 close(fd);
540}
Rob Landleyd25f7e42007-02-03 14:11:26 -0500541
542// Create a dirtree node from a path.
543
544struct dirtree *read_dirtree_node(char *path)
545{
546 struct dirtree *dt;
547 char *name;
548
549 // Find last chunk of name.
550
551 for (;;) {
552 name = strrchr(path, '/');
553
554 if (!name) name = path;
555 else {
556 if (*(name+1)) name++;
557 else {
558 *name=0;
559 continue;
560 }
561 }
562 break;
563 }
564
565 dt = xzalloc(sizeof(struct dirtree)+strlen(name)+1);
566 xstat(path, &(dt->st));
567 strcpy(dt->name, name);
568
569 return dt;
570}
571
572// Given a directory (in a writeable PATH_MAX buffer), recursively read in a
573// directory tree.
574
Rob Landley720fc262007-02-04 19:14:58 -0500575struct dirtree *read_dirtree(char *path, struct dirtree *parent)
Rob Landleyd25f7e42007-02-03 14:11:26 -0500576{
577 struct dirtree *dt = NULL, **ddt = &dt;
578 DIR *dir;
579 int len = strlen(path);
580
581 if (!(dir = opendir(path))) perror_msg("No %s", path);
582
583 for (;;) {
584 struct dirent *entry = readdir(dir);
585 if (!entry) break;
586
587 // Skip "." and ".."
588 if (entry->d_name[0]=='.') {
589 if (!entry->d_name[1]) continue;
590 if (entry->d_name[1]=='.' && !entry->d_name[2]) continue;
591 }
592
593 snprintf(path+len, sizeof(toybuf)-len, "/%s", entry->d_name);
594 *ddt = read_dirtree_node(path);
Rob Landley720fc262007-02-04 19:14:58 -0500595 (*ddt)->parent = parent;
596 if (entry->d_type == DT_DIR) (*ddt)->child = read_dirtree(path, *ddt);
Rob Landleyd25f7e42007-02-03 14:11:26 -0500597 ddt = &((*ddt)->next);
598 path[len]=0;
599 }
600
601 return dt;
602}