blob: b8c122e0ea790eddea5a711a1b2a38406842c1a3 [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.)
97void xrealloc(void **ptr, size_t size)
98{
99 *ptr = realloc(*ptr, size);
100 if (!*ptr) error_exit("xrealloc");
101}
102
Rob Landleyfa98d012006-11-02 02:57:27 -0500103// Die unless we can allocate a copy of this many bytes of string.
landley4f344e32006-10-05 16:18:03 -0400104void *xstrndup(char *s, size_t n)
105{
106 void *ret = xmalloc(++n);
107 strlcpy(ret, s, n);
108
109 return ret;
110}
111
Rob Landleyfa98d012006-11-02 02:57:27 -0500112// Die unless we can allocate a copy of this string.
113void *xstrdup(char *s)
114{
115 return xstrndup(s,strlen(s));
116}
117
landley00f87f12006-10-25 18:38:37 -0400118// Die unless we can allocate enough space to sprintf() into.
119char *xmsprintf(char *format, ...)
120{
121 va_list va;
122 int len;
123 char *ret;
124
125 // How long is it?
126
127 va_start(va, format);
128 len = vsnprintf(0, 0, format, va);
129 len++;
130 va_end(va);
131
132 // Allocate and do the sprintf()
133 ret = xmalloc(len);
134 va_start(va, format);
135 vsnprintf(ret, len, format, va);
136 va_end(va);
137
138 return ret;
139}
140
Rob Landley24d1d452007-01-20 18:04:20 -0500141void xprintf(char *format, ...)
142{
143 va_list va;
144 va_start(va, format);
145
146 vprintf(format, va);
147 if (ferror(stdout)) perror_exit("write");
148}
149
150void xputc(char c)
151{
152 if (EOF == fputc(c, stdout)) perror_exit("write");
153}
154
155void xflush(void)
156{
157 if (fflush(stdout)) perror_exit("write");;
158}
159
landleycd9dfc32006-10-18 18:38:16 -0400160// Die unless we can exec argv[] (or run builtin command). Note that anything
161// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500162void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400163{
landleycd9dfc32006-10-18 18:38:16 -0400164 toy_exec(argv);
landley4f344e32006-10-05 16:18:03 -0400165 execvp(argv[0], argv);
166 error_exit("No %s", argv[0]);
167}
168
Rob Landleyd3e9d642007-01-08 03:25:47 -0500169void xaccess(char *path, int flags)
170{
Rob Landley24d1d452007-01-20 18:04:20 -0500171 if (access(path, flags)) perror_exit("Can't access '%s'\n", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500172}
173
landley4f344e32006-10-05 16:18:03 -0400174// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500175int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400176{
177 int fd = open(path, flags, mode);
Rob Landley24d1d452007-01-20 18:04:20 -0500178 if (fd == -1) perror_exit("No file %s\n", path);
landley4f344e32006-10-05 16:18:03 -0400179 return fd;
180}
181
Rob Landley1322beb2007-01-07 22:51:12 -0500182// Die unless we can open a file, returning file descriptor.
183int xopen(char *path, int flags)
184{
185 return xcreate(path, flags, 0);
186}
187
landley4f344e32006-10-05 16:18:03 -0400188// Die unless we can open/create a file, returning FILE *.
189FILE *xfopen(char *path, char *mode)
190{
191 FILE *f = fopen(path, mode);
Rob Landley24d1d452007-01-20 18:04:20 -0500192 if (!f) perror_exit("No file %s\n", path);
landley4f344e32006-10-05 16:18:03 -0400193 return f;
194}
landley00f87f12006-10-25 18:38:37 -0400195
landley64b2e232006-10-30 10:01:19 -0500196// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500197ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500198{
Rob Landley90163772007-01-18 21:54:08 -0500199 size_t count = 0;
200 while (count<len) {
201 int i = read(fd, buf+count, len-count);
landley64b2e232006-10-30 10:01:19 -0500202 if (!i) return len;
203 if (i<0) return i;
204 count += i;
205 }
206
207 return count;
208}
209
Rob Landleyf3e452a2007-01-08 02:49:39 -0500210// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500211ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500212{
Rob Landley90163772007-01-18 21:54:08 -0500213 size_t count = 0;
214 while (count<len) {
215 int i = write(fd, buf+count, len-count);
216 if (i<1) return i;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500217 count += i;
218 }
219
220 return count;
221}
222
Rob Landley055cfcb2007-01-14 20:20:06 -0500223// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500224size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500225{
Rob Landley90163772007-01-18 21:54:08 -0500226 len = read(fd, buf, len);
227 if (len < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500228
Rob Landley90163772007-01-18 21:54:08 -0500229 return len;
Rob Landley055cfcb2007-01-14 20:20:06 -0500230}
231
Rob Landley90163772007-01-18 21:54:08 -0500232void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500233{
Rob Landley90163772007-01-18 21:54:08 -0500234 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500235}
landley00f87f12006-10-25 18:38:37 -0400236
Rob Landley90163772007-01-18 21:54:08 -0500237// There's no xwriteall(), just xwrite(). When we read, there may or may not
238// be more data waiting. When we write, there is data and it had better go
239// somewhere.
240
241void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500242{
Rob Landley90163772007-01-18 21:54:08 -0500243 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500244}
245
landley00f87f12006-10-25 18:38:37 -0400246char *xgetcwd(void)
247{
248 char *buf = getcwd(NULL, 0);
Rob Landley24d1d452007-01-20 18:04:20 -0500249 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500250
251 return buf;
landley00f87f12006-10-25 18:38:37 -0400252}
253
Rob Landleyfa98d012006-11-02 02:57:27 -0500254// Cannonicalizes path by removing ".", "..", and "//" elements. This is not
Rob Landleyc6f481c2006-12-30 22:01:47 -0500255// the same as realpath(), where "dir/.." could wind up somewhere else by
256// following symlinks.
Rob Landleyfa98d012006-11-02 02:57:27 -0500257char *xabspath(char *path)
landley00f87f12006-10-25 18:38:37 -0400258{
Rob Landleyfa98d012006-11-02 02:57:27 -0500259 char *from, *to;
landley00f87f12006-10-25 18:38:37 -0400260
Rob Landleyfa98d012006-11-02 02:57:27 -0500261 // If this isn't an absolute path, make it one with cwd.
262 if (path[0]!='/') {
263 char *cwd=xgetcwd();
264 path = xmsprintf("%s/%s",cwd,path);
265 free(cwd);
266 } else path = xstrdup(path);
landley00f87f12006-10-25 18:38:37 -0400267
Rob Landleyfa98d012006-11-02 02:57:27 -0500268 // Loop through path elements
269 from = to = path;
270 while (*from) {
271
272 // Continue any current path component.
273 if (*from!='/') {
274 *(to++) = *(from++);
275 continue;
landley00f87f12006-10-25 18:38:37 -0400276 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500277
278 // Skip duplicate slashes.
279 while (*from=='/') from++;
280
281 // Start of a new filename. Handle . and ..
282 while (*from=='.') {
283 // Skip .
284 if (from[1]=='/') from += 2;
285 else if (!from[1]) from++;
286 // Back up for ..
287 else if (from[1]=='.') {
288 if (from[2]=='/') from +=3;
289 else if(!from[2]) from+=2;
290 else break;
291 while (to>path && *(--to)!='/');
292 } else break;
293 }
294 // Add directory separator slash.
295 *(to++) = '/';
296 }
297 *to = 0;
298
299 return path;
300}
301
Rob Landley0a04b3e2006-11-03 00:05:52 -0500302// Find all file in a colon-separated path with access type "type" (generally
303// X_OK or R_OK). Returns a list of absolute paths to each file found, in
304// order.
305
306struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500307{
Rob Landley0a04b3e2006-11-03 00:05:52 -0500308 struct string_list *rlist = NULL;
309 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500310
311 for (;;) {
312 char *next = path ? index(path, ':') : NULL;
313 int len = next ? next-path : strlen(path);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500314 struct string_list *rnext;
315 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500316
Rob Landley0a04b3e2006-11-03 00:05:52 -0500317 rnext = xmalloc(sizeof(void *) + strlen(filename)
318 + (len ? len : strlen(cwd)) + 2);
319 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500320 else {
Rob Landley0a04b3e2006-11-03 00:05:52 -0500321 char *res = rnext->str;
Rob Landleyfa98d012006-11-02 02:57:27 -0500322 strncpy(res, path, len);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500323 res += len;
324 *(res++) = '/';
325 strcpy(res, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500326 }
327
Rob Landley0a04b3e2006-11-03 00:05:52 -0500328 // Confirm it's not a directory.
329 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
330 rnext->next = rlist;
331 rlist = rnext;
332 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500333
Rob Landleyfa98d012006-11-02 02:57:27 -0500334 if (!next) break;
335 path += len;
336 path++;
landley00f87f12006-10-25 18:38:37 -0400337 }
338 free(cwd);
339
Rob Landley0a04b3e2006-11-03 00:05:52 -0500340 return rlist;
Rob Landleyfa98d012006-11-02 02:57:27 -0500341
landley00f87f12006-10-25 18:38:37 -0400342}
landley09ea7ac2006-10-30 01:38:00 -0500343
344// Convert unsigned int to ascii, writing into supplied buffer. A truncated
345// result contains the first few digits of the result ala strncpy, and is
346// always null terminated (unless buflen is 0).
347void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
348{
349 int i, out = 0;
350
351 if (buflen) {
352 for (i=1000000000; i; i/=10) {
353 int res = n/i;
354
355 if ((res || out || i == 1) && --buflen>0) {
356 out++;
357 n -= res*i;
358 *buf++ = '0' + res;
359 }
360 }
361 *buf = 0;
362 }
363}
364
365// Convert signed integer to ascii, using utoa_to_buf()
366void itoa_to_buf(int n, char *buf, unsigned buflen)
367{
368 if (buflen && n<0) {
369 n = -n;
370 *buf++ = '-';
371 buflen--;
372 }
373 utoa_to_buf((unsigned)n, buf, buflen);
374}
375
376// This static buffer is used by both utoa() and itoa(), calling either one a
377// second time will overwrite the previous results.
378//
379// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
380// Note that int is always 32 bits on any remotely unix-like system, see
381// http://www.unix.org/whitepapers/64bit.html for details.
382
383static char itoa_buf[12];
384
385// Convert unsigned integer to ascii, returning a static buffer.
386char *utoa(unsigned n)
387{
388 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
389
390 return itoa_buf;
391}
392
393char *itoa(int n)
394{
395 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
396
397 return itoa_buf;
398}
Rob Landley055cfcb2007-01-14 20:20:06 -0500399
400/*
401 This might be of use or might not. Unknown yet...
402
403
404// Return how long the file at fd is, if there's any way to determine it.
405off_t fdlength(int fd)
406{
407 off_t bottom = 0, top = 0, pos;
408 long size;
409
410 // If the ioctl works for this, return it.
411
412 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
413
414 // If not, do a binary search for the last location we can read. (Some
415 // block devices don't do BLKGETSIZE right.) This should probably have
416 // a CONFIG option...
417
418 do {
419 char temp;
420
421 pos = bottom + (top - bottom) / 2;
422
423 // If we can read from the current location, it's bigger.
424
425 if (lseek(fd, pos, 0)>=0 && safe_read(fd, &temp, 1)==1) {
426 if (bottom == top) bottom = top = (top+1) * 2;
427 else bottom = pos;
428
429 // If we can't, it's smaller.
430
431 } else {
432 if (bottom == top) {
433 if (!top) return 0;
434 bottom = top/2;
435 } else top = pos;
436 }
437 } while (bottom + 1 != top);
438
439 return pos + 1;
440}
441
442// Read contents of file as a single freshly allocated nul-terminated string.
443char *readfile(char *name)
444{
445 off_t len;
446 int fd;
447 char *buf;
448
449 fd = open(pidfile, O_RDONLY);
450 if (fd == -1) return 0;
451 len = fdlength(fd);
452 buf = xmalloc(len+1);
453 buf[xread(fd, buf, len)] = 0;
454
455 return buf;
456}
457
458char *xreadfile(char *name)
459{
460 char *buf = readfile(name);
Rob Landley24d1d452007-01-20 18:04:20 -0500461 if (!buf) perror_exit("xreadfile %s", name);
Rob Landley055cfcb2007-01-14 20:20:06 -0500462 return buf;
463}
464
465*/
466
467// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
468// exists and is this executable.
469void xpidfile(char *name)
470{
471 char pidfile[256], spid[32];
472 int i, fd;
473 pid_t pid;
474
475 sprintf(pidfile, "/var/run/%s.pid", name);
476 // Try three times to open the sucker.
477 for (i=0; i<3; i++) {
478 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
479 if (fd != -1) break;
480
481 // If it already existed, read it. Loop for race condition.
482 fd = open(pidfile, O_RDONLY);
483 if (fd == -1) continue;
484
485 // Is the old program still there?
486 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
487 close(fd);
488 pid = atoi(spid);
489 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
490
491 // An else with more sanity checking might be nice here.
492 }
493
494 if (i == 3) error_exit("xpidfile %s", name);
495
496 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
497 close(fd);
498}