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 #include <dlfcn.h>
  27 #include <sys/socket.h>
  28 #include <netinet/in.h>
  29 #include <arpa/inet.h>
  30 
  31 #include <Security/AuthSession.h>
  32 #include <CoreFoundation/CoreFoundation.h>
  33 #include <SystemConfiguration/SystemConfiguration.h>
  34 #include <Foundation/Foundation.h>
  35 
  36 #include "java_props_macosx.h"
  37 
  38 // need dlopen/dlsym trick to avoid pulling in JavaRuntimeSupport before libjava.dylib is loaded
  39 static void *getJRSFramework() {
  40     static void *jrsFwk = NULL;
  41 #ifndef STATIC_BUILD
  42 // JavaRuntimeSupport doesn't support static Java runtimes
  43     if (jrsFwk == NULL) {
  44        jrsFwk = dlopen("/System/Library/Frameworks/JavaVM.framework/Frameworks/JavaRuntimeSupport.framework/JavaRuntimeSupport", RTLD_LAZY | RTLD_LOCAL);
  45     }
  46 #endif
  47     return jrsFwk;
  48 }
  49 
  50 char *getPosixLocale(int cat) {
  51     char *lc = setlocale(cat, NULL);
  52     if ((lc == NULL) || (strcmp(lc, "C") == 0)) {
  53         lc = getenv("LANG");
  54     }
  55     if (lc == NULL) return NULL;
  56     return strdup(lc);
  57 }
  58 
  59 #define LOCALEIDLENGTH  128
  60 char *getMacOSXLocale(int cat) {
  61     switch (cat) {
  62     case LC_MESSAGES:
  63         {
  64             void *jrsFwk = getJRSFramework();
  65             if (jrsFwk == NULL) return NULL;
  66 
  67             char *(*JRSCopyPrimaryLanguage)() = dlsym(jrsFwk, "JRSCopyPrimaryLanguage");
  68             char *primaryLanguage = JRSCopyPrimaryLanguage ? JRSCopyPrimaryLanguage() : NULL;
  69             if (primaryLanguage == NULL) return NULL;
  70 
  71             char *(*JRSCopyCanonicalLanguageForPrimaryLanguage)(char *) = dlsym(jrsFwk, "JRSCopyCanonicalLanguageForPrimaryLanguage");
  72             char *canonicalLanguage = JRSCopyCanonicalLanguageForPrimaryLanguage ?  JRSCopyCanonicalLanguageForPrimaryLanguage(primaryLanguage) : NULL;
  73             free (primaryLanguage);
  74 
  75             return canonicalLanguage;
  76         }
  77         break;
  78     default:
  79         {
  80             char localeString[LOCALEIDLENGTH];
  81             if (CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
  82                                    localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {
  83                 return strdup(localeString);
  84             }
  85         }
  86         break;
  87     }
  88 
  89     return NULL;
  90 }
  91 
  92 char *setupMacOSXLocale(int cat) {
  93     char * ret = getMacOSXLocale(cat);
  94 
  95     if (cat == LC_MESSAGES && ret != NULL) {
  96         void *jrsFwk = getJRSFramework();
  97         if (jrsFwk != NULL) {
  98             void (*JRSSetDefaultLocalization)(char *) = dlsym(jrsFwk, "JRSSetDefaultLocalization");
  99             if (JRSSetDefaultLocalization) JRSSetDefaultLocalization(ret);
 100         }
 101     }
 102 
 103     if (ret == NULL) {
 104         return getPosixLocale(cat);
 105     } else {
 106         return ret;
 107     }
 108 }
 109 
 110 int isInAquaSession() {
 111     // environment variable to bypass the aqua session check
 112     char *ev = getenv("AWT_FORCE_HEADFUL");
 113     if (ev && (strncasecmp(ev, "true", 4) == 0)) {
 114         // if "true" then tell the caller we're in an Aqua session without actually checking
 115         return 1;
 116     }
 117     // Is the WindowServer available?
 118     SecuritySessionId session_id;
 119     SessionAttributeBits session_info;
 120     OSStatus status = SessionGetInfo(callerSecuritySession, &session_id, &session_info);
 121     if (status == noErr) {
 122         if (session_info & sessionHasGraphicAccess) {
 123             return 1;
 124         }
 125     }
 126     return 0;
 127 }
 128 
 129 void setOSNameAndVersion(java_props_t *sprops) {
 130     /* Don't rely on JRSCopyOSName because there's no guarantee the value will
 131      * remain the same, or even if the JRS functions will continue to be part of
 132      * Mac OS X.  So hardcode os_name, and fill in os_version if we can.
 133      */
 134     sprops->os_name = strdup("Mac OS X");
 135 
 136     void *jrsFwk = getJRSFramework();
 137     if (jrsFwk != NULL) {
 138         char *(*copyOSVersion)() = dlsym(jrsFwk, "JRSCopyOSVersion");
 139         if (copyOSVersion != NULL) {
 140             sprops->os_version = copyOSVersion();
 141             return;
 142         }
 143     }
 144     sprops->os_version = strdup("Unknown");
 145 }
 146 
 147 
 148 static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey, CFStringRef inHostKey, CFStringRef inPortKey, CFStringRef *outProxyHost, int *ioProxyPort) {
 149     /* See if the proxy is enabled. */
 150     CFNumberRef cf_enabled = CFDictionaryGetValue(inDict, inEnabledKey);
 151     if (cf_enabled == NULL) {
 152         return false;
 153     }
 154 
 155     int isEnabled = false;
 156     if (!CFNumberGetValue(cf_enabled, kCFNumberIntType, &isEnabled)) {
 157         return isEnabled;
 158     }
 159 
 160     if (!isEnabled) return false;
 161     *outProxyHost = CFDictionaryGetValue(inDict, inHostKey);
 162 
 163     // If cf_host is null, that means the checkbox is set,
 164     //   but no host was entered. We'll treat that as NOT ENABLED.
 165     // If cf_port is null or cf_port isn't a number, that means
 166     //   no port number was entered. Treat this as ENABLED with the
 167     //   protocol's default port.
 168     if (*outProxyHost == NULL) {
 169         return false;
 170     }
 171 
 172     if (CFStringGetLength(*outProxyHost) == 0) {
 173         return false;
 174     }
 175 
 176     int newPort = 0;
 177     CFNumberRef cf_port = NULL;
 178     if ((cf_port = CFDictionaryGetValue(inDict, inPortKey)) != NULL &&
 179         CFNumberGetValue(cf_port, kCFNumberIntType, &newPort) &&
 180         newPort > 0) {
 181         *ioProxyPort = newPort;
 182     } else {
 183         // bad port or no port - leave *ioProxyPort unchanged
 184     }
 185 
 186     return true;
 187 }
 188 
 189 static char *createUTF8CString(const CFStringRef theString) {
 190     if (theString == NULL) return NULL;
 191 
 192     const CFIndex stringLength = CFStringGetLength(theString);
 193     const CFIndex bufSize = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 1;
 194     char *returnVal = (char *)malloc(bufSize);
 195 
 196     if (CFStringGetCString(theString, returnVal, bufSize, kCFStringEncodingUTF8)) {
 197         return returnVal;
 198     }
 199 
 200     free(returnVal);
 201     return NULL;
 202 }
 203 
 204 // Return TRUE if str is a syntactically valid IP address.
 205 // Using inet_pton() instead of inet_aton() for IPv6 support.
 206 // len is only a hint; cstr must still be nul-terminated
 207 static int looksLikeIPAddress(char *cstr, size_t len) {
 208     if (len == 0  ||  (len == 1 && cstr[0] == '.')) return FALSE;
 209 
 210     char dst[16]; // big enough for INET6
 211     return (1 == inet_pton(AF_INET, cstr, dst)  ||
 212             1 == inet_pton(AF_INET6, cstr, dst));
 213 }
 214 
 215 
 216 
 217 // Convert Mac OS X proxy exception entry to Java syntax.
 218 // See Radar #3441134 for details.
 219 // Returns NULL if this exception should be ignored by Java.
 220 // May generate a string with multiple exceptions separated by '|'.
 221 static char * createConvertedException(CFStringRef cf_original) {
 222     // This is done with char* instead of CFString because inet_pton()
 223     // needs a C string.
 224     char *c_exception = createUTF8CString(cf_original);
 225     if (!c_exception) return NULL;
 226 
 227     int c_len = strlen(c_exception);
 228 
 229     // 1. sanitize exception prefix
 230     if (c_len >= 1  &&  0 == strncmp(c_exception, ".", 1)) {
 231         memmove(c_exception, c_exception+1, c_len);
 232         c_len -= 1;
 233     } else if (c_len >= 2  &&  0 == strncmp(c_exception, "*.", 2)) {
 234         memmove(c_exception, c_exception+2, c_len-1);
 235         c_len -= 2;
 236     }
 237 
 238     // 2. pre-reject other exception wildcards
 239     if (strchr(c_exception, '*')) {
 240         free(c_exception);
 241         return NULL;
 242     }
 243 
 244     // 3. no IP wildcarding
 245     if (looksLikeIPAddress(c_exception, c_len)) {
 246         return c_exception;
 247     }
 248 
 249     // 4. allow domain suffixes
 250     // c_exception is now "str\0" - change to "str|*.str\0"
 251     c_exception = reallocf(c_exception, c_len+3+c_len+1);
 252     if (!c_exception) return NULL;
 253 
 254     strncpy(c_exception+c_len, "|*.", 3);
 255     strncpy(c_exception+c_len+3, c_exception, c_len);
 256     c_exception[c_len+3+c_len] = '\0';
 257     return c_exception;
 258 }
 259 
 260 /*
 261  * Method for fetching the user.home path and storing it in the property list.
 262  * For signed .apps running in the Mac App Sandbox, user.home is set to the
 263  * app's sandbox container.
 264  */
 265 void setUserHome(java_props_t *sprops) {
 266     if (sprops == NULL) { return; }
 267     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 268     sprops->user_home = createUTF8CString((CFStringRef)NSHomeDirectory());
 269     [pool drain];
 270 }
 271 
 272 /*
 273  * Method for fetching proxy info and storing it in the property list.
 274  */
 275 void setProxyProperties(java_props_t *sProps) {
 276     if (sProps == NULL) return;
 277 
 278     char buf[16];    /* Used for %d of an int - 16 is plenty */
 279     CFStringRef
 280     cf_httpHost = NULL,
 281     cf_httpsHost = NULL,
 282     cf_ftpHost = NULL,
 283     cf_socksHost = NULL,
 284     cf_gopherHost = NULL;
 285     int
 286     httpPort = 80, // Default proxy port values
 287     httpsPort = 443,
 288     ftpPort = 21,
 289     socksPort = 1080,
 290     gopherPort = 70;
 291 
 292     CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
 293     if (dict == NULL) return;
 294 
 295     /* Read the proxy exceptions list */
 296     CFArrayRef cf_list = CFDictionaryGetValue(dict, kSCPropNetProxiesExceptionsList);
 297 
 298     CFMutableStringRef cf_exceptionList = NULL;
 299     if (cf_list != NULL) {
 300         CFIndex len = CFArrayGetCount(cf_list), idx;
 301 
 302         cf_exceptionList = CFStringCreateMutable(NULL, 0);
 303         for (idx = (CFIndex)0; idx < len; idx++) {
 304             CFStringRef cf_ehost;
 305             if ((cf_ehost = CFArrayGetValueAtIndex(cf_list, idx))) {
 306                 /* Convert this exception from Mac OS X syntax to Java syntax.
 307                  See Radar #3441134 for details. This may generate a string
 308                  with multiple Java exceptions separated by '|'. */
 309                 char *c_exception = createConvertedException(cf_ehost);
 310                 if (c_exception) {
 311                     /* Append the host to the list of exclusions. */
 312                     if (CFStringGetLength(cf_exceptionList) > 0) {
 313                         CFStringAppendCString(cf_exceptionList, "|", kCFStringEncodingMacRoman);
 314                     }
 315                     CFStringAppendCString(cf_exceptionList, c_exception, kCFStringEncodingMacRoman);
 316                     free(c_exception);
 317                 }
 318             }
 319         }
 320     }
 321 
 322     if (cf_exceptionList != NULL) {
 323         if (CFStringGetLength(cf_exceptionList) > 0) {
 324             sProps->exceptionList = createUTF8CString(cf_exceptionList);
 325         }
 326         CFRelease(cf_exceptionList);
 327     }
 328 
 329 #define CHECK_PROXY(protocol, PROTOCOL)                                     \
 330     sProps->protocol##ProxyEnabled =                                        \
 331     getProxyInfoForProtocol(dict, kSCPropNetProxies##PROTOCOL##Enable,      \
 332     kSCPropNetProxies##PROTOCOL##Proxy,         \
 333     kSCPropNetProxies##PROTOCOL##Port,          \
 334     &cf_##protocol##Host, &protocol##Port);     \
 335     if (sProps->protocol##ProxyEnabled) {                                   \
 336         sProps->protocol##Host = createUTF8CString(cf_##protocol##Host);    \
 337         snprintf(buf, sizeof(buf), "%d", protocol##Port);                   \
 338         sProps->protocol##Port = malloc(strlen(buf) + 1);                   \
 339         strcpy(sProps->protocol##Port, buf);                                \
 340     }
 341 
 342     CHECK_PROXY(http, HTTP);
 343     CHECK_PROXY(https, HTTPS);
 344     CHECK_PROXY(ftp, FTP);
 345     CHECK_PROXY(socks, SOCKS);
 346     CHECK_PROXY(gopher, Gopher);
 347 
 348 #undef CHECK_PROXY
 349 
 350     CFRelease(dict);
 351 }