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