blob: 1f5d797f5ef16ea39013ae6294221d93bd6d817c [file] [log] [blame]
landleycd9dfc32006-10-18 18:38:16 -04001/* vi: set sw=4 ts=4 :*/
Charlie Shepherd54524c92008-01-25 12:36:24 +00002/* lib.c - reusable stuff.
landley4f344e32006-10-05 16:18:03 -04003 *
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
Rob Landleye15850a2007-11-19 01:51:00 -060014// Strcpy with size checking: exit if there's not enough space for the string.
15void xstrcpy(char *dest, char *src, size_t size)
Rob Landley18d43ff2007-06-07 15:19:44 -040016{
Rob Landleye15850a2007-11-19 01:51:00 -060017 if (strlen(src)+1 > size) error_exit("xstrcpy");
18 strcpy(dest, src);
Rob Landley18d43ff2007-06-07 15:19:44 -040019}
Rob Landley18d43ff2007-06-07 15:19:44 -040020
landley09ea7ac2006-10-30 01:38:00 -050021void verror_msg(char *msg, int err, va_list va)
22{
Rob Landley12138e42008-01-27 15:26:08 -060023 char *s = ": %s";
24
landley09ea7ac2006-10-30 01:38:00 -050025 fprintf(stderr, "%s: ", toys.which->name);
Rob Landley12138e42008-01-27 15:26:08 -060026 if (msg) vfprintf(stderr, msg, va);
27 else s+=2;
28 if (err) fprintf(stderr, s, strerror(err));
landley09ea7ac2006-10-30 01:38:00 -050029 putc('\n', stderr);
30}
31
32void error_msg(char *msg, ...)
33{
34 va_list va;
35
36 va_start(va, msg);
37 verror_msg(msg, 0, va);
38 va_end(va);
39}
40
41void perror_msg(char *msg, ...)
42{
43 va_list va;
44
45 va_start(va, msg);
46 verror_msg(msg, errno, va);
47 va_end(va);
48}
49
landley4f344e32006-10-05 16:18:03 -040050// Die with an error message.
51void error_exit(char *msg, ...)
52{
landley09ea7ac2006-10-30 01:38:00 -050053 va_list va;
landley4f344e32006-10-05 16:18:03 -040054
Rob Landleyd06c58d2007-10-11 15:36:36 -050055 if (CFG_HELP && toys.exithelp) {
56 *toys.optargs=*toys.argv;
Rob Landley55928b12008-01-19 17:43:27 -060057 USE_HELP(help_main();) // dear gcc: shut up.
Rob Landleyd06c58d2007-10-11 15:36:36 -050058 fprintf(stderr,"\n");
59 }
60
landley09ea7ac2006-10-30 01:38:00 -050061 va_start(va, msg);
62 verror_msg(msg, 0, va);
63 va_end(va);
64
Rob Landleyaaffc072007-12-09 15:35:42 -060065 exit(!toys.exitval ? 1 : toys.exitval);
landley09ea7ac2006-10-30 01:38:00 -050066}
67
Rob Landley055cfcb2007-01-14 20:20:06 -050068
landley09ea7ac2006-10-30 01:38:00 -050069// Die with an error message and strerror(errno)
70void perror_exit(char *msg, ...)
71{
72 va_list va;
73
74 va_start(va, msg);
75 verror_msg(msg, errno, va);
76 va_end(va);
77
Rob Landleyaaffc072007-12-09 15:35:42 -060078 exit(!toys.exitval ? 1 : toys.exitval);
landley4f344e32006-10-05 16:18:03 -040079}
80
landley4f344e32006-10-05 16:18:03 -040081// Die unless we can allocate memory.
82void *xmalloc(size_t size)
83{
84 void *ret = malloc(size);
85 if (!ret) error_exit("xmalloc");
landleycd9dfc32006-10-18 18:38:16 -040086
87 return ret;
landley4f344e32006-10-05 16:18:03 -040088}
89
landleycd9dfc32006-10-18 18:38:16 -040090// Die unless we can allocate prezeroed memory.
91void *xzalloc(size_t size)
92{
93 void *ret = xmalloc(size);
Rob Landleyf6418542008-01-27 16:22:41 -060094 bzero(ret, size);
landleycd9dfc32006-10-18 18:38:16 -040095 return ret;
96}
97
98// Die unless we can change the size of an existing allocation, possibly
99// moving it. (Notice different arguments from libc function.)
Rob Landley0c93f6c2007-04-29 19:55:21 -0400100void *xrealloc(void *ptr, size_t size)
landleycd9dfc32006-10-18 18:38:16 -0400101{
Rob Landley0c93f6c2007-04-29 19:55:21 -0400102 ptr = realloc(ptr, size);
103 if (!ptr) error_exit("xrealloc");
104
105 return ptr;
landleycd9dfc32006-10-18 18:38:16 -0400106}
107
Rob Landleyfa98d012006-11-02 02:57:27 -0500108// Die unless we can allocate a copy of this many bytes of string.
landley4f344e32006-10-05 16:18:03 -0400109void *xstrndup(char *s, size_t n)
110{
111 void *ret = xmalloc(++n);
Rob Landleye15850a2007-11-19 01:51:00 -0600112 xstrcpy(ret, s, n);
Rob Landley2c226852007-11-15 18:30:30 -0600113
landley4f344e32006-10-05 16:18:03 -0400114 return ret;
115}
116
Rob Landleyfa98d012006-11-02 02:57:27 -0500117// Die unless we can allocate a copy of this string.
118void *xstrdup(char *s)
119{
Rob Landleyf6418542008-01-27 16:22:41 -0600120 return xstrndup(s, strlen(s));
Rob Landleyfa98d012006-11-02 02:57:27 -0500121}
122
landley00f87f12006-10-25 18:38:37 -0400123// Die unless we can allocate enough space to sprintf() into.
124char *xmsprintf(char *format, ...)
125{
Rob Landley0d8dfb22007-06-15 15:16:46 -0400126 va_list va, va2;
landley00f87f12006-10-25 18:38:37 -0400127 int len;
128 char *ret;
Rob Landley2c226852007-11-15 18:30:30 -0600129
landley00f87f12006-10-25 18:38:37 -0400130 va_start(va, format);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400131 va_copy(va2, va);
132
133 // How long is it?
landley00f87f12006-10-25 18:38:37 -0400134 len = vsnprintf(0, 0, format, va);
135 len++;
136 va_end(va);
137
138 // Allocate and do the sprintf()
139 ret = xmalloc(len);
Rob Landley2c226852007-11-15 18:30:30 -0600140 vsnprintf(ret, len, format, va2);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400141 va_end(va2);
landley00f87f12006-10-25 18:38:37 -0400142
143 return ret;
144}
145
Rob Landley24d1d452007-01-20 18:04:20 -0500146void xprintf(char *format, ...)
147{
148 va_list va;
149 va_start(va, format);
150
151 vprintf(format, va);
152 if (ferror(stdout)) perror_exit("write");
153}
154
Rob Landley5084fea2007-06-18 00:14:03 -0400155void xputs(char *s)
156{
157 if (EOF == puts(s)) perror_exit("write");
158}
159
Rob Landley24d1d452007-01-20 18:04:20 -0500160void xputc(char c)
161{
162 if (EOF == fputc(c, stdout)) perror_exit("write");
163}
164
165void xflush(void)
166{
167 if (fflush(stdout)) perror_exit("write");;
168}
169
landleycd9dfc32006-10-18 18:38:16 -0400170// Die unless we can exec argv[] (or run builtin command). Note that anything
171// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500172void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400173{
landleycd9dfc32006-10-18 18:38:16 -0400174 toy_exec(argv);
landley4f344e32006-10-05 16:18:03 -0400175 execvp(argv[0], argv);
176 error_exit("No %s", argv[0]);
177}
178
Rob Landleyd3e9d642007-01-08 03:25:47 -0500179void xaccess(char *path, int flags)
180{
Charlie Shepherd94dd3e72008-01-25 12:54:31 +0000181 if (access(path, flags)) perror_exit("Can't access '%s'", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500182}
183
Rob Landleye745d8e2007-12-20 06:30:19 -0600184// Die unless we can delete a file. (File must exist to be deleted.)
185void xunlink(char *path)
186{
187 if (unlink(path)) perror_exit("unlink '%s'", path);
188}
189
landley4f344e32006-10-05 16:18:03 -0400190// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500191int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400192{
193 int fd = open(path, flags, mode);
Rob Landley961e1712007-11-04 15:31:06 -0600194 if (fd == -1) perror_exit("%s", path);
landley4f344e32006-10-05 16:18:03 -0400195 return fd;
196}
197
Rob Landley1322beb2007-01-07 22:51:12 -0500198// Die unless we can open a file, returning file descriptor.
199int xopen(char *path, int flags)
200{
201 return xcreate(path, flags, 0);
202}
203
Rob Landleybc078652007-12-15 21:47:25 -0600204void xclose(int fd)
205{
206 if (close(fd)) perror_exit("xclose");
207}
208
landley4f344e32006-10-05 16:18:03 -0400209// Die unless we can open/create a file, returning FILE *.
210FILE *xfopen(char *path, char *mode)
211{
212 FILE *f = fopen(path, mode);
Charlie Shepherd94dd3e72008-01-25 12:54:31 +0000213 if (!f) perror_exit("No file %s", path);
landley4f344e32006-10-05 16:18:03 -0400214 return f;
215}
landley00f87f12006-10-25 18:38:37 -0400216
landley64b2e232006-10-30 10:01:19 -0500217// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500218ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500219{
Rob Landley90163772007-01-18 21:54:08 -0500220 size_t count = 0;
221 while (count<len) {
222 int i = read(fd, buf+count, len-count);
landley64b2e232006-10-30 10:01:19 -0500223 if (!i) return len;
224 if (i<0) return i;
225 count += i;
226 }
227
228 return count;
229}
230
Rob Landleyf3e452a2007-01-08 02:49:39 -0500231// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500232ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500233{
Rob Landley90163772007-01-18 21:54:08 -0500234 size_t count = 0;
235 while (count<len) {
236 int i = write(fd, buf+count, len-count);
237 if (i<1) return i;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500238 count += i;
239 }
240
241 return count;
242}
243
Rob Landley055cfcb2007-01-14 20:20:06 -0500244// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500245size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500246{
Rob Landley90163772007-01-18 21:54:08 -0500247 len = read(fd, buf, len);
248 if (len < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500249
Rob Landley90163772007-01-18 21:54:08 -0500250 return len;
Rob Landley055cfcb2007-01-14 20:20:06 -0500251}
252
Rob Landley90163772007-01-18 21:54:08 -0500253void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500254{
Rob Landley90163772007-01-18 21:54:08 -0500255 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500256}
landley00f87f12006-10-25 18:38:37 -0400257
Rob Landley90163772007-01-18 21:54:08 -0500258// There's no xwriteall(), just xwrite(). When we read, there may or may not
259// be more data waiting. When we write, there is data and it had better go
260// somewhere.
261
262void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500263{
Rob Landley90163772007-01-18 21:54:08 -0500264 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500265}
266
landley00f87f12006-10-25 18:38:37 -0400267char *xgetcwd(void)
268{
269 char *buf = getcwd(NULL, 0);
Rob Landley24d1d452007-01-20 18:04:20 -0500270 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500271
272 return buf;
landley00f87f12006-10-25 18:38:37 -0400273}
274
Rob Landleyd25f7e42007-02-03 14:11:26 -0500275void xstat(char *path, struct stat *st)
276{
Rob Landleyf6418542008-01-27 16:22:41 -0600277 if(stat(path, st)) perror_exit("Can't stat %s", path);
Rob Landleyd25f7e42007-02-03 14:11:26 -0500278}
279
Rob Landleyfa98d012006-11-02 02:57:27 -0500280// Cannonicalizes path by removing ".", "..", and "//" elements. This is not
Rob Landleyc6f481c2006-12-30 22:01:47 -0500281// the same as realpath(), where "dir/.." could wind up somewhere else by
282// following symlinks.
Rob Landleyfa98d012006-11-02 02:57:27 -0500283char *xabspath(char *path)
landley00f87f12006-10-25 18:38:37 -0400284{
Rob Landleyfa98d012006-11-02 02:57:27 -0500285 char *from, *to;
landley00f87f12006-10-25 18:38:37 -0400286
Rob Landleyfa98d012006-11-02 02:57:27 -0500287 // If this isn't an absolute path, make it one with cwd.
288 if (path[0]!='/') {
289 char *cwd=xgetcwd();
Rob Landleyf6418542008-01-27 16:22:41 -0600290 path = xmsprintf("%s/%s", cwd, path);
Rob Landleyfa98d012006-11-02 02:57:27 -0500291 free(cwd);
292 } else path = xstrdup(path);
landley00f87f12006-10-25 18:38:37 -0400293
Rob Landleyfa98d012006-11-02 02:57:27 -0500294 // Loop through path elements
295 from = to = path;
296 while (*from) {
297
298 // Continue any current path component.
299 if (*from!='/') {
300 *(to++) = *(from++);
301 continue;
landley00f87f12006-10-25 18:38:37 -0400302 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500303
304 // Skip duplicate slashes.
305 while (*from=='/') from++;
Rob Landley2c226852007-11-15 18:30:30 -0600306
Rob Landleyfa98d012006-11-02 02:57:27 -0500307 // Start of a new filename. Handle . and ..
308 while (*from=='.') {
309 // Skip .
310 if (from[1]=='/') from += 2;
311 else if (!from[1]) from++;
312 // Back up for ..
313 else if (from[1]=='.') {
314 if (from[2]=='/') from +=3;
315 else if(!from[2]) from+=2;
316 else break;
317 while (to>path && *(--to)!='/');
318 } else break;
319 }
320 // Add directory separator slash.
321 *(to++) = '/';
322 }
323 *to = 0;
324
325 return path;
326}
327
Rob Landley35483412007-12-27 21:36:33 -0600328// Ensure entire path exists.
329// If mode != -1 set permissions on newly created dirs.
330// Requires that path string be writable (for temporary null terminators).
331void xmkpath(char *path, int mode)
332{
333 char *p, old;
334 mode_t mask;
335 int rc;
336 struct stat st;
337
338 for (p = path; ; p++) {
339 if (!*p || *p == '/') {
340 old = *p;
341 *p = rc = 0;
342 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
343 if (mode != -1) {
344 mask=umask(0);
345 rc = mkdir(path, mode);
346 umask(mask);
347 } else rc = mkdir(path, 0777);
348 }
349 *p = old;
Rob Landleyf6418542008-01-27 16:22:41 -0600350 if(rc) perror_exit("mkpath '%s'", path);
Rob Landley35483412007-12-27 21:36:33 -0600351 }
352 if (!*p) break;
353 }
354}
Rob Landley0a04b3e2006-11-03 00:05:52 -0500355// Find all file in a colon-separated path with access type "type" (generally
356// X_OK or R_OK). Returns a list of absolute paths to each file found, in
357// order.
358
359struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500360{
Rob Landley0a04b3e2006-11-03 00:05:52 -0500361 struct string_list *rlist = NULL;
362 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500363
364 for (;;) {
365 char *next = path ? index(path, ':') : NULL;
366 int len = next ? next-path : strlen(path);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500367 struct string_list *rnext;
368 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500369
Rob Landley0a04b3e2006-11-03 00:05:52 -0500370 rnext = xmalloc(sizeof(void *) + strlen(filename)
371 + (len ? len : strlen(cwd)) + 2);
372 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500373 else {
Rob Landley0a04b3e2006-11-03 00:05:52 -0500374 char *res = rnext->str;
Rob Landleyfa98d012006-11-02 02:57:27 -0500375 strncpy(res, path, len);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500376 res += len;
377 *(res++) = '/';
378 strcpy(res, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500379 }
380
Rob Landley0a04b3e2006-11-03 00:05:52 -0500381 // Confirm it's not a directory.
382 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
383 rnext->next = rlist;
384 rlist = rnext;
385 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500386
Rob Landleyfa98d012006-11-02 02:57:27 -0500387 if (!next) break;
388 path += len;
389 path++;
landley00f87f12006-10-25 18:38:37 -0400390 }
391 free(cwd);
392
Rob Landley0a04b3e2006-11-03 00:05:52 -0500393 return rlist;
landley00f87f12006-10-25 18:38:37 -0400394}
landley09ea7ac2006-10-30 01:38:00 -0500395
396// Convert unsigned int to ascii, writing into supplied buffer. A truncated
397// result contains the first few digits of the result ala strncpy, and is
398// always null terminated (unless buflen is 0).
399void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
400{
401 int i, out = 0;
402
403 if (buflen) {
404 for (i=1000000000; i; i/=10) {
405 int res = n/i;
406
407 if ((res || out || i == 1) && --buflen>0) {
408 out++;
409 n -= res*i;
410 *buf++ = '0' + res;
411 }
412 }
413 *buf = 0;
414 }
415}
416
417// Convert signed integer to ascii, using utoa_to_buf()
418void itoa_to_buf(int n, char *buf, unsigned buflen)
419{
420 if (buflen && n<0) {
421 n = -n;
422 *buf++ = '-';
423 buflen--;
424 }
425 utoa_to_buf((unsigned)n, buf, buflen);
426}
427
428// This static buffer is used by both utoa() and itoa(), calling either one a
429// second time will overwrite the previous results.
430//
431// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
432// Note that int is always 32 bits on any remotely unix-like system, see
433// http://www.unix.org/whitepapers/64bit.html for details.
434
435static char itoa_buf[12];
436
437// Convert unsigned integer to ascii, returning a static buffer.
438char *utoa(unsigned n)
439{
440 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
441
442 return itoa_buf;
443}
444
445char *itoa(int n)
446{
447 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
448
449 return itoa_buf;
450}
Rob Landley055cfcb2007-01-14 20:20:06 -0500451
Rob Landleyf5757162007-02-16 21:08:22 -0500452// atol() with the kilo/mega/giga/tera/peta/exa extensions.
453// (zetta and yotta don't fit in 64 bits.)
454long atolx(char *c)
455{
456 char *suffixes="kmgtpe", *end;
457 long val = strtol(c, &c, 0);
458
Rob Landley6a6dee32007-11-04 15:32:59 -0600459 if (*c) {
460 end = strchr(suffixes, tolower(*c));
461 if (end) val *= 1024L<<((end-suffixes)*10);
462 }
Rob Landleyf5757162007-02-16 21:08:22 -0500463 return val;
464}
465
Rob Landley055cfcb2007-01-14 20:20:06 -0500466// Return how long the file at fd is, if there's any way to determine it.
467off_t fdlength(int fd)
468{
469 off_t bottom = 0, top = 0, pos;
Rob Landleye2580db2007-01-23 13:20:38 -0500470 int size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500471
472 // If the ioctl works for this, return it.
473
Rob Landleye2580db2007-01-23 13:20:38 -0500474 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500475
476 // If not, do a binary search for the last location we can read. (Some
477 // block devices don't do BLKGETSIZE right.) This should probably have
478 // a CONFIG option...
479
480 do {
481 char temp;
482
483 pos = bottom + (top - bottom) / 2;
484
485 // If we can read from the current location, it's bigger.
486
Rob Landleyb3a33822007-01-25 16:10:37 -0500487 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley055cfcb2007-01-14 20:20:06 -0500488 if (bottom == top) bottom = top = (top+1) * 2;
489 else bottom = pos;
490
491 // If we can't, it's smaller.
492
493 } else {
494 if (bottom == top) {
495 if (!top) return 0;
496 bottom = top/2;
497 } else top = pos;
498 }
499 } while (bottom + 1 != top);
500
501 return pos + 1;
502}
503
Rob Landley0c93f6c2007-04-29 19:55:21 -0400504// This can return null (meaning file not found). It just won't return null
505// for memory allocation reasons.
506char *xreadlink(char *name)
507{
508 int len, size = 0;
509 char *buf = 0;
510
511 // Grow by 64 byte chunks until it's big enough.
512 for(;;) {
513 size +=64;
514 buf = xrealloc(buf, size);
515 len = readlink(name, buf, size);
516
517 if (len<0) {
518 free(buf);
519 return 0;
520 }
521 if (len<size) {
522 buf[len]=0;
523 return buf;
524 }
525 }
526}
527
Rob Landleyb3a33822007-01-25 16:10:37 -0500528/*
529 This might be of use or might not. Unknown yet...
530
Rob Landley055cfcb2007-01-14 20:20:06 -0500531// Read contents of file as a single freshly allocated nul-terminated string.
532char *readfile(char *name)
533{
534 off_t len;
535 int fd;
536 char *buf;
537
Rob Landley2c226852007-11-15 18:30:30 -0600538 fd = open(name, O_RDONLY);
Rob Landley055cfcb2007-01-14 20:20:06 -0500539 if (fd == -1) return 0;
540 len = fdlength(fd);
541 buf = xmalloc(len+1);
542 buf[xread(fd, buf, len)] = 0;
543
544 return buf;
545}
546
547char *xreadfile(char *name)
548{
549 char *buf = readfile(name);
Rob Landley24d1d452007-01-20 18:04:20 -0500550 if (!buf) perror_exit("xreadfile %s", name);
Rob Landley055cfcb2007-01-14 20:20:06 -0500551 return buf;
552}
553
554*/
555
556// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
557// exists and is this executable.
558void xpidfile(char *name)
559{
560 char pidfile[256], spid[32];
561 int i, fd;
562 pid_t pid;
563
564 sprintf(pidfile, "/var/run/%s.pid", name);
565 // Try three times to open the sucker.
566 for (i=0; i<3; i++) {
567 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
568 if (fd != -1) break;
569
570 // If it already existed, read it. Loop for race condition.
571 fd = open(pidfile, O_RDONLY);
572 if (fd == -1) continue;
573
574 // Is the old program still there?
575 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
576 close(fd);
577 pid = atoi(spid);
578 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
579
580 // An else with more sanity checking might be nice here.
581 }
Rob Landley2c226852007-11-15 18:30:30 -0600582
Rob Landley055cfcb2007-01-14 20:20:06 -0500583 if (i == 3) error_exit("xpidfile %s", name);
584
585 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
586 close(fd);
587}
Rob Landley7634b552007-11-29 17:49:50 -0600588
589// Iterate through an array of files, opening each one (read only) and
590// calling a function on that filehandle and name. The special filename
591// "-" means stdin. An empty argument list calls function() on stdin.
592void loopfiles(char **argv, void (*function)(int fd, char *name))
593{
594 int fd;
595
596 // If no arguments, read from stdin.
Rob Landleyce6750a2007-11-29 18:32:20 -0600597 if (!*argv) function(0, "-");
Rob Landley7634b552007-11-29 17:49:50 -0600598 else do {
599 // Filename "-" means read from stdin.
600 // Inability to open a file prints a warning, but doesn't exit.
601
602 if (!strcmp(*argv,"-")) fd=0;
603 else if (0>(fd = open(*argv, O_RDONLY))) {
Rob Landleyf6418542008-01-27 16:22:41 -0600604 perror_msg("%s", *argv);
Rob Landley7634b552007-11-29 17:49:50 -0600605 toys.exitval = 1;
Rob Landley3632d5d2008-01-01 02:39:29 -0600606 continue;
Rob Landley7634b552007-11-29 17:49:50 -0600607 }
608 function(fd, *argv);
609 close(fd);
610 } while (*++argv);
611}
Rob Landleybc078652007-12-15 21:47:25 -0600612
613// Slow, but small.
614
615char *get_rawline(int fd, long *plen)
616{
617 char c, *buf = NULL;
618 long len = 0;
619
620 for (;;) {
621 if (1>read(fd, &c, 1)) break;
622 if (!(len & 63)) buf=xrealloc(buf, len+64);
623 if ((buf[len++]=c) == '\n') break;
624 }
625 if (buf) buf[len]=0;
626 if (plen) *plen = len;
627
628 return buf;
629}
630
631char *get_line(int fd)
632{
633 long len;
634 char *buf = get_rawline(fd, &len);
635
636 if (buf && buf[--len]=='\n') buf[len]=0;
637
638 return buf;
639}
640
641// Copy the rest of in to out and close both files.
642
643void xsendfile(int in, int out)
644{
645 long len;
Rob Landley42ecbab2007-12-18 02:02:21 -0600646 char buf[4096];
Rob Landleybc078652007-12-15 21:47:25 -0600647
648 if (in<0) return;
649 for (;;) {
Rob Landley42ecbab2007-12-18 02:02:21 -0600650 len = xread(in, buf, 4096);
Rob Landleybc078652007-12-15 21:47:25 -0600651 if (len<1) break;
Rob Landley42ecbab2007-12-18 02:02:21 -0600652 xwrite(out, buf, len);
Rob Landleybc078652007-12-15 21:47:25 -0600653 }
Rob Landley42ecbab2007-12-18 02:02:21 -0600654}
655
656// Open a temporary file to copy an existing file into.
657int copy_tempfile(int fdin, char *name, char **tempname)
658{
659 struct stat statbuf;
660 int fd;
661
662 *tempname = xstrndup(name, strlen(name)+6);
663 strcat(*tempname,"XXXXXX");
664 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
665
666 // Set permissions of output file
667
668 fstat(fdin, &statbuf);
669 fchmod(fd, statbuf.st_mode);
670
671 return fd;
672}
673
674// Abort the copy and delete the temporary file.
675void delete_tempfile(int fdin, int fdout, char **tempname)
676{
677 close(fdin);
678 close(fdout);
679 unlink(*tempname);
680 free(*tempname);
681 *tempname = NULL;
682}
683
684// Copy the rest of the data and replace the original with the copy.
685void replace_tempfile(int fdin, int fdout, char **tempname)
686{
687 char *temp = xstrdup(*tempname);
688
689 temp[strlen(temp)-6]=0;
690 if (fdin != -1) {
691 xsendfile(fdin, fdout);
692 xclose(fdin);
693 }
694 xclose(fdout);
695 rename(*tempname, temp);
696 free(*tempname);
697 free(temp);
698 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600699}