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