blob: b0029eef302acfdccea3fe5800574f8627fbedeb [file] [log] [blame]
Rob Landleyd3904932013-07-16 00:04:56 -05001/* xwrap.c - wrappers around existing library functions.
2 *
3 * Functions with the x prefix are wrappers that either succeed or kill the
4 * program with an error message, but never return failure. They usually have
5 * the same arguments and return value as the function they wrap.
6 *
7 * Copyright 2006 Rob Landley <rob@landley.net>
8 */
9
10#include "toys.h"
11
12// Strcpy with size checking: exit if there's not enough space for the string.
13void xstrncpy(char *dest, char *src, size_t size)
14{
15 if (strlen(src)+1 > size) error_exit("xstrcpy");
16 strcpy(dest, src);
17}
18
19void xexit(void)
20{
21 if (toys.rebound) longjmp(*toys.rebound, 1);
22 else exit(toys.exitval);
23}
24
25// Die unless we can allocate memory.
26void *xmalloc(size_t size)
27{
28 void *ret = malloc(size);
29 if (!ret) error_exit("xmalloc");
30
31 return ret;
32}
33
34// Die unless we can allocate prezeroed memory.
35void *xzalloc(size_t size)
36{
37 void *ret = xmalloc(size);
38 memset(ret, 0, size);
39 return ret;
40}
41
42// Die unless we can change the size of an existing allocation, possibly
43// moving it. (Notice different arguments from libc function.)
44void *xrealloc(void *ptr, size_t size)
45{
46 ptr = realloc(ptr, size);
47 if (!ptr) error_exit("xrealloc");
48
49 return ptr;
50}
51
52// Die unless we can allocate a copy of this many bytes of string.
53char *xstrndup(char *s, size_t n)
54{
55 char *ret = xmalloc(++n);
56 strncpy(ret, s, n);
57 ret[--n]=0;
58
59 return ret;
60}
61
62// Die unless we can allocate a copy of this string.
63char *xstrdup(char *s)
64{
65 return xstrndup(s, strlen(s));
66}
67
68// Die unless we can allocate enough space to sprintf() into.
69char *xmsprintf(char *format, ...)
70{
71 va_list va, va2;
72 int len;
73 char *ret;
74
75 va_start(va, format);
76 va_copy(va2, va);
77
78 // How long is it?
79 len = vsnprintf(0, 0, format, va);
80 len++;
81 va_end(va);
82
83 // Allocate and do the sprintf()
84 ret = xmalloc(len);
85 vsnprintf(ret, len, format, va2);
86 va_end(va2);
87
88 return ret;
89}
90
91void xprintf(char *format, ...)
92{
93 va_list va;
94 va_start(va, format);
95
96 vprintf(format, va);
97 if (ferror(stdout)) perror_exit("write");
98}
99
100void xputs(char *s)
101{
102 if (EOF == puts(s) || fflush(stdout)) perror_exit("write");
103}
104
105void xputc(char c)
106{
107 if (EOF == fputc(c, stdout) || fflush(stdout)) perror_exit("write");
108}
109
110void xflush(void)
111{
112 if (fflush(stdout)) perror_exit("write");;
113}
114
115// Die unless we can exec argv[] (or run builtin command). Note that anything
116// with a path isn't a builtin, so /bin/sh won't match the builtin sh.
117void xexec(char **argv)
118{
119 toy_exec(argv);
120 execvp(argv[0], argv);
121
122 perror_exit("exec %s", argv[0]);
123}
124
125void xaccess(char *path, int flags)
126{
127 if (access(path, flags)) perror_exit("Can't access '%s'", path);
128}
129
130// Die unless we can delete a file. (File must exist to be deleted.)
131void xunlink(char *path)
132{
133 if (unlink(path)) perror_exit("unlink '%s'", path);
134}
135
136// Die unless we can open/create a file, returning file descriptor.
137int xcreate(char *path, int flags, int mode)
138{
139 int fd = open(path, flags, mode);
140 if (fd == -1) perror_exit("%s", path);
141 return fd;
142}
143
144// Die unless we can open a file, returning file descriptor.
145int xopen(char *path, int flags)
146{
147 return xcreate(path, flags, 0);
148}
149
150void xclose(int fd)
151{
152 if (close(fd)) perror_exit("xclose");
153}
154
155int xdup(int fd)
156{
157 if (fd != -1) {
158 fd = dup(fd);
159 if (fd == -1) perror_exit("xdup");
160 }
161 return fd;
162}
163
164// Die unless we can open/create a file, returning FILE *.
165FILE *xfopen(char *path, char *mode)
166{
167 FILE *f = fopen(path, mode);
168 if (!f) perror_exit("No file %s", path);
169 return f;
170}
171
172// Die if there's an error other than EOF.
173size_t xread(int fd, void *buf, size_t len)
174{
175 ssize_t ret = read(fd, buf, len);
176 if (ret < 0) perror_exit("xread");
177
178 return ret;
179}
180
181void xreadall(int fd, void *buf, size_t len)
182{
183 if (len != readall(fd, buf, len)) perror_exit("xreadall");
184}
185
186// There's no xwriteall(), just xwrite(). When we read, there may or may not
187// be more data waiting. When we write, there is data and it had better go
188// somewhere.
189
190void xwrite(int fd, void *buf, size_t len)
191{
192 if (len != writeall(fd, buf, len)) perror_exit("xwrite");
193}
194
195// Die if lseek fails, probably due to being called on a pipe.
196
197off_t xlseek(int fd, off_t offset, int whence)
198{
199 offset = lseek(fd, offset, whence);
200 if (offset<0) perror_exit("lseek");
201
202 return offset;
203}
204
205char *xgetcwd(void)
206{
207 char *buf = getcwd(NULL, 0);
208 if (!buf) perror_exit("xgetcwd");
209
210 return buf;
211}
212
213void xstat(char *path, struct stat *st)
214{
215 if(stat(path, st)) perror_exit("Can't stat %s", path);
216}
217
218// Cannonicalize path, even to file with one or more missing components at end.
219// if exact, require last path component to exist
220char *xabspath(char *path, int exact)
221{
222 struct string_list *todo, *done = 0;
223 int try = 9999, dirfd = open("/", 0);;
224 char buf[4096], *ret;
225
226 // If this isn't an absolute path, start with cwd.
227 if (*path != '/') {
228 char *temp = xgetcwd();
229
230 splitpath(path, splitpath(temp, &todo));
231 free(temp);
232 } else splitpath(path, &todo);
233
234 // Iterate through path components
235 while (todo) {
236 struct string_list *new = llist_pop(&todo), **tail;
237 ssize_t len;
238
239 if (!try--) {
240 errno = ELOOP;
241 goto error;
242 }
243
244 // Removable path componenents.
245 if (!strcmp(new->str, ".") || !strcmp(new->str, "..")) {
246 int x = new->str[1];
247
248 free(new);
249 if (x) {
250 if (done) free(llist_pop(&done));
251 len = 0;
252 } else continue;
253
254 // Is this a symlink?
255 } else len=readlinkat(dirfd, new->str, buf, 4096);
256
257 if (len>4095) goto error;
258 if (len<1) {
259 int fd;
260 char *s = "..";
261
262 // For .. just move dirfd
263 if (len) {
264 // Not a symlink: add to linked list, move dirfd, fail if error
265 if ((exact || todo) && errno != EINVAL) goto error;
266 new->next = done;
267 done = new;
268 if (errno == EINVAL && !todo) break;
269 s = new->str;
270 }
271 fd = openat(dirfd, s, 0);
272 if (fd == -1 && (exact || todo || errno != ENOENT)) goto error;
273 close(dirfd);
274 dirfd = fd;
275 continue;
276 }
277
278 // If this symlink is to an absolute path, discard existing resolved path
279 buf[len] = 0;
280 if (*buf == '/') {
281 llist_traverse(done, free);
282 done=0;
283 close(dirfd);
284 dirfd = open("/", 0);
285 }
286 free(new);
287
288 // prepend components of new path. Note symlink to "/" will leave new NULL
289 tail = splitpath(buf, &new);
290
291 // symlink to "/" will return null and leave tail alone
292 if (new) {
293 *tail = todo;
294 todo = new;
295 }
296 }
297 close(dirfd);
298
299 // At this point done has the path, in reverse order. Reverse list while
300 // calculating buffer length.
301
302 try = 2;
303 while (done) {
304 struct string_list *temp = llist_pop(&done);;
305
306 if (todo) try++;
307 try += strlen(temp->str);
308 temp->next = todo;
309 todo = temp;
310 }
311
312 // Assemble return buffer
313
314 ret = xmalloc(try);
315 *ret = '/';
316 ret [try = 1] = 0;
317 while (todo) {
318 if (try>1) ret[try++] = '/';
319 try = stpcpy(ret+try, todo->str) - ret;
320 free(llist_pop(&todo));
321 }
322
323 return ret;
324
325error:
326 close(dirfd);
327 llist_traverse(todo, free);
328 llist_traverse(done, free);
329
330 return NULL;
331}
332
333// Resolve all symlinks, returning malloc() memory.
334char *xrealpath(char *path)
335{
336 char *new = realpath(path, NULL);
337 if (!new) perror_exit("realpath '%s'", path);
338 return new;
339}
340
341void xchdir(char *path)
342{
343 if (chdir(path)) error_exit("chdir '%s'", path);
344}
345
346// Ensure entire path exists.
347// If mode != -1 set permissions on newly created dirs.
348// Requires that path string be writable (for temporary null terminators).
349void xmkpath(char *path, int mode)
350{
351 char *p, old;
352 mode_t mask;
353 int rc;
354 struct stat st;
355
356 for (p = path; ; p++) {
357 if (!*p || *p == '/') {
358 old = *p;
359 *p = rc = 0;
360 if (stat(path, &st) || !S_ISDIR(st.st_mode)) {
361 if (mode != -1) {
362 mask=umask(0);
363 rc = mkdir(path, mode);
364 umask(mask);
365 } else rc = mkdir(path, 0777);
366 }
367 *p = old;
368 if(rc) perror_exit("mkpath '%s'", path);
369 }
370 if (!*p) break;
371 }
372}
373
374// setuid() can fail (for example, too many processes belonging to that user),
375// which opens a security hole if the process continues as the original user.
376
377void xsetuid(uid_t uid)
378{
379 if (setuid(uid)) perror_exit("xsetuid");
380}
381
382// This can return null (meaning file not found). It just won't return null
383// for memory allocation reasons.
384char *xreadlink(char *name)
385{
386 int len, size = 0;
387 char *buf = 0;
388
389 // Grow by 64 byte chunks until it's big enough.
390 for(;;) {
391 size +=64;
392 buf = xrealloc(buf, size);
393 len = readlink(name, buf, size);
394
395 if (len<0) {
396 free(buf);
397 return 0;
398 }
399 if (len<size) {
400 buf[len]=0;
401 return buf;
402 }
403 }
404}
405
406char *xreadfile(char *name)
407{
408 char *buf = readfile(name);
409 if (!buf) perror_exit("xreadfile %s", name);
410 return buf;
411}
412
413int xioctl(int fd, int request, void *data)
414{
415 int rc;
416
417 errno = 0;
418 rc = ioctl(fd, request, data);
419 if (rc == -1 && errno) perror_exit("ioctl %x", request);
420
421 return rc;
422}
423
424// Open a /var/run/NAME.pid file, dying if we can't write it or if it currently
425// exists and is this executable.
426void xpidfile(char *name)
427{
428 char pidfile[256], spid[32];
429 int i, fd;
430 pid_t pid;
431
432 sprintf(pidfile, "/var/run/%s.pid", name);
433 // Try three times to open the sucker.
434 for (i=0; i<3; i++) {
435 fd = open(pidfile, O_CREAT|O_EXCL, 0644);
436 if (fd != -1) break;
437
438 // If it already existed, read it. Loop for race condition.
439 fd = open(pidfile, O_RDONLY);
440 if (fd == -1) continue;
441
442 // Is the old program still there?
443 spid[xread(fd, spid, sizeof(spid)-1)] = 0;
444 close(fd);
445 pid = atoi(spid);
446 if (pid < 1 || kill(pid, 0) == ESRCH) unlink(pidfile);
447
448 // An else with more sanity checking might be nice here.
449 }
450
451 if (i == 3) error_exit("xpidfile %s", name);
452
453 xwrite(fd, spid, sprintf(spid, "%ld\n", (long)getpid()));
454 close(fd);
455}
456
457// Copy the rest of in to out and close both files.
458
459void xsendfile(int in, int out)
460{
461 long len;
462 char buf[4096];
463
464 if (in<0) return;
465 for (;;) {
466 len = xread(in, buf, 4096);
467 if (len<1) break;
468 xwrite(out, buf, len);
469 }
470}