]> git.ozlabs.org Git - ccan/blob - ccan/tal/path/path.c
b50120667c0759649d35292578f627ef644988c3
[ccan] / ccan / tal / path / path.c
1 /* Licensed under BSD-MIT - see LICENSE file for details */
2 #include <ccan/tal/path/path.h>
3 #include <ccan/str/str.h>
4 #include <ccan/tal/str/str.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <limits.h>
10 #include <stdlib.h>
11 #include <errno.h>
12 #include <assert.h>
13
14 char *path_cwd(const tal_t *ctx)
15 {
16         size_t len = 64;
17         char *cwd;
18
19         /* *This* is why people hate C. */
20         cwd = tal_arr(ctx, char, len);
21         while (cwd && !getcwd(cwd, len)) {
22                 if (errno != ERANGE || !tal_resize(&cwd, len *= 2))
23                         cwd = tal_free(cwd);
24         }
25         return cwd;
26 }
27
28 char *path_join(const tal_t *ctx, const char *base, const char *a)
29 {
30         char *ret = NULL;
31         size_t len;
32
33         if (unlikely(!a) && taken(a)) {
34                 if (taken(base))
35                         tal_free(base);
36                 return NULL;
37         }
38
39         if (a[0] == PATH_SEP) {
40                 if (taken(base))
41                         tal_free(base);
42                 return tal_strdup(ctx, a);
43         }
44
45         if (unlikely(!base) && taken(base))
46                 goto out;
47
48         len = strlen(base);
49         ret = tal_dup_arr(ctx, char, base, len, 1 + strlen(a) + 1);
50         if (!ret)
51                 goto out;
52         if (len != 0 && ret[len-1] != PATH_SEP)
53                 ret[len++] = PATH_SEP;
54         strcpy(ret + len, a);
55
56 out:
57         if (taken(a))
58                 tal_free(a);
59         return ret;
60 }
61
62 #if HAVE_FCHDIR
63 struct path_pushd {
64         int fd;
65 };
66
67 static void pushd_destroy(struct path_pushd *pushd)
68 {
69         close(pushd->fd);
70 }
71
72 struct path_pushd *path_pushd(const tal_t *ctx, const char *dir)
73 {
74         struct path_pushd *old = tal(ctx, struct path_pushd);
75
76         if (!old)
77                 return NULL;
78
79         if (unlikely(!dir) && taken(dir))
80                 return tal_free(old);
81
82         if (!tal_add_destructor(old, pushd_destroy))
83                 old = tal_free(old);
84         else {
85                 old->fd = open(".", O_RDONLY);
86                 if (old->fd < 0)
87                         old = tal_free(old);
88                 else if (chdir(dir) != 0)
89                         old = tal_free(old);
90         }
91
92         if (taken(dir))
93                 tal_free(dir);
94         return old;
95 }
96
97 bool path_popd(struct path_pushd *olddir)
98 {
99         bool ok = (fchdir(olddir->fd) == 0);
100
101         tal_free(olddir);
102         return ok;
103 }
104 #else
105 struct path_pushd {
106         const char *olddir;
107 };
108
109 struct path_pushd *path_pushd(const tal_t *ctx, const char *dir)
110 {
111         struct path_pushd *old = tal(ctx, struct path_pushd);
112
113         if (!old)
114                 return NULL;
115
116         old->olddir = path_cwd(old);
117         if (unlikely(!old->olddir))
118                 old = tal_free(old);
119         else if (unlikely(!dir) && is_taken(dir))
120                 old = tal_free(old);
121         else if (chdir(dir) != 0)
122                 old = tal_free(old);
123
124         if (taken(dir))
125                 tal_free(dir);
126
127         return old;
128 }
129
130 bool path_popd(struct path_pushd *olddir)
131 {
132         bool ok = (chdir(olddir->olddir) == 0);
133
134         tal_free(olddir);
135         return ok;
136 }
137 #endif /* !HAVE_FCHDIR */
138
139 char *path_canon(const tal_t *ctx, const char *a)
140 {
141 #if 0
142         char *oldcwd, *path, *p;
143         void *tmpctx;
144         size_t len;
145         struct path_pushd *olddir;
146
147         /* A good guess as to size. */
148         len = strlen(a) + 1;
149         if (a[0] != PATH_SEP) {
150                 tmpctx = oldcwd = path_cwd(ctx);
151                 if (!oldcwd)
152                         return NULL;
153                 len += strlen(oldcwd) + strlen(PATH_SEP_STR);
154
155                 path = tal_array(tmpctx, char, len);
156                 if (!path)
157                         goto out;
158
159                 len = strlen(oldcwd);
160                 memcpy(path, oldcwd, len);
161                 path[len++] = PATH_SEP;
162         } else {
163                 tmpctx = path = tal_array(ctx, char, len);
164                 if (!path)
165                         return NULL;
166                 len = 0;
167         }
168         strcpy(path + len, a);
169
170         p = strrchr(path, PATH_SEP);
171         *p = '\0';
172
173         olddir = path_pushd(tmpctx, path);
174         if (!olddir)
175                 goto out;
176
177         /* Make OS canonicalize path for us. */
178         path = path_cwd(tmpctx);
179         if (!path)
180                 goto out;
181
182         /* Append rest of old path. */
183         len = strlen(p+1);
184         if (len) {
185                 size_t oldlen = tal_array_length(path);
186                 if (path[oldlen-1] != PATH_SEP) {
187                         /* Include / to append. */
188                         *p = PATH_SEP;
189                         p--;
190                         len++;
191                 }
192                 path = tal_realloc(NULL, path, char, oldlen+len+1);
193                 if (!path)
194                         goto out;
195                 memcpy(path + oldlen, p, len+1);
196         }
197
198         path = tal_steal(ctx, path);
199 out:
200         /* This can happen if old cwd is deleted. */
201         if (!path_popd(olddir))
202                 path = tal_free(path);
203
204         tal_free(tmpctx);
205         return path;
206 #else
207         char *path;
208         if (unlikely(!a) && is_taken(a))
209                 path = NULL;
210         else {
211                 path = tal_arr(ctx, char, PATH_MAX);
212                 if (path && !realpath(a, path))
213                         path = tal_free(path);
214         }
215         if (taken(a))
216                 tal_free(a);
217         return path;
218 #endif
219 }
220
221 /* Symlinks make this hard! */
222 char *path_rel(const tal_t *ctx, const char *from, const char *to)
223 {
224         char *cfrom, *cto, *ret, *p;
225         tal_t *tmpctx;
226         size_t common, num_back, i, postlen;
227
228         /* This frees from if we're supposed to take it. */
229         tmpctx = cfrom = path_canon(ctx, from);
230         if (!cfrom)
231                 goto fail_take_to;
232
233         /* From is a directory, so we append / to it. */
234         if (!streq(cfrom, PATH_SEP_STR)) {
235                 if (!tal_resize(&cfrom, strlen(cfrom)+2))
236                         goto fail_take_to;
237                 tmpctx = cfrom;
238                 strcat(cfrom, PATH_SEP_STR);
239         }
240
241         /* This frees to if we're supposed to take it. */
242         cto = path_canon(tmpctx, to);
243         if (!cto) {
244                 ret = NULL;
245                 goto out;
246         }
247
248         /* How much is in common? */
249         for (common = i = 0; cfrom[i] && cto[i]; i++) {
250                 if (cfrom[i] != cto[i])
251                         break;
252                 if (cfrom[i] == PATH_SEP)
253                         common = i + 1;
254         }
255
256         /* Skip over / if matches end of other path.  */
257         if (!cfrom[i] && cto[i] == PATH_SEP) {
258                 cto++;
259                 common = i;
260         } else if (!cto[i] && cfrom[i] == PATH_SEP) {
261                 cfrom++;
262                 common = i;
263         }
264
265         /* Normalize so strings point past common area. */
266         cfrom += common;
267         cto += common;
268
269         /* One .. for every path element remaining in 'from', to get
270          * back to common prefix.  Then the rest of 'to'. */
271         num_back = strcount(cfrom, PATH_SEP_STR);
272         postlen = strlen(cto) + 1;
273
274         /* Nothing left?  That's ".". */
275         if (num_back == 0 && postlen == 1) {
276                 ret = tal_strdup(ctx, ".");
277                 goto out;
278         }
279
280         ret = tal_arr(ctx, char,
281                       strlen(".." PATH_SEP_STR) * num_back + postlen);
282         if (!ret)
283                 goto out;
284
285         for (i = 0, p = ret; i < num_back; i++, p += strlen(".." PATH_SEP_STR))
286                 memcpy(p, ".." PATH_SEP_STR, strlen(".." PATH_SEP_STR));
287         /* Nothing to append?  Trim the final / */
288         if (postlen == 1)
289                 p--;
290         memcpy(p, cto, postlen);
291
292 out:
293         tal_free(tmpctx);
294         return ret;
295
296 fail_take_to:
297         if (taken(to))
298                 tal_free(to);
299         ret = NULL;
300         goto out;
301 }
302
303  char *path_readlink(const tal_t *ctx, const char *linkname)
304  {
305         ssize_t len, maxlen = 64; /* good first guess. */
306         char *ret = NULL;
307
308         if (unlikely(!linkname) && is_taken(linkname))
309                 goto fail;
310
311         ret = tal_arr(ctx, char, maxlen + 1);
312
313         while (ret) {
314                 len = readlink(linkname, ret, maxlen);
315                 if (len < 0)
316                         goto fail;
317                 if (len < maxlen)
318                         break;
319
320                 if (!tal_resize(&ret, maxlen *= 2 + 1))
321                         goto fail;
322         }
323
324         if (ret)
325                 ret[len] = '\0';
326
327 out:
328         if (taken(linkname))
329                 tal_free(linkname);
330
331         return ret;
332
333 fail:
334         ret = tal_free(ret);
335         goto out;
336 }
337
338 char *path_simplify(const tal_t *ctx, const char *path)
339 {
340         size_t i, j, start, len;
341         char *ret;
342         bool ended = false;
343
344         ret = tal_strdup(ctx, path);
345         if (!ret)
346                 return NULL;
347
348         /* Always need first / if there is one. */
349         if (ret[0] == PATH_SEP)
350                 start = 1;
351         else
352                 start = 0;
353
354         for (i = j = start; !ended; i += len) {
355                 /* Get length of this segment, including terminator. */
356                 for (len = 0; ret[i+len] != PATH_SEP; len++) {
357                         if (!ret[i+len]) {
358                                 ended = true;
359                                 break;
360                         }
361                 }
362                 len++;
363
364                 /* Empty segment is //; ignore first one. */
365                 if (len == 1)
366                         continue;
367
368                 /* Always ignore slashdot. */
369                 if (len == 2 && ret[i] == '.')
370                         continue;
371
372                 /* .. => remove previous if there is one, unless symlink. */
373                 if (len == 3 && ret[i] == '.' && ret[i+1] == '.') {
374                         struct stat st;
375
376                         if (j > start) {
377                                 /* eg. /foo/, foo/ or foo/bar/ */
378                                 assert(ret[j-1] == PATH_SEP);
379                                 ret[j-1] = '\0';
380
381                                 /* Avoid stepping back over ..! */
382                                 if (streq(ret, "..")
383                                     || strends(ret, PATH_SEP_STR"..")) {
384                                         ret[j-1] = PATH_SEP;
385                                         goto copy;
386                                 }
387
388                                 if (lstat(ret, &st) == 0
389                                     && !S_ISLNK(st.st_mode)) {
390                                         char *sep = strrchr(ret, PATH_SEP);
391                                         if (sep)
392                                                 j = sep - ret + 1;
393                                         else
394                                                 j = 0;
395                                 }
396                                 continue;
397                         } else if (start) {
398                                 /* /.. => / */
399                                 j = 1;
400                                 /* nul term in case we're at end */
401                                 ret[1] = '\0';
402                                 continue;
403                         }
404                 }
405
406         copy:
407                 memmove(ret + j, ret + i, len);
408                 /* Don't count nul terminator. */
409                 j += len - ended;
410         }
411
412         /* Empty string created by ../ elimination. */
413         if (j == 0) {
414                 ret[0] = '.';
415                 ret[1] = '\0';
416         } else if (j > 1 && ret[j-1] == PATH_SEP) {
417                 ret[j-1] = '\0';
418         } else
419                 ret[j] = '\0';
420
421         return ret;
422 }
423
424 char *path_basename(const tal_t *ctx, const char *path)
425 {
426         const char *sep;
427         char *ret;
428
429         if (unlikely(!path) && taken(path))
430                 return NULL;
431
432         sep = strrchr(path, PATH_SEP);
433         if (!sep)
434                 return tal_strdup(ctx, path);
435
436         /* Trailing slashes need to be trimmed. */
437         if (!sep[1]) {
438                 const char *end;
439
440                 for (end = sep; end != path; end--)
441                         if (*end != PATH_SEP)
442                                 break;
443
444                 /* Find *previous* / */
445                 for (sep = end; sep >= path && *sep != PATH_SEP; sep--);
446
447                 /* All /?  Just return / */
448                 if (end == sep)
449                         ret = tal_strdup(ctx, PATH_SEP_STR);
450                 else
451                         ret = tal_strndup(ctx, sep+1, end - sep);
452         } else
453                 ret = tal_strdup(ctx, sep + 1);
454
455         if (taken(path))
456                 tal_free(path);
457         return ret;
458 }
459
460 /* This reuses str if we're to take it. */
461 static char *fixed_string(const tal_t *ctx,
462                           const char *str, const char *path)
463 {
464         char *ret = tal_dup_arr(ctx, char, path, 0, strlen(str)+1);
465         if (ret)
466                 strcpy(ret, str);
467         return ret;
468 }
469
470 char *path_dirname(const tal_t *ctx, const char *path)
471 {
472         const char *sep;
473
474         if (unlikely(!path) && taken(path))
475                 return NULL;
476
477         sep = strrchr(path, PATH_SEP);
478         if (!sep)
479                 return fixed_string(ctx, ".", path);
480
481         /* Trailing slashes need to be trimmed. */
482         if (!sep[1]) {
483                 const char *end;
484
485                 for (end = sep; end != path; end--)
486                         if (*end != PATH_SEP)
487                                 break;
488
489                 /* Find *previous* / */
490                 for (sep = end; sep > path && *sep != PATH_SEP; sep--);
491         }
492
493         /* In case there are multiple / in a row. */
494         while (sep > path && sep[-1] == PATH_SEP)
495                 sep--;
496
497         if (sep == path) {
498                 if (path_is_abs(path))
499                         return tal_strndup(ctx, path, 1);
500                 else
501                         return fixed_string(ctx, ".", path);
502         }
503         return tal_strndup(ctx, path, sep - path);
504 }
505
506 bool path_is_abs(const char *path)
507 {
508         return path[0] == PATH_SEP;
509 }
510
511 bool path_is_file(const char *path)
512 {
513         struct stat st;
514
515         return stat(path, &st) == 0 && S_ISREG(st.st_mode);
516 }
517
518 bool path_is_dir(const char *path)
519 {
520         struct stat st;
521
522         return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
523 }
524
525 char **path_split(const tal_t *ctx, const char *path)
526 {
527         bool empty = path && !path[0];
528         char **ret = tal_strsplit(ctx, path, PATH_SEP_STR, STR_NO_EMPTY);
529
530         /* Handle the "/" case */
531         if (ret && !empty && !ret[0]) {
532                 if (!tal_resize(&ret, 2))
533                         ret = tal_free(ret);
534                 else {
535                         ret[1] = NULL;
536                         ret[0] = tal_strdup(ret, PATH_SEP_STR);
537                         if (!ret[0])
538                                 ret = tal_free(ret);
539                 }
540         }
541
542         return ret;
543 }
544
545 size_t path_ext_off(const char *path)
546 {
547         const char *dot, *base;
548
549         dot = strrchr(path, '.');
550         if (dot) {
551                 base = strrchr(path, PATH_SEP);
552                 if (!base)
553                         base = path;
554                 else
555                         base++;
556                 if (dot > base)
557                         return dot - path;
558         }
559         return strlen(path);
560 }