]> git.ozlabs.org Git - ccan/blob - ccan/tal/path/path.c
0ad168c872d219d3b485e23d53d39ab430d40eb7
[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/take/take.h>
5 #include <ccan/tal/str/str.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <limits.h>
11 #include <stdlib.h>
12 #include <errno.h>
13 #include <assert.h>
14
15 #define PATH_SEP_STR "/"
16 #define PATH_SEP (PATH_SEP_STR[0])
17
18 char *path_cwd(const tal_t *ctx)
19 {
20         size_t len = 64;
21         char *cwd;
22
23         /* *This* is why people hate C. */
24         cwd = tal_arr(ctx, char, len);
25         while (cwd && !getcwd(cwd, len)) {
26                 if (errno != ERANGE || !tal_resize(&cwd, len *= 2))
27                         cwd = tal_free(cwd);
28         }
29         return cwd;
30 }
31
32 char *path_join(const tal_t *ctx, const char *base, const char *a)
33 {
34         char *ret = NULL;
35         size_t len;
36
37         if (unlikely(!a) && taken(a)) {
38                 if (taken(base))
39                         tal_free(base);
40                 return NULL;
41         }
42
43         if (a[0] == PATH_SEP) {
44                 if (taken(base))
45                         tal_free(base);
46                 return tal_strdup(ctx, a);
47         }
48
49         if (unlikely(!base) && taken(base))
50                 goto out;
51
52         len = strlen(base);
53         ret = tal_dup(ctx, char, base, len, 1 + strlen(a) + 1);
54         if (!ret)
55                 goto out;
56         if (ret[len-1] != PATH_SEP)
57                 ret[len++] = PATH_SEP;
58         strcpy(ret + len, a);
59
60 out:
61         if (taken(a))
62                 tal_free(a);
63         return ret;
64 }
65
66 #if HAVE_FCHDIR
67 struct path_pushd {
68         int fd;
69 };
70
71 static void pushd_destroy(struct path_pushd *pushd)
72 {
73         close(pushd->fd);
74 }
75
76 struct path_pushd *path_pushd(const tal_t *ctx, const char *dir)
77 {
78         struct path_pushd *old = tal(ctx, struct path_pushd);
79
80         if (!old)
81                 return NULL;
82
83         if (unlikely(!dir) && taken(dir))
84                 return tal_free(old);
85
86         if (!tal_add_destructor(old, pushd_destroy))
87                 old = tal_free(old);
88         else {
89                 old->fd = open(".", O_RDONLY);
90                 if (old->fd < 0)
91                         old = tal_free(old);
92                 else if (chdir(dir) != 0)
93                         old = tal_free(old);
94         }
95
96         if (taken(dir))
97                 tal_free(dir);
98         return old;
99 }
100
101 bool path_popd(struct path_pushd *olddir)
102 {
103         bool ok = (fchdir(olddir->fd) == 0);
104
105         tal_free(olddir);
106         return ok;
107 }
108 #else
109 struct path_pushd {
110         const char *olddir;
111 };
112
113 struct path_pushd *path_pushd(const tal_t *ctx, const char *dir)
114 {
115         struct path_pushd *old = tal(ctx, struct path_pushd);
116
117         if (!old)
118                 return NULL;
119
120         old->olddir = path_cwd(old);
121         if (unlikely(!old->olddir))
122                 old = tal_free(old);
123         else if (unlikely(!dir) && is_taken(dir))
124                 old = tal_free(old);
125         else if (chdir(dir) != 0)
126                 old = tal_free(old);
127
128         if (taken(dir))
129                 tal_free(dir);
130
131         return old;
132 }
133
134 bool path_popd(struct path_pushd *olddir)
135 {
136         bool ok = (chdir(olddir->olddir) == 0);
137
138         tal_free(olddir);
139         return ok;
140 }
141 #endif /* !HAVE_FCHDIR */
142
143 char *path_canon(const tal_t *ctx, const char *a)
144 {
145 #if 0
146         char *oldcwd, *path, *p;
147         void *tmpctx;
148         size_t len;
149         struct path_pushd *olddir;
150
151         /* A good guess as to size. */
152         len = strlen(a) + 1;
153         if (a[0] != PATH_SEP) {
154                 tmpctx = oldcwd = path_cwd(ctx);
155                 if (!oldcwd)
156                         return NULL;
157                 len += strlen(oldcwd) + strlen(PATH_SEP_STR);
158
159                 path = tal_array(tmpctx, char, len);
160                 if (!path)
161                         goto out;
162
163                 len = strlen(oldcwd);
164                 memcpy(path, oldcwd, len);
165                 path[len++] = PATH_SEP;
166         } else {
167                 tmpctx = path = tal_array(ctx, char, len);
168                 if (!path)
169                         return NULL;
170                 len = 0;
171         }
172         strcpy(path + len, a);
173
174         p = strrchr(path, PATH_SEP);
175         *p = '\0';
176
177         olddir = path_pushd(tmpctx, path);
178         if (!olddir)
179                 goto out;
180
181         /* Make OS canonicalize path for us. */
182         path = path_cwd(tmpctx);
183         if (!path)
184                 goto out;
185
186         /* Append rest of old path. */
187         len = strlen(p+1);
188         if (len) {
189                 size_t oldlen = tal_array_length(path);
190                 if (path[oldlen-1] != PATH_SEP) {
191                         /* Include / to append. */
192                         *p = PATH_SEP;
193                         p--;
194                         len++;
195                 }
196                 path = tal_realloc(NULL, path, char, oldlen+len+1);
197                 if (!path)
198                         goto out;
199                 memcpy(path + oldlen, p, len+1);
200         }
201
202         path = tal_steal(ctx, path);
203 out:
204         /* This can happen if old cwd is deleted. */
205         if (!path_popd(olddir))
206                 path = tal_free(path);
207
208         tal_free(tmpctx);
209         return path;
210 #else
211         char *path;
212         if (unlikely(!a) && is_taken(a))
213                 path = NULL;
214         else {
215                 path = tal_arr(ctx, char, PATH_MAX);
216                 if (path && !realpath(a, path))
217                         path = tal_free(path);
218         }
219         if (taken(a))
220                 tal_free(a);
221         return path;
222 #endif
223 }
224
225 /* Symlinks make this hard! */
226 char *path_rel(const tal_t *ctx, const char *from, const char *to)
227 {
228         char *cfrom, *cto, *ret, *p;
229         tal_t *tmpctx;
230         size_t common, num_back, i, postlen;
231
232         /* This frees from if we're supposed to take it. */
233         tmpctx = cfrom = path_canon(ctx, from);
234         if (!cfrom)
235                 goto fail_take_to;
236
237         /* From is a directory, so we append / to it. */
238         if (!streq(cfrom, PATH_SEP_STR)) {
239                 if (!tal_resize(&cfrom, strlen(cfrom)+2))
240                         goto fail_take_to;
241                 tmpctx = cfrom;
242                 strcat(cfrom, PATH_SEP_STR);
243         }
244
245         /* This frees to if we're supposed to take it. */
246         cto = path_canon(tmpctx, to);
247         if (!cto)
248                 goto out;
249
250         /* How much is in common? */
251         for (common = i = 0; cfrom[i] && cto[i]; i++) {
252                 if (cfrom[i] != cto[i])
253                         break;
254                 if (cfrom[i] == PATH_SEP)
255                         common = i + 1;
256         }
257
258         /* Skip over / if matches end of other path.  */
259         if (!cfrom[i] && cto[i] == PATH_SEP) {
260                 cto++;
261                 common = i;
262         } else if (!cto[i] && cfrom[i] == PATH_SEP) {
263                 cfrom++;
264                 common = i;
265         }
266
267         /* Normalize so strings point past common area. */
268         cfrom += common;
269         cto += common;
270
271         /* One .. for every path element remaining in 'from', to get
272          * back to common prefix.  Then the rest of 'to'. */
273         num_back = strcount(cfrom, PATH_SEP_STR);
274         postlen = strlen(cto) + 1;
275
276         /* Nothing left?  That's ".". */
277         if (num_back == 0 && postlen == 1) {
278                 ret = tal_strdup(ctx, ".");
279                 goto out;
280         }
281
282         ret = tal_arr(ctx, char,
283                       strlen(".." PATH_SEP_STR) * num_back + postlen);
284         if (!ret)
285                 goto out;
286
287         for (i = 0, p = ret; i < num_back; i++, p += strlen(".." PATH_SEP_STR))
288                 memcpy(p, ".." PATH_SEP_STR, strlen(".." PATH_SEP_STR));
289         /* Nothing to append?  Trim the final / */
290         if (postlen == 1)
291                 p--;
292         memcpy(p, cto, postlen);
293
294 out:
295         tal_free(tmpctx);
296         return ret;
297
298 fail_take_to:
299         if (taken(to))
300                 tal_free(to);
301         ret = NULL;
302         goto out;
303 }
304
305  char *path_readlink(const tal_t *ctx, const char *linkname)
306  {
307         ssize_t len, maxlen = 64; /* good first guess. */
308         char *ret = NULL;
309
310         if (unlikely(!linkname) && is_taken(linkname))
311                 goto fail;
312
313         ret = tal_arr(ctx, char, maxlen + 1);
314
315         while (ret) {
316                 len = readlink(linkname, ret, maxlen);
317                 if (len < 0)
318                         goto fail;
319                 if (len < maxlen)
320                         break;
321
322                 if (!tal_resize(&ret, maxlen *= 2 + 1))
323                         goto fail;
324         }
325
326         ret[len] = '\0';
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(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 = 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 }