1 /*
   2  * Copyright (c) 1998, 2011, 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(int cat, char ** std_language, char ** std_script,
 139                        char ** std_country, char ** std_variant, char ** std_encoding) {
 140     char temp[64];
 141     char *language = NULL, *country = NULL, *variant = NULL,
 142          *encoding = NULL;
 143     char *p, encoding_variant[64];
 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     if (cat == LC_CTYPE) {
 160         /*
 161          * Workaround for Solaris bug 4201684: Xlib doesn't like @euro
 162          * locales. Since we don't depend on the libc @euro behavior,
 163          * we just remove the qualifier.
 164          * On Linux, the bug doesn't occur; on the other hand, @euro
 165          * is needed there because it's a shortcut that also determines
 166          * the encoding - without it, we wouldn't get ISO-8859-15.
 167          * Therefore, this code section is Solaris-specific.
 168          */
 169         lc = strdup(lc);    /* keep a copy, setlocale trashes original. */
 170         strcpy(temp, lc);
 171         p = strstr(temp, "@euro");
 172         if (p != NULL) {
 173             *p = '\0';
 174             setlocale(LC_ALL, temp);
 175         }
 176     }
 177 #else
 178     if (lc == NULL || !strcmp(lc, "C") || !strcmp(lc, "POSIX")) {
 179         lc = "en_US";
 180     }
 181 #endif
 182 
 183     /*
 184      * locale string format in Solaris is
 185      * <language name>_<country name>.<encoding name>@<variant name>
 186      * <country name>, <encoding name>, and <variant name> are optional.
 187      */
 188 
 189     strcpy(temp, lc);
 190 #ifdef MACOSX
 191     free(lc); // malloced memory
 192 #endif
 193     /* Parse the language, country, encoding, and variant from the
 194      * locale.  Any of the elements may be missing, but they must occur
 195      * in the order language_country.encoding@variant, and must be
 196      * preceded by their delimiter (except for language).
 197      *
 198      * If the locale name (without .encoding@variant, if any) matches
 199      * any of the names in the locale_aliases list, map it to the
 200      * corresponding full locale name.  Most of the entries in the
 201      * locale_aliases list are locales that include a language name but
 202      * no country name, and this facility is used to map each language
 203      * to a default country if that's possible.  It's also used to map
 204      * the Solaris locale aliases to their proper Java locale IDs.
 205      */
 206     if ((p = strchr(temp, '.')) != NULL) {
 207         strcpy(encoding_variant, p); /* Copy the leading '.' */
 208         *p = '\0';
 209     } else if ((p = strchr(temp, '@')) != NULL) {
 210         strcpy(encoding_variant, p); /* Copy the leading '@' */
 211         *p = '\0';
 212     } else {
 213         *encoding_variant = '\0';
 214     }
 215 
 216     if (mapLookup(locale_aliases, temp, &p)) {
 217         strcpy(temp, p);
 218         // check the "encoding_variant" again, if any.
 219         if ((p = strchr(temp, '.')) != NULL) {
 220             strcpy(encoding_variant, p); /* Copy the leading '.' */
 221             *p = '\0';
 222         } else if ((p = strchr(temp, '@')) != NULL) {
 223             strcpy(encoding_variant, p); /* Copy the leading '@' */
 224             *p = '\0';
 225         }
 226     }
 227 
 228     language = temp;
 229     if ((country = strchr(temp, '_')) != NULL) {
 230         *country++ = '\0';
 231     }
 232 
 233     p = encoding_variant;
 234     if ((encoding = strchr(p, '.')) != NULL) {
 235         p[encoding++ - p] = '\0';
 236         p = encoding;
 237     }
 238     if ((variant = strchr(p, '@')) != NULL) {
 239         p[variant++ - p] = '\0';
 240     }
 241 
 242     /* Normalize the language name */
 243     if (std_language != NULL) {
 244         *std_language = "en";
 245         if (language != NULL && mapLookup(language_names, language, std_language) == 0) {
 246             *std_language = malloc(strlen(language)+1);
 247             strcpy(*std_language, language);
 248         }
 249     }
 250 
 251     /* Normalize the country name */
 252     if (std_country != NULL && country != NULL) {
 253         if (mapLookup(country_names, country, std_country) == 0) {
 254             *std_country = malloc(strlen(country)+1);
 255             strcpy(*std_country, country);
 256         }
 257     }
 258 
 259     /* Normalize the script and variant name.  Note that we only use
 260      * variants listed in the mapping array; others are ignored.
 261      */
 262     if (variant != NULL) {
 263         if (std_script != NULL) {
 264             mapLookup(script_names, variant, std_script);
 265         }
 266 
 267         if (std_variant != NULL) {
 268             mapLookup(variant_names, variant, std_variant);
 269         }
 270     }
 271 
 272     /* Normalize the encoding name.  Note that we IGNORE the string
 273      * 'encoding' extracted from the locale name above.  Instead, we use the
 274      * more reliable method of calling nl_langinfo(CODESET).  This function
 275      * returns an empty string if no encoding is set for the given locale
 276      * (e.g., the C or POSIX locales); we use the default ISO 8859-1
 277      * converter for such locales.
 278      */
 279     if (std_encoding != NULL) {
 280         /* OK, not so reliable - nl_langinfo() gives wrong answers on
 281          * Euro locales, in particular. */
 282         if (strcmp(p, "ISO8859-15") == 0)
 283             p = "ISO8859-15";
 284         else
 285             p = nl_langinfo(CODESET);
 286 
 287         /* Convert the bare "646" used on Solaris to a proper IANA name */
 288         if (strcmp(p, "646") == 0)
 289             p = "ISO646-US";
 290 
 291         /* return same result nl_langinfo would return for en_UK,
 292          * in order to use optimizations. */
 293         *std_encoding = (*p != '\0') ? p : "ISO8859-1";
 294 
 295 #ifdef __linux__
 296         /*
 297          * Remap the encoding string to a different value for japanese
 298          * locales on linux so that customized converters are used instead
 299          * of the default converter for "EUC-JP". The customized converters
 300          * omit support for the JIS0212 encoding which is not supported by
 301          * the variant of "EUC-JP" encoding used on linux
 302          */
 303         if (strcmp(p, "EUC-JP") == 0) {
 304             *std_encoding = "EUC-JP-LINUX";
 305         }
 306 #else
 307         if (strcmp(p,"eucJP") == 0) {
 308             /* For Solaris use customized vendor defined character
 309              * customized EUC-JP converter
 310              */
 311             *std_encoding = "eucJP-open";
 312         } else if (strcmp(p, "Big5") == 0 || strcmp(p, "BIG5") == 0) {
 313             /*
 314              * Remap the encoding string to Big5_Solaris which augments
 315              * the default converter for Solaris Big5 locales to include
 316              * seven additional ideographic characters beyond those included
 317              * in the Java "Big5" converter.
 318              */
 319             *std_encoding = "Big5_Solaris";
 320         } else if (strcmp(p, "Big5-HKSCS") == 0) {
 321             /*
 322              * Solaris uses HKSCS2001
 323              */
 324             *std_encoding = "Big5-HKSCS-2001";
 325         }
 326 #endif
 327     }
 328 
 329     return 1;
 330 }
 331 
 332 #ifdef JAVASE_EMBEDDED
 333 /* Determine the default embedded toolkit based on whether lib/xawt/
 334  * exists in the JRE. This can still be overridden by -Dawt.toolkit=XXX
 335  */
 336 static char* getEmbeddedToolkit() {
 337     Dl_info dlinfo;
 338     char buf[MAXPATHLEN];
 339     int32_t len;
 340     char *p;
 341     struct stat statbuf;
 342 
 343     /* Get address of this library and the directory containing it. */
 344     dladdr((void *)getEmbeddedToolkit, &dlinfo);
 345     realpath((char *)dlinfo.dli_fname, buf);
 346     len = strlen(buf);
 347     p = strrchr(buf, '/');
 348     /* Default AWT Toolkit on Linux and Solaris is XAWT. */
 349     strncpy(p, "/xawt/", MAXPATHLEN-len-1);
 350     /* Check if it exists */
 351     if (stat(buf, &statbuf) == -1 && errno == ENOENT) {
 352         /* No - this is a reduced-headless-jre so use special HToolkit */
 353         return "sun.awt.HToolkit";
 354     }
 355     else {
 356         /* Yes - this is a headful JRE so fallback to SE defaults */
 357         return NULL;
 358     }
 359 }
 360 #endif
 361 
 362 /* This function gets called very early, before VM_CALLS are setup.
 363  * Do not use any of the VM_CALLS entries!!!
 364  */
 365 java_props_t *
 366 GetJavaProperties(JNIEnv *env)
 367 {
 368     static java_props_t sprops;
 369     char *v; /* tmp var */
 370 
 371     if (sprops.user_dir) {
 372         return &sprops;
 373     }
 374 
 375     /* tmp dir */
 376     sprops.tmp_dir = P_tmpdir;
 377 #ifdef MACOSX
 378     /* darwin has a per-user temp dir */
 379     static char tmp_path[PATH_MAX];
 380     int pathSize = confstr(_CS_DARWIN_USER_TEMP_DIR, tmp_path, PATH_MAX);
 381     if (pathSize > 0 && pathSize <= PATH_MAX) {
 382         sprops.tmp_dir = tmp_path;
 383     }
 384 #endif /* MACOSX */
 385 
 386     /* Printing properties */
 387 #ifdef MACOSX
 388     sprops.printerJob = "sun.lwawt.macosx.CPrinterJob";
 389 #else
 390     sprops.printerJob = "sun.print.PSPrinterJob";
 391 #endif
 392 
 393     /* patches/service packs installed */
 394     sprops.patch_level = "unknown";
 395 
 396     /* Java 2D properties */
 397 #ifdef MACOSX
 398     PreferredToolkit prefToolkit = getPreferredToolkit();
 399     switch (prefToolkit) {
 400         case CToolkit:
 401             sprops.graphics_env = "sun.awt.CGraphicsEnvironment";
 402             break;
 403         case XToolkit:
 404 #endif
 405     sprops.graphics_env = "sun.awt.X11GraphicsEnvironment";
 406 #ifdef MACOSX
 407             break;
 408         default:
 409             sprops.graphics_env = "sun.java2d.HeadlessGraphicsEnvironment";
 410             break;
 411     }
 412 #endif
 413     /* AWT properties */
 414 #ifdef JAVASE_EMBEDDED
 415     sprops.awt_toolkit = getEmbeddedToolkit();
 416     if (sprops.awt_toolkit == NULL) // default as below
 417 #endif
 418 #ifdef MACOSX
 419         switch (prefToolkit) {
 420             case CToolkit:
 421                 sprops.awt_toolkit = "sun.lwawt.macosx.LWCToolkit";
 422                 break;
 423             case XToolkit:
 424 #endif
 425     sprops.awt_toolkit = "sun.awt.X11.XToolkit";
 426 #ifdef MACOSX
 427                 break;
 428             default:
 429                 sprops.awt_toolkit = "sun.awt.HToolkit";
 430                 break;
 431         }
 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         sprops.os_version = strdup(name.release);
 467 #endif
 468 
 469         sprops.os_arch = ARCHPROPNAME;
 470 
 471         if (getenv("GNOME_DESKTOP_SESSION_ID") != NULL) {
 472             sprops.desktop = "gnome";
 473         }
 474         else {
 475             sprops.desktop = NULL;
 476         }
 477     }
 478 
 479     /* Determine the language, country, variant, and encoding from the host,
 480      * and store these in the user.language, user.country, user.variant and
 481      * file.encoding system properties. */
 482     setlocale(LC_ALL, "");
 483     if (ParseLocale(LC_CTYPE,
 484                     &(sprops.format_language),
 485                     &(sprops.format_script),
 486                     &(sprops.format_country),
 487                     &(sprops.format_variant),
 488                     &(sprops.encoding))) {
 489         ParseLocale(LC_MESSAGES,
 490                     &(sprops.language),
 491                     &(sprops.script),
 492                     &(sprops.country),
 493                     &(sprops.variant),
 494                     NULL);
 495     } else {
 496         sprops.language = "en";
 497         sprops.encoding = "ISO8859-1";
 498     }
 499     sprops.display_language = sprops.language;
 500     sprops.display_script = sprops.script;
 501     sprops.display_country = sprops.country;
 502     sprops.display_variant = sprops.variant;
 503     sprops.sun_jnu_encoding = sprops.encoding;
 504 
 505 #ifdef _ALLBSD_SOURCE
 506 #if BYTE_ORDER == _LITTLE_ENDIAN
 507      sprops.unicode_encoding = "UnicodeLittle";
 508  #else
 509      sprops.unicode_encoding = "UnicodeBig";
 510  #endif
 511 #else /* !_ALLBSD_SOURCE */
 512 #ifdef __linux__
 513 #if __BYTE_ORDER == __LITTLE_ENDIAN
 514     sprops.unicode_encoding = "UnicodeLittle";
 515 #else
 516     sprops.unicode_encoding = "UnicodeBig";
 517 #endif
 518 #else
 519     sprops.unicode_encoding = "UnicodeBig";
 520 #endif
 521 #endif /* _ALLBSD_SOURCE */
 522 
 523     /* user properties */
 524     {
 525         struct passwd *pwent = getpwuid(getuid());
 526         sprops.user_name = pwent ? strdup(pwent->pw_name) : "?";
 527         sprops.user_home = pwent ? strdup(pwent->pw_dir) : "?";
 528     }
 529 
 530     /* User TIMEZONE */
 531     {
 532         /*
 533          * We defer setting up timezone until it's actually necessary.
 534          * Refer to TimeZone.getDefault(). However, the system
 535          * property is necessary to be able to be set by the command
 536          * line interface -D. Here temporarily set a null string to
 537          * timezone.
 538          */
 539         tzset();        /* for compatibility */
 540         sprops.timezone = "";
 541     }
 542 
 543     /* Current directory */
 544     {
 545         char buf[MAXPATHLEN];
 546         errno = 0;
 547         if (getcwd(buf, sizeof(buf))  == NULL)
 548             JNU_ThrowByName(env, "java/lang/Error",
 549              "Properties init: Could not determine current working directory.");
 550         else
 551             sprops.user_dir = strdup(buf);
 552     }
 553 
 554     sprops.file_separator = "/";
 555     sprops.path_separator = ":";
 556     sprops.line_separator = "\n";
 557 
 558 #if !defined(_ALLBSD_SOURCE)
 559     /* Append CDE message and resource search path to NLSPATH and
 560      * XFILESEARCHPATH, in order to pick localized message for
 561      * FileSelectionDialog window (Bug 4173641).
 562      */
 563     setPathEnvironment("NLSPATH=/usr/dt/lib/nls/msg/%L/%N.cat");
 564     setPathEnvironment("XFILESEARCHPATH=/usr/dt/app-defaults/%L/Dt");
 565 #endif
 566 
 567 
 568 #ifdef MACOSX
 569     setProxyProperties(&sprops);
 570 #endif
 571 
 572     return &sprops;
 573 }
 574 
 575 jstring
 576 GetStringPlatform(JNIEnv *env, nchar* cstr)
 577 {
 578     return JNU_NewStringPlatform(env, cstr);
 579 }