1 /*
   2  * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * Class-Path Wildcards
  28  *
  29  * The syntax for wildcards is a single asterisk. The class path
  30  * foo/"*", e.g., loads all jar files in the directory named foo.
  31  * (This requires careful quotation when used in shell scripts.)
  32  *
  33  * Only files whose names end in .jar or .JAR are matched.
  34  * Files whose names end in .zip, or which have a particular
  35  * magic number, regardless of filename extension, are not
  36  * matched.
  37  *
  38  * Files are considered regardless of whether or not they are
  39  * "hidden" in the UNIX sense, i.e., have names beginning with '.'.
  40  *
  41  * A wildcard only matches jar files, not class files in the same
  42  * directory.  If you want to load both class files and jar files from
  43  * a single directory foo then you can say foo:foo/"*", or foo/"*":foo
  44  * if you want the jar files to take precedence.
  45  *
  46  * Subdirectories are not searched recursively, i.e., foo/"*" only
  47  * looks for jar files in foo, not in foo/bar, foo/baz, etc.
  48  *
  49  * Expansion of wildcards is done early, prior to the invocation of a
  50  * program's main method, rather than late, during the class-loading
  51  * process itself.  Each element of the input class path containing a
  52  * wildcard is replaced by the (possibly empty) sequence of elements
  53  * generated by enumerating the jar files in the named directory.  If
  54  * the directory foo contains a.jar, b.jar, and c.jar,
  55  * e.g., then the class path foo/"*" is expanded into
  56  * foo/a.jar:foo/b.jar:foo/c.jar, and that string would be the value
  57  * of the system property java.class.path.
  58  *
  59  * The order in which the jar files in a directory are enumerated in
  60  * the expanded class path is not specified and may vary from platform
  61  * to platform and even from moment to moment on the same machine.  A
  62  * well-constructed application should not depend upon any particular
  63  * order.  If a specific order is required then the jar files can be
  64  * enumerated explicitly in the class path.
  65  *
  66  * The CLASSPATH environment variable is not treated any differently
  67  * from the -classpath (equiv. -cp) command-line option,
  68  * i.e. wildcards are honored in all these cases.
  69  *
  70  * Class-path wildcards are not honored in the Class-Path jar-manifest
  71  * header.
  72  *
  73  * Class-path wildcards are honored not only by the Java launcher but
  74  * also by most other command-line tools that accept class paths, and
  75  * in particular by javac and javadoc.
  76  *
  77  * Class-path wildcards are not honored in any other kind of path, and
  78  * especially not in the bootstrap class path, which is a mere
  79  * artifact of our implementation and not something that developers
  80  * should use.
  81  *
  82  * Classpath wildcards are only expanded in the Java launcher code,
  83  * supporting the use of wildcards on the command line and in the
  84  * CLASSPATH environment variable.  We do not support the use of
  85  * wildcards by applications that embed the JVM.
  86  */
  87 
  88 #include <stddef.h>
  89 #include <stdio.h>
  90 #include <stdlib.h>
  91 #include <string.h>
  92 #include <sys/types.h>
  93 #include "java.h"       /* Strictly for PATH_SEPARATOR/FILE_SEPARATOR */
  94 #include "jli_util.h"
  95 
  96 #ifdef _WIN32
  97 #include <windows.h>
  98 #else /* Unix */
  99 #include <unistd.h>
 100 #include <dirent.h>
 101 #endif /* Unix */
 102 
 103 #if defined(_AIX)
 104   #define DIR DIR64
 105   #define opendir opendir64
 106   #define closedir closedir64
 107 #endif
 108 
 109 static int
 110 exists(const char* filename)
 111 {
 112 #ifdef _WIN32
 113     return _access(filename, 0) == 0;
 114 #else
 115     return access(filename, F_OK) == 0;
 116 #endif
 117 }
 118 
 119 #define NEW_(TYPE) ((TYPE) JLI_MemAlloc(sizeof(struct TYPE##_)))
 120 
 121 /*
 122  * Wildcard directory iteration.
 123  * WildcardIterator_for(wildcard) returns an iterator.
 124  * Each call to that iterator's next() method returns the basename
 125  * of an entry in the wildcard's directory.  The basename's memory
 126  * belongs to the iterator.  The caller is responsible for prepending
 127  * the directory name and file separator, if necessary.
 128  * When done with the iterator, call the close method to clean up.
 129  */
 130 typedef struct WildcardIterator_* WildcardIterator;
 131 
 132 #ifdef _WIN32
 133 struct WildcardIterator_
 134 {
 135     HANDLE handle;
 136     char *firstFile; /* Stupid FindFirstFile...FindNextFile */
 137 };
 138 // since this is used repeatedly we keep it here.
 139 static WIN32_FIND_DATA find_data;
 140 static WildcardIterator
 141 WildcardIterator_for(const char *wildcard)
 142 {
 143     WildcardIterator it = NEW_(WildcardIterator);
 144     HANDLE handle = FindFirstFile(wildcard, &find_data);
 145     if (handle == INVALID_HANDLE_VALUE) {
 146         JLI_MemFree(it);
 147         return NULL;
 148     }
 149     it->handle = handle;
 150     it->firstFile = find_data.cFileName;
 151     return it;
 152 }
 153 
 154 static char *
 155 WildcardIterator_next(WildcardIterator it)
 156 {
 157     if (it->firstFile != NULL) {
 158         char *firstFile = it->firstFile;
 159         it->firstFile = NULL;
 160         return firstFile;
 161     }
 162     return FindNextFile(it->handle, &find_data)
 163         ? find_data.cFileName : NULL;
 164 }
 165 
 166 static void
 167 WildcardIterator_close(WildcardIterator it)
 168 {
 169     if (it) {
 170         FindClose(it->handle);
 171         JLI_MemFree(it->firstFile);
 172         JLI_MemFree(it);
 173     }
 174 }
 175 
 176 #else /* Unix */
 177 struct WildcardIterator_
 178 {
 179     DIR *dir;
 180 };
 181 
 182 static WildcardIterator
 183 WildcardIterator_for(const char *wildcard)
 184 {
 185     DIR *dir;
 186     int wildlen = JLI_StrLen(wildcard);
 187     if (wildlen < 2) {
 188         dir = opendir(".");
 189     } else {
 190         char *dirname = JLI_StringDup(wildcard);
 191         dirname[wildlen - 1] = '\0';
 192         dir = opendir(dirname);
 193         JLI_MemFree(dirname);
 194     }
 195     if (dir == NULL)
 196         return NULL;
 197     else {
 198         WildcardIterator it = NEW_(WildcardIterator);
 199         it->dir = dir;
 200         return it;
 201     }
 202 }
 203 
 204 static char *
 205 WildcardIterator_next(WildcardIterator it)
 206 {
 207     struct dirent* dirp = readdir(it->dir);
 208     return dirp ? dirp->d_name : NULL;
 209 }
 210 
 211 static void
 212 WildcardIterator_close(WildcardIterator it)
 213 {
 214     if (it) {
 215         closedir(it->dir);
 216         JLI_MemFree(it);
 217     }
 218 }
 219 #endif /* Unix */
 220 
 221 static int
 222 equal(const char *s1, const char *s2)
 223 {
 224     return JLI_StrCmp(s1, s2) == 0;
 225 }
 226 
 227 static int
 228 isJarFileName(const char *filename)
 229 {
 230     int len = (int)JLI_StrLen(filename);
 231     return (len >= 4) &&
 232         (filename[len - 4] == '.') &&
 233         (equal(filename + len - 3, "jar") ||
 234          equal(filename + len - 3, "JAR")) &&
 235         /* Paranoia: Maybe filename is "DIR:foo.jar" */
 236         (JLI_StrChr(filename, PATH_SEPARATOR) == NULL);
 237 }
 238 
 239 static char *
 240 wildcardConcat(const char *wildcard, const char *basename)
 241 {
 242     int wildlen = (int)JLI_StrLen(wildcard);
 243     int baselen = (int)JLI_StrLen(basename);
 244     char *filename = (char *) JLI_MemAlloc(wildlen + baselen);
 245     /* Replace the trailing '*' with basename */
 246     memcpy(filename, wildcard, wildlen-1);
 247     memcpy(filename+wildlen-1, basename, baselen+1);
 248     return filename;
 249 }
 250 
 251 static JLI_List
 252 wildcardFileList(const char *wildcard)
 253 {
 254     const char *basename;
 255     JLI_List fl = JLI_List_new(16);
 256     WildcardIterator it = WildcardIterator_for(wildcard);
 257 
 258     if (it == NULL)
 259     {
 260         JLI_List_free(fl);
 261         return NULL;
 262     }
 263 
 264     while ((basename = WildcardIterator_next(it)) != NULL)
 265         if (isJarFileName(basename))
 266             JLI_List_add(fl, wildcardConcat(wildcard, basename));
 267     WildcardIterator_close(it);
 268     return fl;
 269 }
 270 
 271 static int
 272 isWildcard(const char *filename)
 273 {
 274     int len = (int)JLI_StrLen(filename);
 275     return (len > 0) &&
 276         (filename[len - 1] == '*') &&
 277         (len == 1 || IS_FILE_SEPARATOR(filename[len - 2])) &&
 278         (! exists(filename));
 279 }
 280 
 281 static int
 282 FileList_expandWildcards(JLI_List fl)
 283 {
 284     size_t i, j;
 285     int expandedCnt = 0;
 286     for (i = 0; i < fl->size; i++) {
 287         if (isWildcard(fl->elements[i])) {
 288             JLI_List expanded = wildcardFileList(fl->elements[i]);
 289             if (expanded != NULL && expanded->size > 0) {
 290                 expandedCnt++;
 291                 JLI_MemFree(fl->elements[i]);
 292                 JLI_List_ensureCapacity(fl, fl->size + expanded->size);
 293                 for (j = fl->size - 1; j >= i+1; j--)
 294                     fl->elements[j+expanded->size-1] = fl->elements[j];
 295                 for (j = 0; j < expanded->size; j++)
 296                     fl->elements[i+j] = expanded->elements[j];
 297                 i += expanded->size - 1;
 298                 fl->size += expanded->size - 1;
 299                 /* fl expropriates expanded's elements. */
 300                 expanded->size = 0;
 301             }
 302             JLI_List_free(expanded);
 303         }
 304     }
 305     return expandedCnt;
 306 }
 307 
 308 const char *
 309 JLI_WildcardExpandClasspath(const char *classpath)
 310 {
 311     const char *expanded;
 312     JLI_List fl;
 313 
 314     if (JLI_StrChr(classpath, '*') == NULL)
 315         return classpath;
 316     fl = JLI_List_split(classpath, PATH_SEPARATOR);
 317     expanded = FileList_expandWildcards(fl) ?
 318         JLI_List_join(fl, PATH_SEPARATOR) : classpath;
 319     JLI_List_free(fl);
 320     if (getenv(JLDEBUG_ENV_ENTRY) != 0)
 321         printf("Expanded wildcards:\n"
 322                "    before: \"%s\"\n"
 323                "    after : \"%s\"\n",
 324                classpath, expanded);
 325     return expanded;
 326 }
 327 
 328 #ifdef DEBUG_WILDCARD
 329 static void
 330 FileList_print(JLI_List fl)
 331 {
 332     size_t i;
 333     putchar('[');
 334     for (i = 0; i < fl->size; i++) {
 335         if (i > 0) printf(", ");
 336         printf("\"%s\"",fl->elements[i]);
 337     }
 338     putchar(']');
 339 }
 340 
 341 static void
 342 wildcardExpandArgv(const char ***argv)
 343 {
 344     int i;
 345     for (i = 0; (*argv)[i]; i++) {
 346         if (equal((*argv)[i], "-cp") ||
 347             equal((*argv)[i], "-classpath")) {
 348             i++;
 349             (*argv)[i] = wildcardExpandClasspath((*argv)[i]);
 350         }
 351     }
 352 }
 353 
 354 static void
 355 debugPrintArgv(char *argv[])
 356 {
 357     int i;
 358     putchar('[');
 359     for (i = 0; argv[i]; i++) {
 360         if (i > 0) printf(", ");
 361         printf("\"%s\"", argv[i]);
 362     }
 363     printf("]\n");
 364 }
 365 
 366 int
 367 main(int argc, char *argv[])
 368 {
 369     argv[0] = "java";
 370     wildcardExpandArgv((const char***)&argv);
 371     debugPrintArgv(argv);
 372     /* execvp("java", argv); */
 373     return 0;
 374 }
 375 #endif /* DEBUG_WILDCARD */
 376 
 377 /* Cute little perl prototype implementation....
 378 
 379 my $sep = ($^O =~ /^(Windows|cygwin)/) ? ";" : ":";
 380 
 381 sub expand($) {
 382   opendir DIR, $_[0] or return $_[0];
 383   join $sep, map {"$_[0]/$_"} grep {/\.(jar|JAR)$/} readdir DIR;
 384 }
 385 
 386 sub munge($) {
 387   join $sep,
 388     map {(! -r $_ and s/[\/\\]+\*$//) ? expand $_ : $_} split $sep, $_[0];
 389 }
 390 
 391 for (my $i = 0; $i < @ARGV - 1; $i++) {
 392   $ARGV[$i+1] = munge $ARGV[$i+1] if $ARGV[$i] =~ /^-c(p|lasspath)$/;
 393 }
 394 
 395 $ENV{CLASSPATH} = munge $ENV{CLASSPATH} if exists $ENV{CLASSPATH};
 396 @ARGV = ("java", @ARGV);
 397 print "@ARGV\n";
 398 exec @ARGV;
 399 
 400 */