"Robert P. J. Day" | 63fc1a9 | 2006-07-02 19:47:05 +0000 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 2 | /* |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 3 | * xreadlink.c - safe implementation of readlink. |
| 4 | * Returns a NULL on failure... |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 5 | */ |
| 6 | |
Denis Vlasenko | a9b60e9 | 2007-01-04 17:59:59 +0000 | [diff] [blame] | 7 | #include "libbb.h" |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 8 | |
| 9 | /* |
| 10 | * NOTE: This function returns a malloced char* that you will have to free |
| 11 | * yourself. You have been warned. |
| 12 | */ |
| 13 | |
Denis Vlasenko | 6ca0444 | 2007-02-11 16:19:28 +0000 | [diff] [blame] | 14 | char *xmalloc_readlink_or_warn(const char *path) |
Tim Riker | c1ef7bd | 2006-01-25 00:08:53 +0000 | [diff] [blame] | 15 | { |
Rob Landley | bc68cd1 | 2006-03-10 19:22:06 +0000 | [diff] [blame] | 16 | enum { GROWBY = 80 }; /* how large we will grow strings by */ |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 17 | |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 18 | char *buf = NULL; |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 19 | int bufsize = 0, readsize = 0; |
| 20 | |
| 21 | do { |
| 22 | buf = xrealloc(buf, bufsize += GROWBY); |
| 23 | readsize = readlink(path, buf, bufsize); /* 1st try */ |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 24 | if (readsize == -1) { |
Glenn L McGrath | 18bbd9b | 2004-08-11 03:50:30 +0000 | [diff] [blame] | 25 | bb_perror_msg("%s", path); |
| 26 | free(buf); |
| 27 | return NULL; |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 28 | } |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 29 | } |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 30 | while (bufsize < readsize + 1); |
| 31 | |
| 32 | buf[readsize] = '\0'; |
| 33 | |
| 34 | return buf; |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 35 | } |
Denis Vlasenko | a9b60e9 | 2007-01-04 17:59:59 +0000 | [diff] [blame] | 36 | |
| 37 | char *xmalloc_realpath(const char *path) |
| 38 | { |
Denis Vlasenko | 218f2f4 | 2007-01-24 22:02:01 +0000 | [diff] [blame] | 39 | #if defined(__GLIBC__) && !defined(__UCLIBC__) |
Denis Vlasenko | a9b60e9 | 2007-01-04 17:59:59 +0000 | [diff] [blame] | 40 | /* glibc provides a non-standard extension */ |
| 41 | return realpath(path, NULL); |
| 42 | #else |
| 43 | char buf[PATH_MAX+1]; |
| 44 | |
| 45 | /* on error returns NULL (xstrdup(NULL) ==NULL) */ |
| 46 | return xstrdup(realpath(path, buf)); |
| 47 | #endif |
| 48 | } |