Debian Codegraph @

texk/kpathsea/elt-dirs.c

raw
1 /* elt-dirs.c: Translate a path element to its corresponding director{y,ies}.
2
3 Copyright 1993, 1994, 1995, 1996, 1997, 2008, 2009, 2010, 2011, 2016,
4 2017, 2018, 2025 Karl Berry.
5 Copyright 1997, 1998, 1999, 2000, 2005 Olaf Weber.
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with this library; if not, see <http://www.gnu.org/licenses/>. */
19
20 #include <kpathsea/config.h>
21
22 #include <kpathsea/c-pathch.h>
23 #include <kpathsea/expand.h>
24 #include <kpathsea/fn.h>
25 #include <kpathsea/pathsearch.h>
26 #include <kpathsea/variable.h>
27 #include <kpathsea/xopendir.h>
28
29 /* To avoid giving prototypes for all the routines and then their real
30 definitions, we give all the subroutines first. The entry point is
31 the last routine in the file. */
32
33 /* Make a copy of DIR (unless it's null) and save it in L. Ensure that
34 DIR ends with a DIR_SEP for the benefit of later searches. */
35
36 static void
37 dir_list_add (str_llist_type *l, string dir)
38 {
39 char last_char = dir[strlen (dir) - 1];
40 string saved_dir
41 = IS_DIR_SEP_CH (last_char) || IS_DEVICE_SEP (last_char)
42 ? xstrdup (dir)
43 : concat (dir, DIR_SEP_STRING);
44
45 str_llist_add (l, saved_dir);
46 }
47
48
49 /* If DIR is a directory, add it to the list L. */
50
51 static void
52 checked_dir_list_add (kpathsea kpse, str_llist_type *l, string dir)
53 {
54 if (kpathsea_dir_p (kpse, dir))
55 dir_list_add (l, dir);
56 }
57
58 /* The cache. Typically, several paths have the same element; for
59 example, /usr/local/lib/texmf/fonts//. We don't want to compute the
60 expansion of such a thing more than once. Even though we also cache
61 the dir_links call, that's not enough -- without this path element
62 caching as well, the execution time doubles. */
63
64 /* Associate KEY with VALUE. We implement the cache as a simple linear
65 list, since it's unlikely to ever be more than a dozen or so elements
66 long. We don't bother to check here if PATH has already been saved;
67 we always add it to our list. We copy KEY but not VALUE; not sure
68 that's right, but it seems to be all that's needed. */
69
70 static void
71 cache (kpathsea kpse, const_string key, str_llist_type *value)
72 {
73 kpse->cache_length++;
74 XRETALLOC (kpse->the_cache, kpse->cache_length, cache_entry);
75 kpse->the_cache[kpse->cache_length - 1].key = xstrdup (key);
76 kpse->the_cache[kpse->cache_length - 1].value = value;
77 }
78
79
80 /* To retrieve, just check the list in order. */
81
82 static str_llist_type *
83 cached (kpathsea kpse, const_string key)
84 {
85 unsigned p;
86
87 for (p = 0; p < kpse->cache_length; p++)
88 {
89 if (FILESTRCASEEQ (kpse->the_cache[p].key, key))
90 return kpse->the_cache[p].value;
91 }
92
93 return NULL;
94 }
95
96 /* Handle the magic path constructs. */
97
98 /* Declare recursively called routine. */
99 static void expand_elt (kpathsea, str_llist_type *, string, unsigned);
100
101
102 /* POST is a pointer into the original element (which may no longer be
103 ELT) to just after the doubled DIR_SEP, perhaps to the null. Append
104 subdirectories of ELT (up to ELT_LENGTH, which must be a /) to
105 STR_LIST_PTR. ELT must not be the empty string (or NULL). */
106
107 #ifdef WIN32
108 /* Shared across recursive calls, it acts like a stack. */
109 static char dirname[MAX_PATH*2];
110 static wchar_t dirnamew[MAX_PATH];
111 static char *potname;
112 #endif
113
114 static void
115 do_subdir (kpathsea kpse, str_llist_type *str_list_ptr, string elt,
116 unsigned elt_length, string post)
117 {
118 #ifdef WIN32
119 WIN32_FIND_DATAW find_file_data;
120 HANDLE hnd;
121 int proceed;
122 int nlinks = 2;
123 #else
124 DIR *dir;
125 struct dirent *e;
126 #endif /* not WIN32 */
127 fn_type name;
128
129 /* Some old compilers don't allow aggregate initialization. */
130 name = fn_copy0 (elt, elt_length);
131
132 assert (elt_length > 0
133 && (IS_DIR_SEP_CH (elt[elt_length - 1])
134 || IS_DEVICE_SEP (elt[elt_length - 1])));
135
136 #if defined (WIN32)
137 strcpy(dirname, FN_STRING(name));
138 strcat(dirname, "/*.*"); /* "*.*" or "*" -- seems equivalent. */
139 get_wstring_from_mbstring(kpse->File_system_codepage, dirname, dirnamew);
140 hnd = FindFirstFileW(dirnamew, &find_file_data);
141
142 if (hnd == INVALID_HANDLE_VALUE) {
143 fn_free(&name);
144 return;
145 }
146
147 /* Include top level before subdirectories, if nothing to match. */
148 if (*post == 0)
149 dir_list_add (str_list_ptr, FN_STRING (name));
150 else {
151 /* If we do have something to match, see if it exists. For
152 example, POST might be `pk/ljfour', and they might have a
153 directory `$TEXMF/fonts/pk/ljfour' that we should find. */
154 fn_str_grow (&name, post);
155 expand_elt (kpse, str_list_ptr, FN_STRING (name), elt_length);
156 fn_shrink_to (&name, elt_length);
157 }
158 proceed = 1;
159 while (proceed) {
160 if (find_file_data.cFileName[0] != L'.') {
161 int links;
162
163 /* Construct the potential subdirectory name. */
164 potname = get_mbstring_from_wstring(kpse->File_system_codepage, find_file_data.cFileName, potname=NULL);
165 fn_str_grow (&name, potname);
166 free(potname);
167
168 /* Maybe we have cached the leafness of this directory.
169 The function will return 0 if unknown,
170 else the actual (Unix-like) value. */
171 links = kpathsea_dir_links (kpse, FN_STRING (name), 0);
172
173 if (find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
174 unsigned potential_len = FN_LENGTH (name);
175 /* in any case, compute the leafness */
176 nlinks++;
177
178 /* It's a directory, so append the separator. */
179 fn_str_grow (&name, DIR_SEP_STRING);
180 if (*post != 0) {
181 fn_str_grow (&name, post);
182 /* Unfortunately we can't check if the new element is
183 a leaf directory, because we don't have a directory
184 name here, we just have a path spec. This means we
185 may descend into a leaf directory cm/pk, if the
186 spec is ...fonts//pk//. */
187 expand_elt (kpse, str_list_ptr, FN_STRING (name), potential_len);
188 fn_shrink_to (&name, potential_len);
189 }
190 /* Should we recurse? To see if the subdirectory is a
191 leaf, check if it has two links (one for . and one for
192 ..). This means that symbolic links to directories do
193 not affect the leaf-ness. This is arguably wrong, but
194 the only alternative I know of is to stat every entry
195 in the directory, and that is unacceptably slow. */
196
197 if (links == 0 || links > 2)
198 /* All criteria are met; find subdirectories. */
199 do_subdir (kpse, str_list_ptr, FN_STRING (name),
200 potential_len, post);
201 else if (*post == 0)
202 /* Nothing to match, no recursive subdirectories to
203 look for: we're done with this branch. Add it. */
204 dir_list_add (str_list_ptr, FN_STRING (name));
205 }
206 fn_shrink_to (&name, elt_length);
207 }
208 proceed = FindNextFileW (hnd, &find_file_data);
209 }
210 /* Update the leafness of name. */
211 kpathsea_dir_links(kpse, FN_STRING(name), nlinks);
212 fn_free (&name);
213 FindClose(hnd);
214
215 #else /* not WIN32 */
216
217 /* If we can't open it, quit. */
218 dir = opendir (FN_STRING (name));
219 if (dir == NULL)
220 {
221 fn_free (&name);
222 return;
223 }
224
225 /* Include top level before subdirectories, if nothing to match. */
226 if (*post == 0)
227 dir_list_add (str_list_ptr, FN_STRING (name));
228 else
229 { /* If we do have something to match, see if it exists. For
230 example, POST might be `pk/ljfour', and they might have a
231 directory `$TEXMF/fonts/pk/ljfour' that we should find. */
232 fn_str_grow (&name, post);
233 expand_elt (kpse, str_list_ptr, FN_STRING (name), elt_length);
234 fn_shrink_to (&name, elt_length);
235 }
236
237 while ((e = readdir (dir)) != NULL)
238 { /* If it begins with a `.', never mind. (This allows ``hidden''
239 directories that the algorithm won't find.) */
240 if (e->d_name[0] != '.')
241 {
242 int links;
243
244 /* Construct the potential subdirectory name. */
245 fn_str_grow (&name, e->d_name);
246
247 /* If we can't stat it, or if it isn't a directory, continue. */
248 links = kpathsea_dir_links (kpse, FN_STRING (name), 0);
249
250 if (links >= 0)
251 {
252 unsigned potential_len = FN_LENGTH (name);
253
254 /* It's a directory, so append the separator. */
255 fn_str_grow (&name, DIR_SEP_STRING);
256
257 if (*post != 0)
258 {
259 fn_str_grow (&name, post);
260 /* Unfortunately we can't check if the new element is
261 a leaf directory, because we don't have a directory
262 name here, we just have a path spec. This means we
263 may descend into a leaf directory cm/pk, if the
264 spec is ...fonts//pk//. */
265 expand_elt (kpse, str_list_ptr, FN_STRING (name),
266 potential_len);
267 fn_shrink_to (&name, potential_len);
268 }
269
270 /* Should we recurse? To see if the subdirectory is a
271 leaf, check if it has two links (one for . and one for
272 ..). This means that symbolic links to directories do
273 not affect the leaf-ness. This is arguably wrong, but
274 the only alternative I know of is to stat every entry
275 in the directory, and that is unacceptably slow.
276
277 The #ifdef here makes all this configurable at
278 compile-time, so that if we're using VMS directories or
279 some such, we can still find subdirectories.
280
281 We also have a runtime configuration setting, since
282 even regular Unix systems where the st_link trick would
283 normally work, can have overlay filesystems where it fails
284 (https://tug.org/pipermail/texhax/2025-July/026771.html);
285 and also if users like to make symlinks to subdirs,
286 they might want to disable it
287 (https://tex.stackexchange.com/questions/132908). */
288
289 #ifdef ST_NLINK_TRICK
290 /* With SAS/C++ 6.55 on the Amiga, stat sets the st_nlink
291 field to -1 for a file, or to 1 for a directory.
292 Cygwin 1.7 also leaves st_nlink as 1:
293 http://cygwin.com/ml/cygwin-developers/2008-04/msg00110.html
294 The gvisor sandboxing package also left it at 1, until 2025:
295 https://github.com/google/gvisor/issues/11925
296 The btrfs filesystem also leaves it at 1:
297 https://tug.org/pipermail/tex-k/2025-October/004212.html
298 */
299 if (links != 2 || !kpse_cnf_p (kpathsea_var_value
300 (kpse, "texmf_nlink_for_leaf"))
301 ) {
302 #endif /* ST_NLINK_TRICK */
303 /* All criteria are met; find subdirectories. */
304 #ifdef KPSE_DEBUG
305 if (KPATHSEA_DEBUG_P (KPSE_DEBUG_EXPAND))
306 DEBUGF1 ("do_subdir: recursing into subdir: %s\n", name);
307 #endif /* KPSE_DEBUG */
308 do_subdir (kpse, str_list_ptr, FN_STRING (name),
309 potential_len, post);
310 #ifdef ST_NLINK_TRICK
311 } else if (*post == 0) {
312 /* Nothing to match, no recursive subdirectories to
313 look for: we're done with this branch. Add it. */
314 dir_list_add (str_list_ptr, FN_STRING (name));
315 #ifdef KPSE_DEBUG
316 if (KPATHSEA_DEBUG_P (KPSE_DEBUG_EXPAND))
317 DEBUGF1 ("do_subdir: done with subdir, adding: %s\n", name);
318 #endif /* KPSE_DEBUG */
319 }
320 #endif /* ST_NLINK_TRICK */
321 }
322
323 /* Remove the directory entry we just checked from `name'. */
324 fn_shrink_to (&name, elt_length);
325 }
326 }
327
328 fn_free (&name);
329 xclosedir (dir);
330 #endif /* not WIN32 */
331 }
332
333
334 /* Assume ELT is non-empty and non-NULL. Return list of corresponding
335 directories (with no terminating NULL entry) in STR_LIST_PTR. Start
336 looking for magic constructs at START. */
337
338 static void
339 expand_elt (kpathsea kpse, str_llist_type * str_list_ptr, string elt,
340 unsigned start)
341 {
342 string dir = elt + start, post;
343
344 while (*dir != 0)
345 {
346 if (IS_DIR_SEP_CH (*dir))
347 {
348 /* If two or more consecutive /'s, find subdirectories. */
349 if (IS_DIR_SEP_CH (dir[1]))
350 {
351 for (post = dir + 1; IS_DIR_SEP_CH (*post); post++) ;
352 do_subdir (kpse, str_list_ptr, elt, dir - elt + 1, post);
353 return;
354 }
355
356 /* No special stuff at this slash. Keep going. */
357 }
358
359 dir++;
360 }
361
362 /* When we reach the end of ELT, it will be a normal filename. */
363 checked_dir_list_add (kpse, str_list_ptr, elt);
364 }
365
366 /* On win32 we slashify ELT, i.e., change '\\' to '/', and then can use
367 IS_DIR_SEP_CH instead of IS_DIR_SEP and need not test for the presence
368 of 2-Byte Kanji (CP 932, SJIS) codes. */
369
370 /* The first bits of a path element can be problematic because they
371 look like a request to expand a whole disk, rather than a subtree.
372 - It can contain a drive specification.
373 - It can be a UNC path (w32, but they are part of the single
374 Unix specification as well).
375 The argument is a string as the function can diddle into the argument
376 to canonicalize it, which tends to matter on windows platforms.
377 - Always lower-case drive letters a-z, even those filesystem that
378 preserve case in filenames do not care about the case of the drive
379 letters.
380 - Remove unneeded double slashes. The problem is Windows does not
381 handle well filenames like c://dir/foo. So canonicalize the names.
382 The resulting name will always be shorter than the one passed, so no
383 problem.
384 - Remove multiple leading slashes to prevent expanding from the root
385 of a UNIX filesystem tree. */
386
387 unsigned
388 kpathsea_normalize_path (kpathsea kpse, string elt)
389 {
390 unsigned ret;
391 unsigned i;
392
393 #if defined(WIN32)
394 for (i = 0; elt[i]; i++) {
395 if (elt[i] == '\\')
396 elt[i] = '/';
397 else if (kpathsea_IS_KANJI(kpse, elt + i))
398 i++;
399 }
400 #endif
401
402 if (NAME_BEGINS_WITH_DEVICE(elt)) {
403 if (*elt >= 'A' && *elt <= 'Z')
404 *elt += 'a' - 'A';
405 ret = 2;
406
407 } else if (IS_UNC_NAME(elt)) {
408 for (ret = 2; elt[ret] && !IS_DIR_SEP_CH(elt[ret]); ret++)
409 ;
410
411 } else
412 ret = 0;
413
414 for (i = ret; IS_DIR_SEP_CH(elt[i]); ++i)
415 ;
416 if (i > ret + 1) {
417 #ifdef KPSE_DEBUG
418 if (KPATHSEA_DEBUG_P (KPSE_DEBUG_STAT))
419 DEBUGF2 ("kpse_normalize_path (%s) => %u\n", elt, ret);
420 #endif /* KPSE_DEBUG */
421 memmove (elt + ret + 1, elt + i, strlen (elt + i) + 1);
422 }
423
424 return ret;
425 }
426
427 /* Here is the entry point. Returns directory list for ELT. */
428
429 str_llist_type *
430 kpathsea_element_dirs (kpathsea kpse, string elt)
431 {
432 str_llist_type *ret;
433 unsigned i;
434
435 #ifdef _WIN32
436 char *tname = NULL;
437 wchar_t *wtname = NULL;
438 #endif /* _WIN32 */
439
440 /* If given nothing, return nothing. */
441 if (!elt || !*elt)
442 return NULL;
443
444 #ifdef _WIN32
445 /*
446 Change encoding of a variable into kpse->File_system_codepage
447 to support non-ascii values for the variable.
448 */
449 if (kpse->File_system_codepage != kpse->Win32_codepage) {
450 wtname = get_wstring_from_mbstring (kpse->Win32_codepage,
451 elt, wtname = NULL);
452 tname = get_mbstring_from_wstring (kpse->File_system_codepage,
453 wtname, tname = NULL);
454 elt = tname;
455 free(wtname);
456 }
457 #endif /* _WIN32 */
458
459 /* Normalize ELT before looking for a cached value. */
460 i = kpathsea_normalize_path (kpse, elt);
461
462 /* If we've already cached the answer for ELT, return it. */
463 ret = cached (kpse, elt);
464 #ifdef _WIN32
465 if (ret) {
466 if (tname) free (tname);
467 return ret;
468 }
469 #else
470 if (ret)
471 return ret;
472 #endif /* _WIN32 */
473
474 /* We're going to have a real directory list to return. */
475 ret = XTALLOC1 (str_llist_type);
476 *ret = NULL;
477
478 /* We handle the hard case in a subroutine. */
479 expand_elt (kpse, ret, elt, i);
480
481 /* Remember the directory list we just found, in case future calls are
482 made with the same ELT. */
483 cache (kpse, elt, ret);
484
485 #ifdef KPSE_DEBUG
486 if (KPATHSEA_DEBUG_P (KPSE_DEBUG_EXPAND))
487 {
488 DEBUGF1 ("kpathsea_element_dirs: path element %s =>", elt);
489 if (ret)
490 {
491 str_llist_elt_type *e;
492 for (e = *ret; e; e = STR_LLIST_NEXT (*e))
493 fprintf (stderr, " %s", STR_LLIST (*e));
494 }
495 putc ('\n', stderr);
496 fflush (stderr);
497 }
498 #endif /* KPSE_DEBUG */
499
500 #ifdef _WIN32
501 if (tname) free (tname);
502 #endif /* _WIN32 */
503
504 return ret;
505 }
506
507 #ifdef TEST
508
509 void
510 print_element_dirs (const_string elt)
511 {
512 str_llist_type *dirs;
513
514 printf ("Directories of %s:\t", elt ? elt : "(nil)");
515 fflush (stdout);
516
517 dirs = kpathsea_element_dirs (kpse_def, elt);
518
519 if (!dirs)
520 printf ("(nil)");
521 else
522 {
523 str_llist_elt_type *dir;
524 for (dir = *dirs; dir; dir = STR_LLIST_NEXT (*dir))
525 {
526 string d = STR_LLIST (*dir);
527 printf ("%s ", *d ? d : "`'");
528 }
529 }
530
531 putchar ('\n');
532 }
533
534 int
535 main ()
536 {
537 /* DEBUG_SET (DEBUG_STAT); */
538 /* All lists end with NULL. */
539 print_element_dirs (NULL); /* */
540 print_element_dirs (""); /* ./ */
541 print_element_dirs ("/k"); /* */
542 print_element_dirs (".//"); /* ./ ./archive/ */
543 print_element_dirs (".//archive"); /* ./ ./archive/ */
544 #ifdef AMIGA
545 print_element_dirs ("TeXMF:AmiWeb2c/texmf/fonts//"); /* lots */
546 print_element_dirs ("TeXMF:AmiWeb2c/share/texmf/fonts//bakoma"); /*just one*/
547 print_element_dirs ("TeXMF:AmiWeb2c/texmf/fonts//"); /* lots again [cache] */
548 print_element_dirs ("TeXMF:"); /* TeXMF: */
549 print_element_dirs ("TeXMF:/"); /* TeXMF: and all subdirs */
550 #else /* not AMIGA */
551 print_element_dirs ("/tmp/fonts//"); /* no need to stat anything */
552 print_element_dirs ("/usr/local/lib/tex/fonts//"); /* lots */
553 print_element_dirs ("/usr/local/lib/tex/fonts//times"); /* just one */
554 print_element_dirs ("/usr/local/lib/tex/fonts//"); /* lots again [cache] */
555 print_element_dirs ("~karl"); /* tilde expansion */
556 print_element_dirs ("$karl"); /* variable expansion */
557 print_element_dirs ("~${LOGNAME}"); /* both */
558 #endif /* not AMIGA */
559 return 0;
560 }
561
562 #endif /* TEST */
563
564
565 /*
566 Local variables:
567 standalone-compile-command: "gcc -g -I. -I.. -DTEST elt-dirs.c kpathsea.a"
568 End:
569 */