1 /*
   2  * Copyright (c) 1998, 2015, 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 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
  27 #include <stdio.h>
  28 #include <ctype.h>
  29 #endif
  30 #include <pwd.h>
  31 #include <locale.h>
  32 #ifndef ARCHPROPNAME
  33 #error "The macro ARCHPROPNAME has not been defined"
  34 #endif
  35 #include <sys/utsname.h>        /* For os_name and os_version */
  36 #include <langinfo.h>           /* For nl_langinfo */
  37 #include <stdlib.h>
  38 #include <string.h>
  39 #include <sys/types.h>
  40 #include <unistd.h>
  41 #include <sys/param.h>
  42 #include <time.h>
  43 #include <errno.h>
  44 
  45 #ifdef MACOSX
  46 #include "java_props_macosx.h"
  47 #endif
  48 
  49 #if defined(_ALLBSD_SOURCE)
  50 #if !defined(P_tmpdir)
  51 #include <paths.h>
  52 #define P_tmpdir _PATH_VARTMP
  53 #endif
  54 #endif
  55 
  56 #include "locale_str.h"
  57 #include "java_props.h"
  58 
  59 #if !defined(_ALLBSD_SOURCE)
  60 #ifdef __linux__
  61   #ifndef CODESET
  62   #define CODESET _NL_CTYPE_CODESET_NAME
  63   #endif
  64 #else
  65 #ifdef ALT_CODESET_KEY
  66 #define CODESET ALT_CODESET_KEY
  67 #endif
  68 #endif
  69 #endif /* !_ALLBSD_SOURCE */
  70 
  71 #ifdef JAVASE_EMBEDDED
  72 #include <dlfcn.h>
  73 #include <sys/stat.h>
  74 #endif
  75 
  76 /* Take an array of string pairs (map of key->value) and a string (key).
  77  * Examine each pair in the map to see if the first string (key) matches the
  78  * string.  If so, store the second string of the pair (value) in the value and
  79  * return 1.  Otherwise do nothing and return 0.  The end of the map is
  80  * indicated by an empty string at the start of a pair (key of "").
  81  */
  82 static int
  83 mapLookup(char* map[], const char* key, char** value) {
  84     int i;
  85     for (i = 0; strcmp(map[i], ""); i += 2){
  86         if (!strcmp(key, map[i])){
  87             *value = map[i + 1];
  88             return 1;
  89         }
  90     }
  91     return 0;
  92 }
  93 
  94 /* This function sets an environment variable using envstring.
  95  * The format of envstring is "name=value".
  96  * If the name has already existed, it will append value to the name.
  97  */
  98 static void
  99 setPathEnvironment(char *envstring)
 100 {
 101     char name[20], *value, *current;
 102 
 103     value = strchr(envstring, '='); /* locate name and value separator */
 104 
 105     if (! value)
 106         return; /* not a valid environment setting */
 107 
 108     /* copy first part as environment name */
 109     strncpy(name, envstring, value - envstring);
 110     name[value-envstring] = '\0';
 111 
 112     value++; /* set value point to value of the envstring */
 113 
 114     current = getenv(name);
 115     if (current) {
 116         if (! strstr(current, value)) {
 117             /* value is not found in current environment, append it */
 118             char *temp = malloc(strlen(envstring) + strlen(current) + 2);
 119         strcpy(temp, name);
 120         strcat(temp, "=");
 121         strcat(temp, current);
 122         strcat(temp, ":");
 123         strcat(temp, value);
 124         putenv(temp);
 125         }
 126         /* else the value has already been set, do nothing */
 127     }
 128     else {
 129         /* environment variable is not found */
 130         putenv(envstring);
 131     }
 132 }
 133 
 134 #ifndef P_tmpdir
 135 #define P_tmpdir "/var/tmp"
 136 #endif
 137 
 138 static int ParseLocale(JNIEnv* env, int cat, char ** std_language, char ** std_script,
 139                        char ** std_country, char ** std_variant, char ** std_encoding) {
 140     char *temp = NULL;
 141     char *language = NULL, *country = NULL, *variant = NULL,
 142          *encoding = NULL;
 143     char *p, *encoding_variant, *old_temp, *old_ev;
 144     char *lc;
 145 
 146     /* Query the locale set for the category */
 147 
 148 #ifdef MACOSX
 149     lc = setupMacOSXLocale(cat); // malloc'd memory, need to free
 150 #else
 151     lc = setlocale(cat, NULL);
 152 #endif
 153 
 154 #ifndef __linux__
 155     if (lc == NULL) {
 156         return 0;
 157     }
 158 
 159     temp = malloc(strlen(lc) + 1);
 160     if (temp == NULL) {
 161 #ifdef MACOSX
 162         free(lc); // malloced memory
 163 #endif
 164         JNU_ThrowOutOfMemoryError(env, NULL);
 165         return 0;
 166     }
 167 
 168     if (cat == LC_CTYPE) {
 169         /*
 170          * Workaround for Solaris bug 4201684: Xlib doesn't like @euro
 171          * locales. Since we don't depend on the libc @euro behavior,
 172          * we just remove the qualifier.
 173          * On Linux, the bug doesn't occur; on the other hand, @euro
 174          * is needed there because it's a shortcut that also determines
 175          * the encoding - without it, we wouldn't get ISO-8859-15.
 176          * Therefore, this code section is Solaris-specific.
 177          */
 178         strcpy(temp, lc);
 179         p = strstr(temp, "@euro");
 180         if (p != NULL) {
 181             *p = '\0';
 182             setlocale(LC_ALL, temp);
 183         }
 184     }
 185 #else
 186     if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) {
 187         lc = "en_US";
 188     }
 189 
 190     temp = malloc(strlen(lc) + 1);
 191     if (temp == NULL) {
 192         JNU_ThrowOutOfMemoryError(env, NULL);
 193         return 0;
 194     }
 195 
 196 #endif
 197 
 198     /*
 199      * locale string format in Solaris is
 200      * <language name>_<country name>.<encoding name>@<variant name>
 201      * <country name>, <encoding name>, and <variant name> are optional.
 202      */
 203 
 204     strcpy(temp, lc);
 205 #ifdef MACOSX
 206     free(lc); // malloced memory
 207 #endif
 208     /* Parse the language, country, encoding, and variant from the
 209      * locale.  Any of the elements may be missing, but they must occur
 210      * in the order language_country.encoding@variant, and must be
 211      * preceded by their delimiter (except for language).
 212      *
 213      * If the locale name (without .encoding@variant, if any) matches
 214      * any of the names in the locale_aliases list, map it to the
 215      * corresponding full locale name.  Most of the entries in the
 216      * locale_aliases list are locales that include a language name but
 217      * no country name, and this facility is used to map each language
 218      * to a default country if that's possible.  It's also used to map
 219      * the Solaris locale aliases to their proper Java locale IDs.
 220      */
 221 
 222     encoding_variant = malloc(strlen(temp)+1);
 223     if (encoding_variant == NULL) {
 224         free(temp);
 225         JNU_ThrowOutOfMemoryError(env, NULL);
 226         return 0;
 227     }
 228 
 229     if ((p = strchr(temp, '.')) != NULL) {
 230         strcpy(encoding_variant, p); /* Copy the leading '.' */
 231         *p = '\0';
 232     } else if ((p = strchr(temp, '@')) != NULL) {
 233         strcpy(encoding_variant, p); /* Copy the leading '@' */
 234         *p = '\0';
 235     } else {
 236         *encoding_variant = '\0';
 237     }
 238 
 239     if (mapLookup(locale_aliases, temp, &p)) {
 240         old_temp = temp;
 241         temp = realloc(temp, strlen(p)+1);
 242         if (temp == NULL) {
 243             free(old_temp);
 244             free(encoding_variant);
 245             JNU_ThrowOutOfMemoryError(env, NULL);
 246             return 0;
 247         }
 248         strcpy(temp, p);
 249         old_ev = encoding_variant;
 250         encoding_variant = realloc(encoding_variant, strlen(temp)+1);
 251         if (encoding_variant == NULL) {
 252             free(old_ev);
 253             free(temp);
 254             JNU_ThrowOutOfMemoryError(env, NULL);
 255             return 0;
 256         }
 257         // check the "encoding_variant" again, if any.
 258         if ((p = strchr(temp, '.')) != NULL) {
 259             strcpy(encoding_variant, p); /* Copy the leading '.' */
 260             *p = '\0';
 261         } else if ((p = strchr(temp, '@')) != NULL) {
 262             strcpy(encoding_variant, p); /* Copy the leading '@' */
 263             *p = '\0';
 264         }
 265     }
 266 
 267     language = temp;
 268     if ((country = strchr(temp, '_')) != NULL) {
 269         *country++ = '\0';
 270     }
 271 
 272     p = encoding_variant;
 273     if ((encoding = strchr(p, '.')) != NULL) {
 274         p[encoding++ - p] = '\0';
 275         p = encoding;
 276     }
 277     if ((variant = strchr(p, '@')) != NULL) {
 278         p[variant++ - p] = '\0';
 279     }
 280 
 281     /* Normalize the language name */
 282     if (std_language != NULL) {
 283         *std_language = "en";
 284         if (language != NULL && mapLookup(language_names, language, std_language) == 0) {
 285             *std_language = malloc(strlen(language)+1);
 286             strcpy(*std_language, language);
 287         }
 288     }
 289 
 290     /* Normalize the country name */
 291     if (std_country != NULL && country != NULL) {
 292         if (mapLookup(country_names, country, std_country) == 0) {
 293             *std_country = malloc(strlen(country)+1);
 294             strcpy(*std_country, country);
 295         }
 296     }
 297 
 298     /* Normalize the script and variant name.  Note that we only use
 299      * variants listed in the mapping array; others are ignored.
 300      */
 301     if (variant != NULL) {
 302         if (std_script != NULL) {
 303             mapLookup(script_names, variant, std_script);
 304         }
 305 
 306         if (std_variant != NULL) {
 307             mapLookup(variant_names, variant, std_variant);
 308         }
 309     }
 310 
 311     /* Normalize the encoding name.  Note that we IGNORE the string
 312      * 'encoding' extracted from the locale name above.  Instead, we use the
 313      * more reliable method of calling nl_langinfo(CODESET).  This function
 314      * returns an empty string if no encoding is set for the given locale
 315      * (e.g., the C or POSIX locales); we use the default ISO 8859-1
 316      * converter for such locales.
 317      */
 318     if (std_encoding != NULL) {
 319         /* OK, not so reliable - nl_langinfo() gives wrong answers on
 320          * Euro locales, in particular. */
 321         if (strcmp(p, "ISO8859-15") == 0)
 322             p = "ISO8859-15";
 323         else {
 324            /* nl_langinfo() returns a pointer to a static buffer which may
 325             * be overwritten, so we have to save it for later use. */
 326             char *encoding;
 327             p = nl_langinfo(CODESET);
 328             encoding = malloc(strlen(p) + 1);
 329             if (encoding == NULL) {
 330                 free(temp);
 331                 free(encoding_variant);
 332                 JNU_ThrowOutOfMemoryError(env, NULL);
 333                 return 0;
 334             }
 335             strcpy(encoding, p);
 336             p = encoding;
 337         }
 338         /* Convert the bare "646" used on Solaris to a proper IANA name */
 339         if (strcmp(p, "646") == 0)
 340             p = "ISO646-US";
 341 
 342         /* return same result nl_langinfo would return for en_UK,
 343          * in order to use optimizations. */
 344         *std_encoding = (*p != '\0') ? p : "ISO8859-1";
 345 
 346 #ifdef __linux__
 347         /*
 348          * Remap the encoding string to a different value for japanese
 349          * locales on linux so that customized converters are used instead
 350          * of the default converter for "EUC-JP". The customized converters
 351          * omit support for the JIS0212 encoding which is not supported by
 352          * the variant of "EUC-JP" encoding used on linux
 353          */
 354         if (strcmp(p, "EUC-JP") == 0) {
 355             *std_encoding = "EUC-JP-LINUX";
 356         }
 357 #else
 358         if (strcmp(p,"eucJP") == 0) {
 359             /* For Solaris use customized vendor defined character
 360              * customized EUC-JP converter
 361              */
 362             *std_encoding = "eucJP-open";
 363         } else if (strcmp(p, "Big5") == 0 || strcmp(p, "BIG5") == 0) {
 364             /*
 365              * Remap the encoding string to Big5_Solaris which augments
 366              * the default converter for Solaris Big5 locales to include
 367              * seven additional ideographic characters beyond those included
 368              * in the Java "Big5" converter.
 369              */
 370             *std_encoding = "Big5_Solaris";
 371         } else if (strcmp(p, "Big5-HKSCS") == 0) {
 372             /*
 373              * Solaris uses HKSCS2001
 374              */
 375             *std_encoding = "Big5-HKSCS-2001";
 376         }
 377 #endif
 378 #ifdef MACOSX
 379         /*
 380          * For the case on MacOS X where encoding is set to US-ASCII, but we
 381          * don't have any encoding hints from LANG/LC_ALL/LC_CTYPE, use UTF-8
 382          * instead.
 383          *
 384          * The contents of ASCII files will still be read and displayed
 385          * correctly, but so will files containing UTF-8 characters beyond the
 386          * standard ASCII range.
 387          *
 388          * Specifically, this allows apps launched by double-clicking a .jar
 389          * file to correctly read UTF-8 files using the default encoding (see
 390          * 8011194).
 391          */
 392         if (strcmp(p,"US-ASCII") == 0 && getenv("LANG") == NULL &&
 393             getenv("LC_ALL") == NULL && getenv("LC_CTYPE") == NULL) {
 394             *std_encoding = "UTF-8";
 395         }
 396 #endif
 397     }
 398 
 399     free(temp);
 400     free(encoding_variant);
 401 
 402     return 1;
 403 }
 404 
 405 #ifdef JAVASE_EMBEDDED
 406 /* Determine the default embedded toolkit based on whether libawt_xawt
 407  * exists in the JRE. This can still be overridden by -Dawt.toolkit=XXX
 408  */
 409 static char* getEmbeddedToolkit() {
 410     Dl_info dlinfo;
 411     char buf[MAXPATHLEN];
 412     int32_t len;
 413     char *p;
 414     struct stat statbuf;
 415 
 416     /* Get address of this library and the directory containing it. */
 417     dladdr((void *)getEmbeddedToolkit, &dlinfo);
 418     realpath((char *)dlinfo.dli_fname, buf);
 419     len = strlen(buf);
 420     p = strrchr(buf, '/');
 421     /* Default AWT Toolkit on Linux and Solaris is XAWT (libawt_xawt.so). */
 422     strncpy(p, "/libawt_xawt.so", MAXPATHLEN-len-1);
 423     /* Check if it exists */
 424     if (stat(buf, &statbuf) == -1 && errno == ENOENT) {
 425         /* No - this is a reduced-headless-jre so use special HToolkit */
 426         return "sun.awt.HToolkit";
 427     }
 428     else {
 429         /* Yes - this is a headful JRE so fallback to SE defaults */
 430         return NULL;
 431     }
 432 }
 433 #endif
 434 
 435 /* This function gets called very early, before VM_CALLS are setup.
 436  * Do not use any of the VM_CALLS entries!!!
 437  */
 438 java_props_t *
 439 GetJavaProperties(JNIEnv *env)
 440 {
 441     static java_props_t sprops;
 442     char *v; /* tmp var */
 443 
 444     if (sprops.user_dir) {
 445         return &sprops;
 446     }
 447 
 448     /* tmp dir */
 449     sprops.tmp_dir = P_tmpdir;
 450 #ifdef MACOSX
 451     /* darwin has a per-user temp dir */
 452     static char tmp_path[PATH_MAX];
 453     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, tmp_path, PATH_MAX);
 454     if (pathSize > 0 && pathSize <= PATH_MAX) {
 455         sprops.tmp_dir = tmp_path;
 456     }
 457 #endif /* MACOSX */
 458 
 459     /* Printing properties */
 460 #ifdef MACOSX
 461     sprops.printerJob = "sun.lwawt.macosx.CPrinterJob";
 462 #else
 463     sprops.printerJob = "sun.print.PSPrinterJob";
 464 #endif
 465 
 466     /* patches/service packs installed */
 467     sprops.patch_level = "unknown";
 468 
 469     /* Java 2D/AWT properties */
 470 #ifdef MACOSX
 471     // Always the same GraphicsEnvironment and Toolkit on Mac OS X
 472     sprops.graphics_env = "sun.awt.CGraphicsEnvironment";
 473     sprops.awt_toolkit = "sun.lwawt.macosx.LWCToolkit";
 474 
 475     // check if we're in a GUI login session and set java.awt.headless=true if not
 476     sprops.awt_headless = isInAquaSession() ? NULL : "true";
 477 #else
 478     sprops.graphics_env = "sun.awt.X11GraphicsEnvironment";
 479 #ifdef JAVASE_EMBEDDED
 480     sprops.awt_toolkit = getEmbeddedToolkit();
 481     if (sprops.awt_toolkit == NULL) // default as below
 482 #endif
 483     sprops.awt_toolkit = "sun.awt.X11.XToolkit";
 484 #endif
 485 
 486     /* This is used only for debugging of font problems. */
 487     v = getenv("JAVA2D_FONTPATH");
 488     sprops.font_dir = v ? v : NULL;
 489 
 490 #ifdef SI_ISALIST
 491     /* supported instruction sets */
 492     {
 493         char list[258];
 494         sysinfo(SI_ISALIST, list, sizeof(list));
 495         sprops.cpu_isalist = strdup(list);
 496     }
 497 #else
 498     sprops.cpu_isalist = NULL;
 499 #endif
 500 
 501     /* endianness of platform */
 502     {
 503         unsigned int endianTest = 0xff000000;
 504         if (((char*)(&endianTest))[0] != 0)
 505             sprops.cpu_endian = "big";
 506         else
 507             sprops.cpu_endian = "little";
 508     }
 509 
 510     /* os properties */
 511     {
 512 #ifdef MACOSX
 513         setOSNameAndVersion(&sprops);
 514 #else
 515         struct utsname name;
 516         uname(&name);
 517         sprops.os_name = strdup(name.sysname);
 518         sprops.os_version = strdup(name.release);
 519 #endif
 520 
 521         sprops.os_arch = ARCHPROPNAME;
 522 
 523         if (getenv("GNOME_DESKTOP_SESSION_ID") != NULL) {
 524             sprops.desktop = "gnome";
 525         }
 526         else {
 527             sprops.desktop = NULL;
 528         }
 529     }
 530 
 531     /* ABI property (optional) */
 532 #ifdef JDK_ARCH_ABI_PROP_NAME
 533     sprops.sun_arch_abi = JDK_ARCH_ABI_PROP_NAME;
 534 #endif
 535 
 536     /* Determine the language, country, variant, and encoding from the host,
 537      * and store these in the user.language, user.country, user.variant and
 538      * file.encoding system properties. */
 539     setlocale(LC_ALL, "");
 540     if (ParseLocale(env, LC_CTYPE,
 541                     &(sprops.format_language),
 542                     &(sprops.format_script),
 543                     &(sprops.format_country),
 544                     &(sprops.format_variant),
 545                     &(sprops.encoding))) {
 546         ParseLocale(env, LC_MESSAGES,
 547                     &(sprops.language),
 548                     &(sprops.script),
 549                     &(sprops.country),
 550                     &(sprops.variant),
 551                     NULL);
 552     } else {
 553         sprops.language = "en";
 554         sprops.encoding = "ISO8859-1";
 555     }
 556     sprops.display_language = sprops.language;
 557     sprops.display_script = sprops.script;
 558     sprops.display_country = sprops.country;
 559     sprops.display_variant = sprops.variant;
 560 
 561     /* ParseLocale failed with OOME */
 562     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 563 
 564 #ifdef MACOSX
 565     sprops.sun_jnu_encoding = "UTF-8";
 566 #else
 567     sprops.sun_jnu_encoding = sprops.encoding;
 568 #endif
 569 
 570 #ifdef _ALLBSD_SOURCE
 571 #if BYTE_ORDER == _LITTLE_ENDIAN
 572      sprops.unicode_encoding = "UnicodeLittle";
 573  #else
 574      sprops.unicode_encoding = "UnicodeBig";
 575  #endif
 576 #else /* !_ALLBSD_SOURCE */
 577 #ifdef __linux__
 578 #if __BYTE_ORDER == __LITTLE_ENDIAN
 579     sprops.unicode_encoding = "UnicodeLittle";
 580 #else
 581     sprops.unicode_encoding = "UnicodeBig";
 582 #endif
 583 #else
 584     sprops.unicode_encoding = "UnicodeBig";
 585 #endif
 586 #endif /* _ALLBSD_SOURCE */
 587 
 588     /* user properties */
 589     {
 590         struct passwd *pwent = getpwuid(getuid());
 591         sprops.user_name = pwent ? strdup(pwent->pw_name) : "?";
 592 #ifdef MACOSX
 593         setUserHome(&sprops);
 594 #else
 595         sprops.user_home = pwent ? strdup(pwent->pw_dir) : NULL;
 596 #endif
 597         if (sprops.user_home == NULL) {
 598             sprops.user_home = "?";
 599         }
 600     }
 601 
 602     /* User TIMEZONE */
 603     {
 604         /*
 605          * We defer setting up timezone until it's actually necessary.
 606          * Refer to TimeZone.getDefault(). However, the system
 607          * property is necessary to be able to be set by the command
 608          * line interface -D. Here temporarily set a null string to
 609          * timezone.
 610          */
 611         tzset();        /* for compatibility */
 612         sprops.timezone = "";
 613     }
 614 
 615     /* Current directory */
 616     {
 617         char buf[MAXPATHLEN];
 618         errno = 0;
 619         if (getcwd(buf, sizeof(buf))  == NULL)
 620             JNU_ThrowByName(env, "java/lang/Error",
 621              "Properties init: Could not determine current working directory.");
 622         else
 623             sprops.user_dir = strdup(buf);
 624     }
 625 
 626     sprops.file_separator = "/";
 627     sprops.path_separator = ":";
 628     sprops.line_separator = "\n";
 629 
 630 #if !defined(_ALLBSD_SOURCE)
 631     /* Append CDE message and resource search path to NLSPATH and
 632      * XFILESEARCHPATH, in order to pick localized message for
 633      * FileSelectionDialog window (Bug 4173641).
 634      */
 635     setPathEnvironment("NLSPATH=/usr/dt/lib/nls/msg/%L/%N.cat");
 636     setPathEnvironment("XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt");
 637 #endif
 638 
 639 
 640 #ifdef MACOSX
 641     setProxyProperties(&sprops);
 642 #endif
 643 
 644     return &sprops;
 645 }
 646 
 647 jstring
 648 GetStringPlatform(JNIEnv *env, nchar* cstr)
 649 {
 650     return JNU_NewStringPlatform(env, cstr);
 651 }