blob: 98a344a21bfd7eafeca5d8f8b4b61d2613adf468 [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
landleycd9dfc32006-10-18 18:38:16 -0400141// Die unless we can exec argv[] (or run builtin command). Note that anything
142// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500143void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400144{
landleycd9dfc32006-10-18 18:38:16 -0400145 toy_exec(argv);
landley4f344e32006-10-05 16:18:03 -0400146 execvp(argv[0], argv);
147 error_exit("No %s", argv[0]);
148}
149
Rob Landleyd3e9d642007-01-08 03:25:47 -0500150void xaccess(char *path, int flags)
151{
152 if (access(path, flags)) error_exit("Can't access '%s'\n", path);
153}
154
landley4f344e32006-10-05 16:18:03 -0400155// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500156int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400157{
158 int fd = open(path, flags, mode);
159 if (fd == -1) error_exit("No file %s\n", path);
160 return fd;
161}
162
Rob Landley1322beb2007-01-07 22:51:12 -0500163// Die unless we can open a file, returning file descriptor.
164int xopen(char *path, int flags)
165{
166 return xcreate(path, flags, 0);
167}
168
landley4f344e32006-10-05 16:18:03 -0400169// Die unless we can open/create a file, returning FILE *.
170FILE *xfopen(char *path, char *mode)
171{
172 FILE *f = fopen(path, mode);
173 if (!f) error_exit("No file %s\n", path);
174 return f;
175}
landley00f87f12006-10-25 18:38:37 -0400176
landley64b2e232006-10-30 10:01:19 -0500177// Read from file handle, retrying if interrupted.
178ssize_t reread(int fd, void *buf, size_t count)
179{
landley64b2e232006-10-30 10:01:19 -0500180 for (;;) {
Rob Landleyf3e452a2007-01-08 02:49:39 -0500181 ssize_t len = read(fd, buf, count);
landley64b2e232006-10-30 10:01:19 -0500182 if (len >= 0 || errno != EINTR) return len;
183 }
184}
185
Rob Landleyf3e452a2007-01-08 02:49:39 -0500186// Write to file handle, retrying if interrupted.
187ssize_t rewrite(int fd, void *buf, size_t count)
188{
189 for (;;) {
190 ssize_t len = write(fd, buf, count);
191 if (len >= 0 || errno != EINTR) return len;
192 }
193}
194
landley64b2e232006-10-30 10:01:19 -0500195// Keep reading until full or EOF
196ssize_t readall(int fd, void *buf, size_t count)
197{
198 size_t len = 0;
199 while (len<count) {
200 int i = reread(fd, buf, count);
201 if (!i) return len;
202 if (i<0) return i;
203 count += i;
204 }
205
206 return count;
207}
208
Rob Landleyf3e452a2007-01-08 02:49:39 -0500209// Keep writing until done or EOF
210ssize_t writeall(int fd, void *buf, size_t count)
211{
212 size_t len = 0;
213 while (len<count) {
214 int i = rewrite(fd, buf, count);
215 if (!i) return len;
216 if (i<0) return i;
217 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.
224size_t xread(int fd, void *buf, size_t count)
landley64b2e232006-10-30 10:01:19 -0500225{
Rob Landley055cfcb2007-01-14 20:20:06 -0500226 count = reread(fd, buf, count);
227 if (count < 0) perror_exit("xread");
228
229 return count;
230}
231
232void xreadall(int fd, void *buf, size_t count)
233{
234 if (count != readall(fd, buf, count)) perror_exit("xreadall");
235}
landley00f87f12006-10-25 18:38:37 -0400236
Rob Landley3388f4c2007-01-08 04:26:01 -0500237void xwrite(int fd, void *buf, size_t count)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500238{
239 if (count != writeall(fd, buf, count)) perror_exit("xwrite");
240}
241
landley00f87f12006-10-25 18:38:37 -0400242char *xgetcwd(void)
243{
244 char *buf = getcwd(NULL, 0);
245 if (!buf) error_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500246
247 return buf;
landley00f87f12006-10-25 18:38:37 -0400248}
249
Rob Landleyfa98d012006-11-02 02:57:27 -0500250// Cannonicalizes path by removing ".", "..", and "//" elements. This is not
Rob Landleyc6f481c2006-12-30 22:01:47 -0500251// the same as realpath(), where "dir/.." could wind up somewhere else by
252// following symlinks.
Rob Landleyfa98d012006-11-02 02:57:27 -0500253char *xabspath(char *path)
landley00f87f12006-10-25 18:38:37 -0400254{
Rob Landleyfa98d012006-11-02 02:57:27 -0500255 char *from, *to;
landley00f87f12006-10-25 18:38:37 -0400256
Rob Landleyfa98d012006-11-02 02:57:27 -0500257 // If this isn't an absolute path, make it one with cwd.
258 if (path[0]!='/') {
259 char *cwd=xgetcwd();
260 path = xmsprintf("%s/%s",cwd,path);
261 free(cwd);
262 } else path = xstrdup(path);
landley00f87f12006-10-25 18:38:37 -0400263
Rob Landleyfa98d012006-11-02 02:57:27 -0500264 // Loop through path elements
265 from = to = path;
266 while (*from) {
267
268 // Continue any current path component.
269 if (*from!='/') {
270 *(to++) = *(from++);
271 continue;
landley00f87f12006-10-25 18:38:37 -0400272 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500273
274 // Skip duplicate slashes.
275 while (*from=='/') from++;
276
277 // Start of a new filename. Handle . and ..
278 while (*from=='.') {
279 // Skip .
280 if (from[1]=='/') from += 2;
281 else if (!from[1]) from++;
282 // Back up for ..
283 else if (from[1]=='.') {
284 if (from[2]=='/') from +=3;
285 else if(!from[2]) from+=2;
286 else break;
287 while (to>path && *(--to)!='/');
288 } else break;
289 }
290 // Add directory separator slash.
291 *(to++) = '/';
292 }
293 *to = 0;
294
295 return path;
296}
297
Rob Landley0a04b3e2006-11-03 00:05:52 -0500298// Find all file in a colon-separated path with access type "type" (generally
299// X_OK or R_OK). Returns a list of absolute paths to each file found, in
300// order.
301
302struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500303{
Rob Landley0a04b3e2006-11-03 00:05:52 -0500304 struct string_list *rlist = NULL;
305 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500306
307 for (;;) {
308 char *next = path ? index(path, ':') : NULL;
309 int len = next ? next-path : strlen(path);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500310 struct string_list *rnext;
311 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500312
Rob Landley0a04b3e2006-11-03 00:05:52 -0500313 rnext = xmalloc(sizeof(void *) + strlen(filename)
314 + (len ? len : strlen(cwd)) + 2);
315 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500316 else {
Rob Landley0a04b3e2006-11-03 00:05:52 -0500317 char *res = rnext->str;
Rob Landleyfa98d012006-11-02 02:57:27 -0500318 strncpy(res, path, len);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500319 res += len;
320 *(res++) = '/';
321 strcpy(res, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500322 }
323
Rob Landley0a04b3e2006-11-03 00:05:52 -0500324 // Confirm it's not a directory.
325 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
326 rnext->next = rlist;
327 rlist = rnext;
328 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500329
Rob Landleyfa98d012006-11-02 02:57:27 -0500330 if (!next) break;
331 path += len;
332 path++;
landley00f87f12006-10-25 18:38:37 -0400333 }
334 free(cwd);
335
Rob Landley0a04b3e2006-11-03 00:05:52 -0500336 return rlist;
Rob Landleyfa98d012006-11-02 02:57:27 -0500337
landley00f87f12006-10-25 18:38:37 -0400338}
landley09ea7ac2006-10-30 01:38:00 -0500339
340// Convert unsigned int to ascii, writing into supplied buffer. A truncated
341// result contains the first few digits of the result ala strncpy, and is
342// always null terminated (unless buflen is 0).
343void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
344{
345 int i, out = 0;
346
347 if (buflen) {
348 for (i=1000000000; i; i/=10) {
349 int res = n/i;
350
351 if ((res || out || i == 1) && --buflen>0) {
352 out++;
353 n -= res*i;
354 *buf++ = '0' + res;
355 }
356 }
357 *buf = 0;
358 }
359}
360
361// Convert signed integer to ascii, using utoa_to_buf()
362void itoa_to_buf(int n, char *buf, unsigned buflen)
363{
364 if (buflen && n<0) {
365 n = -n;
366 *buf++ = '-';
367 buflen--;
368 }
369 utoa_to_buf((unsigned)n, buf, buflen);
370}
371
372// This static buffer is used by both utoa() and itoa(), calling either one a
373// second time will overwrite the previous results.
374//
375// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
376// Note that int is always 32 bits on any remotely unix-like system, see
377// http://www.unix.org/whitepapers/64bit.html for details.
378
379static char itoa_buf[12];
380
381// Convert unsigned integer to ascii, returning a static buffer.
382char *utoa(unsigned n)
383{
384 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
385
386 return itoa_buf;
387}
388
389char *itoa(int n)
390{
391 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
392
393 return itoa_buf;
394}
Rob Landley055cfcb2007-01-14 20:20:06 -0500395
396/*
397 This might be of use or might not. Unknown yet...
398
399
400// Return how long the file at fd is, if there's any way to determine it.
401off_t fdlength(int fd)
402{
403 off_t bottom = 0, top = 0, pos;
404 long size;
405
406 // If the ioctl works for this, return it.
407
408 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
409
410 // If not, do a binary search for the last location we can read. (Some
411 // block devices don't do BLKGETSIZE right.) This should probably have
412 // a CONFIG option...
413
414 do {
415 char temp;
416
417 pos = bottom + (top - bottom) / 2;
418
419 // If we can read from the current location, it's bigger.
420
421 if (lseek(fd, pos, 0)>=0 && safe_read(fd, &temp, 1)==1) {
422 if (bottom == top) bottom = top = (top+1) * 2;
423 else bottom = pos;
424
425 // If we can't, it's smaller.
426
427 } else {
428 if (bottom == top) {
429 if (!top) return 0;
430 bottom = top/2;
431 } else top = pos;
432 }
433 } while (bottom + 1 != top);
434
435 return pos + 1;
436}
437
438// Read contents of file as a single freshly allocated nul-terminated string.
439char *readfile(char *name)
440{
441 off_t len;
442 int fd;
443 char *buf;
444
445 fd = open(pidfile, O_RDONLY);
446 if (fd == -1) return 0;
447 len = fdlength(fd);
448 buf = xmalloc(len+1);
449 buf[xread(fd, buf, len)] = 0;
450
451 return buf;
452}
453
454char *xreadfile(char *name)
455{
456 char *buf = readfile(name);
457 if (!buf) error_exit("xreadfile %s", name);
458 return buf;
459}
460
461*/
462
463// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
464// exists and is this executable.
465void xpidfile(char *name)
466{
467 char pidfile[256], spid[32];
468 int i, fd;
469 pid_t pid;
470
471 sprintf(pidfile, "/var/run/%s.pid", name);
472 // Try three times to open the sucker.
473 for (i=0; i<3; i++) {
474 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
475 if (fd != -1) break;
476
477 // If it already existed, read it. Loop for race condition.
478 fd = open(pidfile, O_RDONLY);
479 if (fd == -1) continue;
480
481 // Is the old program still there?
482 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
483 close(fd);
484 pid = atoi(spid);
485 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
486
487 // An else with more sanity checking might be nice here.
488 }
489
490 if (i == 3) error_exit("xpidfile %s", name);
491
492 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
493 close(fd);
494}