blob: 6102e1b4e97f68fe3e8295a4d28e8035d756f9d8 [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{
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500111 char *ret = xmalloc(++n);
112 strncpy(ret, s, n);
113 ret[--n]=0;
Rob Landley2c226852007-11-15 18:30:30 -0600114
landley4f344e32006-10-05 16:18:03 -0400115 return ret;
116}
117
Rob Landleyfa98d012006-11-02 02:57:27 -0500118// Die unless we can allocate a copy of this string.
119void *xstrdup(char *s)
120{
Rob Landleyf6418542008-01-27 16:22:41 -0600121 return xstrndup(s, strlen(s));
Rob Landleyfa98d012006-11-02 02:57:27 -0500122}
123
landley00f87f12006-10-25 18:38:37 -0400124// Die unless we can allocate enough space to sprintf() into.
125char *xmsprintf(char *format, ...)
126{
Rob Landley0d8dfb22007-06-15 15:16:46 -0400127 va_list va, va2;
landley00f87f12006-10-25 18:38:37 -0400128 int len;
129 char *ret;
Rob Landley2c226852007-11-15 18:30:30 -0600130
landley00f87f12006-10-25 18:38:37 -0400131 va_start(va, format);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400132 va_copy(va2, va);
133
134 // How long is it?
landley00f87f12006-10-25 18:38:37 -0400135 len = vsnprintf(0, 0, format, va);
136 len++;
137 va_end(va);
138
139 // Allocate and do the sprintf()
140 ret = xmalloc(len);
Rob Landley2c226852007-11-15 18:30:30 -0600141 vsnprintf(ret, len, format, va2);
Rob Landley0d8dfb22007-06-15 15:16:46 -0400142 va_end(va2);
landley00f87f12006-10-25 18:38:37 -0400143
144 return ret;
145}
146
Rob Landley24d1d452007-01-20 18:04:20 -0500147void xprintf(char *format, ...)
148{
149 va_list va;
150 va_start(va, format);
151
152 vprintf(format, va);
153 if (ferror(stdout)) perror_exit("write");
154}
155
Rob Landley5084fea2007-06-18 00:14:03 -0400156void xputs(char *s)
157{
158 if (EOF == puts(s)) perror_exit("write");
159}
160
Rob Landley24d1d452007-01-20 18:04:20 -0500161void xputc(char c)
162{
163 if (EOF == fputc(c, stdout)) perror_exit("write");
164}
165
166void xflush(void)
167{
168 if (fflush(stdout)) perror_exit("write");;
169}
170
landleycd9dfc32006-10-18 18:38:16 -0400171// Die unless we can exec argv[] (or run builtin command). Note that anything
172// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
landley09ea7ac2006-10-30 01:38:00 -0500173void xexec(char **argv)
landley4f344e32006-10-05 16:18:03 -0400174{
landleycd9dfc32006-10-18 18:38:16 -0400175 toy_exec(argv);
landley4f344e32006-10-05 16:18:03 -0400176 execvp(argv[0], argv);
177 error_exit("No %s", argv[0]);
178}
179
Rob Landleyd3e9d642007-01-08 03:25:47 -0500180void xaccess(char *path, int flags)
181{
Charlie Shepherd94dd3e72008-01-25 12:54:31 +0000182 if (access(path, flags)) perror_exit("Can't access '%s'", path);
Rob Landleyd3e9d642007-01-08 03:25:47 -0500183}
184
Rob Landleye745d8e2007-12-20 06:30:19 -0600185// Die unless we can delete a file. (File must exist to be deleted.)
186void xunlink(char *path)
187{
188 if (unlink(path)) perror_exit("unlink '%s'", path);
189}
190
landley4f344e32006-10-05 16:18:03 -0400191// Die unless we can open/create a file, returning file descriptor.
Rob Landley1322beb2007-01-07 22:51:12 -0500192int xcreate(char *path, int flags, int mode)
landley4f344e32006-10-05 16:18:03 -0400193{
194 int fd = open(path, flags, mode);
Rob Landley961e1712007-11-04 15:31:06 -0600195 if (fd == -1) perror_exit("%s", path);
landley4f344e32006-10-05 16:18:03 -0400196 return fd;
197}
198
Rob Landley1322beb2007-01-07 22:51:12 -0500199// Die unless we can open a file, returning file descriptor.
200int xopen(char *path, int flags)
201{
202 return xcreate(path, flags, 0);
203}
204
Rob Landleybc078652007-12-15 21:47:25 -0600205void xclose(int fd)
206{
207 if (close(fd)) perror_exit("xclose");
208}
209
landley4f344e32006-10-05 16:18:03 -0400210// Die unless we can open/create a file, returning FILE *.
211FILE *xfopen(char *path, char *mode)
212{
213 FILE *f = fopen(path, mode);
Charlie Shepherd94dd3e72008-01-25 12:54:31 +0000214 if (!f) perror_exit("No file %s", path);
landley4f344e32006-10-05 16:18:03 -0400215 return f;
216}
landley00f87f12006-10-25 18:38:37 -0400217
landley64b2e232006-10-30 10:01:19 -0500218// Keep reading until full or EOF
Rob Landley90163772007-01-18 21:54:08 -0500219ssize_t readall(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500220{
Rob Landley90163772007-01-18 21:54:08 -0500221 size_t count = 0;
222 while (count<len) {
223 int i = read(fd, buf+count, len-count);
landley64b2e232006-10-30 10:01:19 -0500224 if (!i) return len;
225 if (i<0) return i;
226 count += i;
227 }
228
229 return count;
230}
231
Rob Landleyf3e452a2007-01-08 02:49:39 -0500232// Keep writing until done or EOF
Rob Landley90163772007-01-18 21:54:08 -0500233ssize_t writeall(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500234{
Rob Landley90163772007-01-18 21:54:08 -0500235 size_t count = 0;
236 while (count<len) {
237 int i = write(fd, buf+count, len-count);
238 if (i<1) return i;
Rob Landleyf3e452a2007-01-08 02:49:39 -0500239 count += i;
240 }
241
242 return count;
243}
244
Rob Landley055cfcb2007-01-14 20:20:06 -0500245// Die if there's an error other than EOF.
Rob Landley90163772007-01-18 21:54:08 -0500246size_t xread(int fd, void *buf, size_t len)
landley64b2e232006-10-30 10:01:19 -0500247{
Rob Landley90163772007-01-18 21:54:08 -0500248 len = read(fd, buf, len);
249 if (len < 0) perror_exit("xread");
Rob Landley055cfcb2007-01-14 20:20:06 -0500250
Rob Landley90163772007-01-18 21:54:08 -0500251 return len;
Rob Landley055cfcb2007-01-14 20:20:06 -0500252}
253
Rob Landley90163772007-01-18 21:54:08 -0500254void xreadall(int fd, void *buf, size_t len)
Rob Landley055cfcb2007-01-14 20:20:06 -0500255{
Rob Landley90163772007-01-18 21:54:08 -0500256 if (len != readall(fd, buf, len)) perror_exit("xreadall");
Rob Landley055cfcb2007-01-14 20:20:06 -0500257}
landley00f87f12006-10-25 18:38:37 -0400258
Rob Landley90163772007-01-18 21:54:08 -0500259// There's no xwriteall(), just xwrite(). When we read, there may or may not
260// be more data waiting. When we write, there is data and it had better go
261// somewhere.
262
263void xwrite(int fd, void *buf, size_t len)
Rob Landleyf3e452a2007-01-08 02:49:39 -0500264{
Rob Landley90163772007-01-18 21:54:08 -0500265 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
Rob Landleyf3e452a2007-01-08 02:49:39 -0500266}
267
landley00f87f12006-10-25 18:38:37 -0400268char *xgetcwd(void)
269{
270 char *buf = getcwd(NULL, 0);
Rob Landley24d1d452007-01-20 18:04:20 -0500271 if (!buf) perror_exit("xgetcwd");
landley09ea7ac2006-10-30 01:38:00 -0500272
273 return buf;
landley00f87f12006-10-25 18:38:37 -0400274}
275
Rob Landleyd25f7e42007-02-03 14:11:26 -0500276void xstat(char *path, struct stat *st)
277{
Rob Landleyf6418542008-01-27 16:22:41 -0600278 if(stat(path, st)) perror_exit("Can't stat %s", path);
Rob Landleyd25f7e42007-02-03 14:11:26 -0500279}
280
Rob Landleyfa98d012006-11-02 02:57:27 -0500281// Cannonicalizes path by removing ".", "..", and "//" elements. This is not
Rob Landleyc6f481c2006-12-30 22:01:47 -0500282// the same as realpath(), where "dir/.." could wind up somewhere else by
283// following symlinks.
Rob Landleyfa98d012006-11-02 02:57:27 -0500284char *xabspath(char *path)
landley00f87f12006-10-25 18:38:37 -0400285{
Rob Landleyfa98d012006-11-02 02:57:27 -0500286 char *from, *to;
landley00f87f12006-10-25 18:38:37 -0400287
Rob Landleyfa98d012006-11-02 02:57:27 -0500288 // If this isn't an absolute path, make it one with cwd.
289 if (path[0]!='/') {
290 char *cwd=xgetcwd();
Rob Landleyf6418542008-01-27 16:22:41 -0600291 path = xmsprintf("%s/%s", cwd, path);
Rob Landleyfa98d012006-11-02 02:57:27 -0500292 free(cwd);
293 } else path = xstrdup(path);
landley00f87f12006-10-25 18:38:37 -0400294
Rob Landleyfa98d012006-11-02 02:57:27 -0500295 // Loop through path elements
296 from = to = path;
297 while (*from) {
298
299 // Continue any current path component.
300 if (*from!='/') {
301 *(to++) = *(from++);
302 continue;
landley00f87f12006-10-25 18:38:37 -0400303 }
Rob Landleyfa98d012006-11-02 02:57:27 -0500304
305 // Skip duplicate slashes.
306 while (*from=='/') from++;
Rob Landley2c226852007-11-15 18:30:30 -0600307
Rob Landleyfa98d012006-11-02 02:57:27 -0500308 // Start of a new filename. Handle . and ..
309 while (*from=='.') {
310 // Skip .
311 if (from[1]=='/') from += 2;
312 else if (!from[1]) from++;
313 // Back up for ..
314 else if (from[1]=='.') {
315 if (from[2]=='/') from +=3;
316 else if(!from[2]) from+=2;
317 else break;
318 while (to>path && *(--to)!='/');
319 } else break;
320 }
321 // Add directory separator slash.
322 *(to++) = '/';
323 }
324 *to = 0;
325
326 return path;
327}
328
Rob Landley35483412007-12-27 21:36:33 -0600329// Ensure entire path exists.
330// If mode != -1 set permissions on newly created dirs.
331// Requires that path string be writable (for temporary null terminators).
332void xmkpath(char *path, int mode)
333{
334 char *p, old;
335 mode_t mask;
336 int rc;
337 struct stat st;
338
339 for (p = path; ; p++) {
340 if (!*p || *p == '/') {
341 old = *p;
342 *p = rc = 0;
343 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
344 if (mode != -1) {
345 mask=umask(0);
346 rc = mkdir(path, mode);
347 umask(mask);
348 } else rc = mkdir(path, 0777);
349 }
350 *p = old;
Rob Landleyf6418542008-01-27 16:22:41 -0600351 if(rc) perror_exit("mkpath '%s'", path);
Rob Landley35483412007-12-27 21:36:33 -0600352 }
353 if (!*p) break;
354 }
355}
Rob Landley0a04b3e2006-11-03 00:05:52 -0500356// Find all file in a colon-separated path with access type "type" (generally
357// X_OK or R_OK). Returns a list of absolute paths to each file found, in
358// order.
359
360struct string_list *find_in_path(char *path, char *filename)
Rob Landleyfa98d012006-11-02 02:57:27 -0500361{
Rob Landley0a04b3e2006-11-03 00:05:52 -0500362 struct string_list *rlist = NULL;
363 char *cwd = xgetcwd();
Rob Landleyfa98d012006-11-02 02:57:27 -0500364
365 for (;;) {
366 char *next = path ? index(path, ':') : NULL;
367 int len = next ? next-path : strlen(path);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500368 struct string_list *rnext;
369 struct stat st;
Rob Landleyfa98d012006-11-02 02:57:27 -0500370
Rob Landley0a04b3e2006-11-03 00:05:52 -0500371 rnext = xmalloc(sizeof(void *) + strlen(filename)
372 + (len ? len : strlen(cwd)) + 2);
373 if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500374 else {
Rob Landley0a04b3e2006-11-03 00:05:52 -0500375 char *res = rnext->str;
Rob Landleyfa98d012006-11-02 02:57:27 -0500376 strncpy(res, path, len);
Rob Landley0a04b3e2006-11-03 00:05:52 -0500377 res += len;
378 *(res++) = '/';
379 strcpy(res, filename);
Rob Landleyfa98d012006-11-02 02:57:27 -0500380 }
381
Rob Landley0a04b3e2006-11-03 00:05:52 -0500382 // Confirm it's not a directory.
383 if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
384 rnext->next = rlist;
385 rlist = rnext;
386 } else free(rnext);
Rob Landleyfa98d012006-11-02 02:57:27 -0500387
Rob Landleyfa98d012006-11-02 02:57:27 -0500388 if (!next) break;
389 path += len;
390 path++;
landley00f87f12006-10-25 18:38:37 -0400391 }
392 free(cwd);
393
Rob Landley0a04b3e2006-11-03 00:05:52 -0500394 return rlist;
landley00f87f12006-10-25 18:38:37 -0400395}
landley09ea7ac2006-10-30 01:38:00 -0500396
397// Convert unsigned int to ascii, writing into supplied buffer. A truncated
398// result contains the first few digits of the result ala strncpy, and is
399// always null terminated (unless buflen is 0).
400void utoa_to_buf(unsigned n, char *buf, unsigned buflen)
401{
402 int i, out = 0;
403
404 if (buflen) {
405 for (i=1000000000; i; i/=10) {
406 int res = n/i;
407
408 if ((res || out || i == 1) && --buflen>0) {
409 out++;
410 n -= res*i;
411 *buf++ = '0' + res;
412 }
413 }
414 *buf = 0;
415 }
416}
417
418// Convert signed integer to ascii, using utoa_to_buf()
419void itoa_to_buf(int n, char *buf, unsigned buflen)
420{
421 if (buflen && n<0) {
422 n = -n;
423 *buf++ = '-';
424 buflen--;
425 }
426 utoa_to_buf((unsigned)n, buf, buflen);
427}
428
429// This static buffer is used by both utoa() and itoa(), calling either one a
430// second time will overwrite the previous results.
431//
432// The longest 32 bit integer is -2 billion plus a null terminator: 12 bytes.
433// Note that int is always 32 bits on any remotely unix-like system, see
434// http://www.unix.org/whitepapers/64bit.html for details.
435
436static char itoa_buf[12];
437
438// Convert unsigned integer to ascii, returning a static buffer.
439char *utoa(unsigned n)
440{
441 utoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
442
443 return itoa_buf;
444}
445
446char *itoa(int n)
447{
448 itoa_to_buf(n, itoa_buf, sizeof(itoa_buf));
449
450 return itoa_buf;
451}
Rob Landley055cfcb2007-01-14 20:20:06 -0500452
Rob Landleyf5757162007-02-16 21:08:22 -0500453// atol() with the kilo/mega/giga/tera/peta/exa extensions.
454// (zetta and yotta don't fit in 64 bits.)
455long atolx(char *c)
456{
457 char *suffixes="kmgtpe", *end;
458 long val = strtol(c, &c, 0);
459
Rob Landley6a6dee32007-11-04 15:32:59 -0600460 if (*c) {
461 end = strchr(suffixes, tolower(*c));
462 if (end) val *= 1024L<<((end-suffixes)*10);
463 }
Rob Landleyf5757162007-02-16 21:08:22 -0500464 return val;
465}
466
Rob Landley055cfcb2007-01-14 20:20:06 -0500467// Return how long the file at fd is, if there's any way to determine it.
468off_t fdlength(int fd)
469{
470 off_t bottom = 0, top = 0, pos;
Rob Landleye2580db2007-01-23 13:20:38 -0500471 int size;
Rob Landley055cfcb2007-01-14 20:20:06 -0500472
473 // If the ioctl works for this, return it.
474
Rob Landleye2580db2007-01-23 13:20:38 -0500475 if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
Rob Landley055cfcb2007-01-14 20:20:06 -0500476
477 // If not, do a binary search for the last location we can read. (Some
478 // block devices don't do BLKGETSIZE right.) This should probably have
479 // a CONFIG option...
480
481 do {
482 char temp;
483
484 pos = bottom + (top - bottom) / 2;
485
486 // If we can read from the current location, it's bigger.
487
Rob Landleyb3a33822007-01-25 16:10:37 -0500488 if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
Rob Landley055cfcb2007-01-14 20:20:06 -0500489 if (bottom == top) bottom = top = (top+1) * 2;
490 else bottom = pos;
491
492 // If we can't, it's smaller.
493
494 } else {
495 if (bottom == top) {
496 if (!top) return 0;
497 bottom = top/2;
498 } else top = pos;
499 }
500 } while (bottom + 1 != top);
501
502 return pos + 1;
503}
504
Rob Landley0c93f6c2007-04-29 19:55:21 -0400505// This can return null (meaning file not found). It just won't return null
506// for memory allocation reasons.
507char *xreadlink(char *name)
508{
509 int len, size = 0;
510 char *buf = 0;
511
512 // Grow by 64 byte chunks until it's big enough.
513 for(;;) {
514 size +=64;
515 buf = xrealloc(buf, size);
516 len = readlink(name, buf, size);
517
518 if (len<0) {
519 free(buf);
520 return 0;
521 }
522 if (len<size) {
523 buf[len]=0;
524 return buf;
525 }
526 }
527}
528
Rob Landleyb3a33822007-01-25 16:10:37 -0500529/*
530 This might be of use or might not. Unknown yet...
531
Rob Landley055cfcb2007-01-14 20:20:06 -0500532// Read contents of file as a single freshly allocated nul-terminated string.
533char *readfile(char *name)
534{
535 off_t len;
536 int fd;
537 char *buf;
538
Rob Landley2c226852007-11-15 18:30:30 -0600539 fd = open(name, O_RDONLY);
Rob Landley055cfcb2007-01-14 20:20:06 -0500540 if (fd == -1) return 0;
541 len = fdlength(fd);
542 buf = xmalloc(len+1);
543 buf[xread(fd, buf, len)] = 0;
544
545 return buf;
546}
547
548char *xreadfile(char *name)
549{
550 char *buf = readfile(name);
Rob Landley24d1d452007-01-20 18:04:20 -0500551 if (!buf) perror_exit("xreadfile %s", name);
Rob Landley055cfcb2007-01-14 20:20:06 -0500552 return buf;
553}
554
555*/
556
557// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
558// exists and is this executable.
559void xpidfile(char *name)
560{
561 char pidfile[256], spid[32];
562 int i, fd;
563 pid_t pid;
564
565 sprintf(pidfile, "/var/run/%s.pid", name);
566 // Try three times to open the sucker.
567 for (i=0; i<3; i++) {
568 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
569 if (fd != -1) break;
570
571 // If it already existed, read it. Loop for race condition.
572 fd = open(pidfile, O_RDONLY);
573 if (fd == -1) continue;
574
575 // Is the old program still there?
576 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
577 close(fd);
578 pid = atoi(spid);
579 if (fd < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
580
581 // An else with more sanity checking might be nice here.
582 }
Rob Landley2c226852007-11-15 18:30:30 -0600583
Rob Landley055cfcb2007-01-14 20:20:06 -0500584 if (i == 3) error_exit("xpidfile %s", name);
585
586 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
587 close(fd);
588}
Rob Landley7634b552007-11-29 17:49:50 -0600589
590// Iterate through an array of files, opening each one (read only) and
591// calling a function on that filehandle and name. The special filename
592// "-" means stdin. An empty argument list calls function() on stdin.
593void loopfiles(char **argv, void (*function)(int fd, char *name))
594{
595 int fd;
596
597 // If no arguments, read from stdin.
Rob Landleyce6750a2007-11-29 18:32:20 -0600598 if (!*argv) function(0, "-");
Rob Landley7634b552007-11-29 17:49:50 -0600599 else do {
600 // Filename "-" means read from stdin.
601 // Inability to open a file prints a warning, but doesn't exit.
602
603 if (!strcmp(*argv,"-")) fd=0;
604 else if (0>(fd = open(*argv, O_RDONLY))) {
Rob Landleyf6418542008-01-27 16:22:41 -0600605 perror_msg("%s", *argv);
Rob Landley7634b552007-11-29 17:49:50 -0600606 toys.exitval = 1;
Rob Landley3632d5d2008-01-01 02:39:29 -0600607 continue;
Rob Landley7634b552007-11-29 17:49:50 -0600608 }
609 function(fd, *argv);
610 close(fd);
611 } while (*++argv);
612}
Rob Landleybc078652007-12-15 21:47:25 -0600613
614// Slow, but small.
615
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500616char *get_rawline(int fd, long *plen, char end)
Rob Landleybc078652007-12-15 21:47:25 -0600617{
618 char c, *buf = NULL;
619 long len = 0;
620
621 for (;;) {
622 if (1>read(fd, &c, 1)) break;
623 if (!(len & 63)) buf=xrealloc(buf, len+64);
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500624 if ((buf[len++]=c) == end) break;
Rob Landleybc078652007-12-15 21:47:25 -0600625 }
626 if (buf) buf[len]=0;
627 if (plen) *plen = len;
628
629 return buf;
630}
631
632char *get_line(int fd)
633{
634 long len;
Rob Landley3fc4e0f2008-04-13 00:29:00 -0500635 char *buf = get_rawline(fd, &len, '\n');
Rob Landleybc078652007-12-15 21:47:25 -0600636
637 if (buf && buf[--len]=='\n') buf[len]=0;
638
639 return buf;
640}
641
642// Copy the rest of in to out and close both files.
643
644void xsendfile(int in, int out)
645{
646 long len;
Rob Landley42ecbab2007-12-18 02:02:21 -0600647 char buf[4096];
Rob Landleybc078652007-12-15 21:47:25 -0600648
649 if (in<0) return;
650 for (;;) {
Rob Landley42ecbab2007-12-18 02:02:21 -0600651 len = xread(in, buf, 4096);
Rob Landleybc078652007-12-15 21:47:25 -0600652 if (len<1) break;
Rob Landley42ecbab2007-12-18 02:02:21 -0600653 xwrite(out, buf, len);
Rob Landleybc078652007-12-15 21:47:25 -0600654 }
Rob Landley42ecbab2007-12-18 02:02:21 -0600655}
656
657// Open a temporary file to copy an existing file into.
658int copy_tempfile(int fdin, char *name, char **tempname)
659{
660 struct stat statbuf;
661 int fd;
662
663 *tempname = xstrndup(name, strlen(name)+6);
664 strcat(*tempname,"XXXXXX");
665 if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
666
667 // Set permissions of output file
668
669 fstat(fdin, &statbuf);
670 fchmod(fd, statbuf.st_mode);
671
672 return fd;
673}
674
675// Abort the copy and delete the temporary file.
676void delete_tempfile(int fdin, int fdout, char **tempname)
677{
678 close(fdin);
679 close(fdout);
680 unlink(*tempname);
681 free(*tempname);
682 *tempname = NULL;
683}
684
685// Copy the rest of the data and replace the original with the copy.
686void replace_tempfile(int fdin, int fdout, char **tempname)
687{
688 char *temp = xstrdup(*tempname);
689
690 temp[strlen(temp)-6]=0;
691 if (fdin != -1) {
692 xsendfile(fdin, fdout);
693 xclose(fdin);
694 }
695 xclose(fdout);
696 rename(*tempname, temp);
697 free(*tempname);
698 free(temp);
699 *tempname = NULL;
Rob Landleybc078652007-12-15 21:47:25 -0600700}