maint: replace each "for (;;)" with "while (true)"
[coreutils.git] / src / pathchk.c
blob62c20941c1b6cb0bbf459d6218bb9780b669e6ab
1 /* pathchk -- check whether file names are valid or portable
2 Copyright (C) 1991-2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 #include <config.h>
18 #include <stdio.h>
19 #include <getopt.h>
20 #include <sys/types.h>
21 #include <wchar.h>
23 #include "system.h"
24 #include "error.h"
25 #include "quote.h"
26 #include "quotearg.h"
28 #if ! (HAVE_MBRLEN && HAVE_MBSTATE_T)
29 # define mbrlen(s, n, ps) 1
30 # define mbstate_t int
31 #endif
33 /* The official name of this program (e.g., no `g' prefix). */
34 #define PROGRAM_NAME "pathchk"
36 #define AUTHORS \
37 proper_name ("Paul Eggert"), \
38 proper_name ("David MacKenzie"), \
39 proper_name ("Jim Meyering")
41 #ifndef _POSIX_PATH_MAX
42 # define _POSIX_PATH_MAX 256
43 #endif
44 #ifndef _POSIX_NAME_MAX
45 # define _POSIX_NAME_MAX 14
46 #endif
48 #ifdef _XOPEN_NAME_MAX
49 # define NAME_MAX_MINIMUM _XOPEN_NAME_MAX
50 #else
51 # define NAME_MAX_MINIMUM _POSIX_NAME_MAX
52 #endif
53 #ifdef _XOPEN_PATH_MAX
54 # define PATH_MAX_MINIMUM _XOPEN_PATH_MAX
55 #else
56 # define PATH_MAX_MINIMUM _POSIX_PATH_MAX
57 #endif
59 #if ! (HAVE_PATHCONF && defined _PC_NAME_MAX && defined _PC_PATH_MAX)
60 # ifndef _PC_NAME_MAX
61 # define _PC_NAME_MAX 0
62 # define _PC_PATH_MAX 1
63 # endif
64 # ifndef pathconf
65 # define pathconf(file, flag) \
66 (flag == _PC_NAME_MAX ? NAME_MAX_MINIMUM : PATH_MAX_MINIMUM)
67 # endif
68 #endif
70 static bool validate_file_name (char *, bool, bool);
72 /* For long options that have no equivalent short option, use a
73 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
74 enum
76 PORTABILITY_OPTION = CHAR_MAX + 1
79 static struct option const longopts[] =
81 {"portability", no_argument, NULL, PORTABILITY_OPTION},
82 {GETOPT_HELP_OPTION_DECL},
83 {GETOPT_VERSION_OPTION_DECL},
84 {NULL, 0, NULL, 0}
87 void
88 usage (int status)
90 if (status != EXIT_SUCCESS)
91 fprintf (stderr, _("Try `%s --help' for more information.\n"),
92 program_name);
93 else
95 printf (_("Usage: %s [OPTION]... NAME...\n"), program_name);
96 fputs (_("\
97 Diagnose invalid or unportable file names.\n\
98 \n\
99 -p check for most POSIX systems\n\
100 -P check for empty names and leading \"-\"\n\
101 --portability check for all POSIX systems (equivalent to -p -P)\n\
102 "), stdout);
103 fputs (HELP_OPTION_DESCRIPTION, stdout);
104 fputs (VERSION_OPTION_DESCRIPTION, stdout);
105 emit_ancillary_info ();
107 exit (status);
111 main (int argc, char **argv)
113 bool ok = true;
114 bool check_basic_portability = false;
115 bool check_extra_portability = false;
116 int optc;
118 initialize_main (&argc, &argv);
119 set_program_name (argv[0]);
120 setlocale (LC_ALL, "");
121 bindtextdomain (PACKAGE, LOCALEDIR);
122 textdomain (PACKAGE);
124 atexit (close_stdout);
126 while ((optc = getopt_long (argc, argv, "+pP", longopts, NULL)) != -1)
128 switch (optc)
130 case PORTABILITY_OPTION:
131 check_basic_portability = true;
132 check_extra_portability = true;
133 break;
135 case 'p':
136 check_basic_portability = true;
137 break;
139 case 'P':
140 check_extra_portability = true;
141 break;
143 case_GETOPT_HELP_CHAR;
145 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
147 default:
148 usage (EXIT_FAILURE);
152 if (optind == argc)
154 error (0, 0, _("missing operand"));
155 usage (EXIT_FAILURE);
158 for (; optind < argc; ++optind)
159 ok &= validate_file_name (argv[optind],
160 check_basic_portability, check_extra_portability);
162 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
165 /* If FILE contains a component with a leading "-", report an error
166 and return false; otherwise, return true. */
168 static bool
169 no_leading_hyphen (char const *file)
171 char const *p;
173 for (p = file; (p = strchr (p, '-')); p++)
174 if (p == file || p[-1] == '/')
176 error (0, 0, _("leading `-' in a component of file name %s"),
177 quote (file));
178 return false;
181 return true;
184 /* If FILE (of length FILELEN) contains only portable characters,
185 return true, else report an error and return false. */
187 static bool
188 portable_chars_only (char const *file, size_t filelen)
190 size_t validlen = strspn (file,
191 ("/"
192 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
193 "abcdefghijklmnopqrstuvwxyz"
194 "0123456789._-"));
195 char const *invalid = file + validlen;
197 if (*invalid)
199 DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate);
200 size_t charlen = mbrlen (invalid, filelen - validlen, &mbstate);
201 error (0, 0,
202 _("nonportable character %s in file name %s"),
203 quotearg_n_style_mem (1, locale_quoting_style, invalid,
204 (charlen <= MB_LEN_MAX ? charlen : 1)),
205 quote_n (0, file));
206 return false;
209 return true;
212 /* Return the address of the start of the next file name component in F. */
214 static char *
215 component_start (char *f)
217 while (*f == '/')
218 f++;
219 return f;
222 /* Return the size of the file name component F. F must be nonempty. */
224 static size_t
225 component_len (char const *f)
227 size_t len;
228 for (len = 1; f[len] != '/' && f[len]; len++)
229 continue;
230 return len;
233 /* Make sure that
234 strlen (FILE) <= PATH_MAX
235 && strlen (each-existing-directory-in-FILE) <= NAME_MAX
237 If CHECK_BASIC_PORTABILITY is true, compare against _POSIX_PATH_MAX and
238 _POSIX_NAME_MAX instead, and make sure that FILE contains no
239 characters not in the POSIX portable filename character set, which
240 consists of A-Z, a-z, 0-9, ., _, - (plus / for separators).
242 If CHECK_BASIC_PORTABILITY is false, make sure that all leading directories
243 along FILE that exist are searchable.
245 If CHECK_EXTRA_PORTABILITY is true, check that file name components do not
246 begin with "-".
248 If either CHECK_BASIC_PORTABILITY or CHECK_EXTRA_PORTABILITY is true,
249 check that the file name is not empty.
251 Return true if all of these tests are successful, false if any fail. */
253 static bool
254 validate_file_name (char *file, bool check_basic_portability,
255 bool check_extra_portability)
257 size_t filelen = strlen (file);
259 /* Start of file name component being checked. */
260 char *start;
262 /* True if component lengths need to be checked. */
263 bool check_component_lengths;
265 /* True if the file is known to exist. */
266 bool file_exists = false;
268 if (check_extra_portability && ! no_leading_hyphen (file))
269 return false;
271 if ((check_basic_portability || check_extra_portability)
272 && filelen == 0)
274 /* Fail, since empty names are not portable. As of
275 2005-01-06 POSIX does not address whether "pathchk -p ''"
276 should (or is allowed to) fail, so this is not a
277 conformance violation. */
278 error (0, 0, _("empty file name"));
279 return false;
282 if (check_basic_portability)
284 if (! portable_chars_only (file, filelen))
285 return false;
287 else
289 /* Check whether a file name component is in a directory that
290 is not searchable, or has some other serious problem.
291 POSIX does not allow "" as a file name, but some non-POSIX
292 hosts do (as an alias for "."), so allow "" if lstat does. */
294 struct stat st;
295 if (lstat (file, &st) == 0)
296 file_exists = true;
297 else if (errno != ENOENT || filelen == 0)
299 error (0, errno, "%s", file);
300 return false;
304 if (check_basic_portability
305 || (! file_exists && PATH_MAX_MINIMUM <= filelen))
307 size_t maxsize;
309 if (check_basic_portability)
310 maxsize = _POSIX_PATH_MAX;
311 else
313 long int size;
314 char const *dir = (*file == '/' ? "/" : ".");
315 errno = 0;
316 size = pathconf (dir, _PC_PATH_MAX);
317 if (size < 0 && errno != 0)
319 error (0, errno,
320 _("%s: unable to determine maximum file name length"),
321 dir);
322 return false;
324 maxsize = MIN (size, SSIZE_MAX);
327 if (maxsize <= filelen)
329 unsigned long int len = filelen;
330 unsigned long int maxlen = maxsize - 1;
331 error (0, 0, _("limit %lu exceeded by length %lu of file name %s"),
332 maxlen, len, quote (file));
333 return false;
337 /* Check whether pathconf (..., _PC_NAME_MAX) can be avoided, i.e.,
338 whether all file name components are so short that they are valid
339 in any file system on this platform. If CHECK_BASIC_PORTABILITY, though,
340 it's more convenient to check component lengths below. */
342 check_component_lengths = check_basic_portability;
343 if (! check_component_lengths && ! file_exists)
345 for (start = file; *(start = component_start (start)); )
347 size_t length = component_len (start);
349 if (NAME_MAX_MINIMUM < length)
351 check_component_lengths = true;
352 break;
355 start += length;
359 if (check_component_lengths)
361 /* The limit on file name components for the current component.
362 This defaults to NAME_MAX_MINIMUM, for the sake of non-POSIX
363 systems (NFS, say?) where pathconf fails on "." or "/" with
364 errno == ENOENT. */
365 size_t name_max = NAME_MAX_MINIMUM;
367 /* If nonzero, the known limit on file name components. */
368 size_t known_name_max = (check_basic_portability ? _POSIX_NAME_MAX : 0);
370 for (start = file; *(start = component_start (start)); )
372 size_t length;
374 if (known_name_max)
375 name_max = known_name_max;
376 else
378 long int len;
379 char const *dir = (start == file ? "." : file);
380 char c = *start;
381 errno = 0;
382 *start = '\0';
383 len = pathconf (dir, _PC_NAME_MAX);
384 *start = c;
385 if (0 <= len)
386 name_max = MIN (len, SSIZE_MAX);
387 else
388 switch (errno)
390 case 0:
391 /* There is no limit. */
392 name_max = SIZE_MAX;
393 break;
395 case ENOENT:
396 /* DIR does not exist; use its parent's maximum. */
397 known_name_max = name_max;
398 break;
400 default:
401 *start = '\0';
402 error (0, errno, "%s", dir);
403 *start = c;
404 return false;
408 length = component_len (start);
410 if (name_max < length)
412 unsigned long int len = length;
413 unsigned long int maxlen = name_max;
414 char c = start[len];
415 start[len] = '\0';
416 error (0, 0,
417 _("limit %lu exceeded by length %lu "
418 "of file name component %s"),
419 maxlen, len, quote (start));
420 start[len] = c;
421 return false;
424 start += length;
428 return true;