Tizen 2.0 Release
[external/tizen-coreutils.git] / src / pathchk.c
1 /* pathchk -- check whether file names are valid or portable
2    Copyright (C) 1991-2006 Free Software Foundation, Inc.
3
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 2, or (at your option)
7    any later version.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 #include <config.h>
19 #include <stdio.h>
20 #include <getopt.h>
21 #include <sys/types.h>
22 #if HAVE_WCHAR_H
23 # include <wchar.h>
24 #endif
25
26 #include "system.h"
27 #include "error.h"
28 #include "euidaccess.h"
29 #include "quote.h"
30 #include "quotearg.h"
31
32 #if ! (HAVE_MBRLEN && HAVE_MBSTATE_T)
33 # define mbrlen(s, n, ps) 1
34 # define mbstate_t int
35 #endif
36
37 /* The official name of this program (e.g., no `g' prefix).  */
38 #define PROGRAM_NAME "pathchk"
39
40 #define AUTHORS "Paul Eggert", "David MacKenzie", "Jim Meyering"
41
42 #ifndef _POSIX_PATH_MAX
43 # define _POSIX_PATH_MAX 256
44 #endif
45 #ifndef _POSIX_NAME_MAX
46 # define _POSIX_NAME_MAX 14
47 #endif
48
49 #ifdef _XOPEN_NAME_MAX
50 # define NAME_MAX_MINIMUM _XOPEN_NAME_MAX
51 #else
52 # define NAME_MAX_MINIMUM _POSIX_NAME_MAX
53 #endif
54 #ifdef _XOPEN_PATH_MAX
55 # define PATH_MAX_MINIMUM _XOPEN_PATH_MAX
56 #else
57 # define PATH_MAX_MINIMUM _POSIX_PATH_MAX
58 #endif
59
60 #if ! (HAVE_PATHCONF && defined _PC_NAME_MAX && defined _PC_PATH_MAX)
61 # ifndef _PC_NAME_MAX
62 #  define _PC_NAME_MAX 0
63 #  define _PC_PATH_MAX 1
64 # endif
65 # ifndef pathconf
66 #  define pathconf(file, flag) \
67      (flag == _PC_NAME_MAX ? NAME_MAX_MINIMUM : PATH_MAX_MINIMUM)
68 # endif
69 #endif
70
71 static bool validate_file_name (char *, bool, bool);
72
73 /* The name this program was run with. */
74 char *program_name;
75
76 /* For long options that have no equivalent short option, use a
77    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
78 enum
79 {
80   PORTABILITY_OPTION = CHAR_MAX + 1
81 };
82
83 static struct option const longopts[] =
84 {
85   {"portability", no_argument, NULL, PORTABILITY_OPTION},
86   {GETOPT_HELP_OPTION_DECL},
87   {GETOPT_VERSION_OPTION_DECL},
88   {NULL, 0, NULL, 0}
89 };
90
91 void
92 usage (int status)
93 {
94   if (status != EXIT_SUCCESS)
95     fprintf (stderr, _("Try `%s --help' for more information.\n"),
96              program_name);
97   else
98     {
99       printf (_("Usage: %s [OPTION]... NAME...\n"), program_name);
100       fputs (_("\
101 Diagnose unportable constructs in NAME.\n\
102 \n\
103   -p                  check for most POSIX systems\n\
104   -P                  check for empty names and leading \"-\"\n\
105       --portability   check for all POSIX systems (equivalent to -p -P)\n\
106 "), stdout);
107       fputs (HELP_OPTION_DESCRIPTION, stdout);
108       fputs (VERSION_OPTION_DESCRIPTION, stdout);
109       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
110     }
111   exit (status);
112 }
113
114 int
115 main (int argc, char **argv)
116 {
117   bool ok = true;
118   bool check_basic_portability = false;
119   bool check_extra_portability = false;
120   int optc;
121
122   initialize_main (&argc, &argv);
123   program_name = argv[0];
124   setlocale (LC_ALL, "");
125   bindtextdomain (PACKAGE, LOCALEDIR);
126   textdomain (PACKAGE);
127
128   atexit (close_stdout);
129
130   while ((optc = getopt_long (argc, argv, "+pP", longopts, NULL)) != -1)
131     {
132       switch (optc)
133         {
134         case PORTABILITY_OPTION:
135           check_basic_portability = true;
136           check_extra_portability = true;
137           break;
138
139         case 'p':
140           check_basic_portability = true;
141           break;
142
143         case 'P':
144           check_extra_portability = true;
145           break;
146
147         case_GETOPT_HELP_CHAR;
148
149         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
150
151         default:
152           usage (EXIT_FAILURE);
153         }
154     }
155
156   if (optind == argc)
157     {
158       error (0, 0, _("missing operand"));
159       usage (EXIT_FAILURE);
160     }
161
162   for (; optind < argc; ++optind)
163     ok &= validate_file_name (argv[optind],
164                               check_basic_portability, check_extra_portability);
165
166   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
167 }
168
169 /* If FILE contains a component with a leading "-", report an error
170    and return false; otherwise, return true.  */
171
172 static bool
173 no_leading_hyphen (char const *file)
174 {
175   char const *p;
176
177   for (p = file;  (p = strchr (p, '-'));  p++)
178     if (p == file || p[-1] == '/')
179       {
180         error (0, 0, _("leading `-' in a component of file name %s"),
181                quote (file));
182         return false;
183       }
184
185   return true;
186 }
187
188 /* If FILE (of length FILELEN) contains only portable characters,
189    return true, else report an error and return false.  */
190
191 static bool
192 portable_chars_only (char const *file, size_t filelen)
193 {
194   size_t validlen = strspn (file,
195                             ("/"
196                              "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
197                              "abcdefghijklmnopqrstuvwxyz"
198                              "0123456789._-"));
199   char const *invalid = file + validlen;
200
201   if (*invalid)
202     {
203       mbstate_t mbstate = { 0, };
204       size_t charlen = mbrlen (invalid, filelen - validlen, &mbstate);
205       error (0, 0,
206              _("nonportable character %s in file name %s"),
207              quotearg_n_style_mem (1, locale_quoting_style, invalid,
208                                    (charlen <= MB_LEN_MAX ? charlen : 1)),
209              quote_n (0, file));
210       return false;
211     }
212
213   return true;
214 }
215
216 /* Return the address of the start of the next file name component in F.  */
217
218 static char *
219 component_start (char *f)
220 {
221   while (*f == '/')
222     f++;
223   return f;
224 }
225
226 /* Return the size of the file name component F.  F must be nonempty.  */
227
228 static size_t
229 component_len (char const *f)
230 {
231   size_t len;
232   for (len = 1; f[len] != '/' && f[len]; len++)
233     continue;
234   return len;
235 }
236
237 /* Make sure that
238    strlen (FILE) <= PATH_MAX
239    && strlen (each-existing-directory-in-FILE) <= NAME_MAX
240
241    If CHECK_BASIC_PORTABILITY is true, compare against _POSIX_PATH_MAX and
242    _POSIX_NAME_MAX instead, and make sure that FILE contains no
243    characters not in the POSIX portable filename character set, which
244    consists of A-Z, a-z, 0-9, ., _, - (plus / for separators).
245
246    If CHECK_BASIC_PORTABILITY is false, make sure that all leading directories
247    along FILE that exist are searchable.
248
249    If CHECK_EXTRA_PORTABILITY is true, check that file name components do not
250    begin with "-".
251
252    If either CHECK_BASIC_PORTABILITY or CHECK_EXTRA_PORTABILITY is true,
253    check that the file name is not empty.
254
255    Return true if all of these tests are successful, false if any fail.  */
256
257 static bool
258 validate_file_name (char *file, bool check_basic_portability,
259                     bool check_extra_portability)
260 {
261   size_t filelen = strlen (file);
262
263   /* Start of file name component being checked.  */
264   char *start;
265
266   /* True if component lengths need to be checked.  */
267   bool check_component_lengths;
268
269   /* True if the file is known to exist.  */
270   bool file_exists = false;
271
272   if (check_extra_portability && ! no_leading_hyphen (file))
273     return false;
274
275   if ((check_basic_portability | check_extra_portability)
276       && filelen == 0)
277     {
278       /* Fail, since empty names are not portable.  As of
279          2005-01-06 POSIX does not address whether "pathchk -p ''"
280          should (or is allowed to) fail, so this is not a
281          conformance violation.  */
282       error (0, 0, _("empty file name"));
283       return false;
284     }
285
286   if (check_basic_portability)
287     {
288       if (! portable_chars_only (file, filelen))
289         return false;
290     }
291   else
292     {
293       /* Check whether a file name component is in a directory that
294          is not searchable, or has some other serious problem.
295          POSIX does not allow "" as a file name, but some non-POSIX
296          hosts do (as an alias for "."), so allow "" if lstat does.  */
297
298       struct stat st;
299       if (lstat (file, &st) == 0)
300         file_exists = true;
301       else if (errno != ENOENT || filelen == 0)
302         {
303           error (0, errno, "%s", file);
304           return false;
305         }
306     }
307
308   if (check_basic_portability
309       || (! file_exists && PATH_MAX_MINIMUM <= filelen))
310     {
311       size_t maxsize;
312
313       if (check_basic_portability)
314         maxsize = _POSIX_PATH_MAX;
315       else
316         {
317           long int size;
318           char const *dir = (*file == '/' ? "/" : ".");
319           errno = 0;
320           size = pathconf (dir, _PC_PATH_MAX);
321           if (size < 0 && errno != 0)
322             {
323               error (0, errno,
324                      _("%s: unable to determine maximum file name length"),
325                      dir);
326               return false;
327             }
328           maxsize = MIN (size, SIZE_MAX);
329         }
330
331       if (maxsize <= filelen)
332         {
333           unsigned long int len = filelen;
334           unsigned long int maxlen = maxsize - 1;
335           error (0, 0, _("limit %lu exceeded by length %lu of file name %s"),
336                  maxlen, len, quote (file));
337           return false;
338         }
339     }
340
341   /* Check whether pathconf (..., _PC_NAME_MAX) can be avoided, i.e.,
342      whether all file name components are so short that they are valid
343      in any file system on this platform.  If CHECK_BASIC_PORTABILITY, though,
344      it's more convenient to check component lengths below.  */
345
346   check_component_lengths = check_basic_portability;
347   if (! check_component_lengths && ! file_exists)
348     {
349       for (start = file; *(start = component_start (start)); )
350         {
351           size_t length = component_len (start);
352
353           if (NAME_MAX_MINIMUM < length)
354             {
355               check_component_lengths = true;
356               break;
357             }
358
359           start += length;
360         }
361     }
362
363   if (check_component_lengths)
364     {
365       /* The limit on file name components for the current component.
366          This defaults to NAME_MAX_MINIMUM, for the sake of non-POSIX
367          systems (NFS, say?) where pathconf fails on "." or "/" with
368          errno == ENOENT.  */
369       size_t name_max = NAME_MAX_MINIMUM;
370
371       /* If nonzero, the known limit on file name components.  */
372       size_t known_name_max = (check_basic_portability ? _POSIX_NAME_MAX : 0);
373
374       for (start = file; *(start = component_start (start)); )
375         {
376           size_t length;
377
378           if (known_name_max)
379             name_max = known_name_max;
380           else
381             {
382               long int len;
383               char const *dir = (start == file ? "." : file);
384               char c = *start;
385               errno = 0;
386               *start = '\0';
387               len = pathconf (dir, _PC_NAME_MAX);
388               *start = c;
389               if (0 <= len)
390                 name_max = MIN (len, SIZE_MAX);
391               else
392                 switch (errno)
393                   {
394                   case 0:
395                     /* There is no limit.  */
396                     name_max = SIZE_MAX;
397                     break;
398
399                   case ENOENT:
400                     /* DIR does not exist; use its parent's maximum.  */
401                     known_name_max = name_max;
402                     break;
403
404                   default:
405                     *start = '\0';
406                     error (0, errno, "%s", dir);
407                     *start = c;
408                     return false;
409                   }
410             }
411
412           length = component_len (start);
413
414           if (name_max < length)
415             {
416               unsigned long int len = length;
417               unsigned long int maxlen = name_max;
418               char c = start[len];
419               start[len] = '\0';
420               error (0, 0,
421                      _("limit %lu exceeded by length %lu "
422                        "of file name component %s"),
423                      maxlen, len, quote (start));
424               start[len] = c;
425               return false;
426             }
427
428           start += length;
429         }
430     }
431
432   return true;
433 }