1 /*
   2  * Copyright (c) 1998, 2017, 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 <sys/socket.h>
  27 #include <netinet/in.h>
  28 #include <arpa/inet.h>
  29 #include <objc/objc-runtime.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 char *getPosixLocale(int cat) {
  39     char *lc = setlocale(cat, NULL);
  40     if ((lc == NULL) || (strcmp(lc, "C") == 0)) {
  41         lc = getenv("LANG");
  42     }
  43     if (lc == NULL) return NULL;
  44     return strdup(lc);
  45 }
  46 
  47 #define LOCALEIDLENGTH  128
  48 char *getMacOSXLocale(int cat) {
  49     const char* retVal = NULL;
  50 
  51     switch (cat) {
  52     case LC_MESSAGES:
  53         {
  54             // get preferred language code
  55             CFArrayRef languages = CFLocaleCopyPreferredLanguages();
  56             if (languages == NULL) {
  57                 return NULL;
  58             }
  59             if (CFArrayGetCount(languages) <= 0) {
  60                 CFRelease(languages);
  61                 return NULL;
  62             }
  63 
  64             CFStringRef primaryLanguage = (CFStringRef)CFArrayGetValueAtIndex(languages, 0);
  65             if (primaryLanguage == NULL) {
  66                 CFRelease(languages);
  67                 return NULL;
  68             }
  69             char languageString[LOCALEIDLENGTH];
  70             if (CFStringGetCString(primaryLanguage, languageString,
  71                                    LOCALEIDLENGTH, CFStringGetSystemEncoding()) == false) {
  72                 CFRelease(languages);
  73                 return NULL;
  74             }
  75             CFRelease(languages);
  76 
  77             retVal = languageString;
  78 
  79             // Special case for Portuguese in Brazil:
  80             // The language code needs the "_BR" region code (to distinguish it
  81             // from Portuguese in Portugal), but this is missing when using the
  82             // "Portuguese (Brazil)" language.
  83             // If language is "pt" and the current locale is pt_BR, return pt_BR.
  84             char localeString[LOCALEIDLENGTH];
  85             if (strcmp(retVal, "pt") == 0 &&
  86                     CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
  87                                        localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding()) &&
  88                     strcmp(localeString, "pt_BR") == 0) {
  89                 retVal = localeString;
  90             }
  91         }
  92         break;
  93     default:
  94         {
  95             char localeString[LOCALEIDLENGTH];
  96             if (!CFStringGetCString(CFLocaleGetIdentifier(CFLocaleCopyCurrent()),
  97                                    localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {
  98                 return NULL;
  99             }
 100             retVal = localeString;
 101         }
 102         break;
 103     }
 104 
 105     if (retVal != NULL) {
 106         // Language IDs use the language designators and (optional) region
 107         // and script designators of BCP 47.  So possible formats are:
 108         //
 109         // "en"         (language designator only)
 110         // "haw"        (3-letter lanuage designator)
 111         // "en-GB"      (language with alpha-2 region designator)
 112         // "es-419"     (language with 3-digit UN M.49 area code)
 113         // "zh-Hans"    (language with ISO 15924 script designator)
 114         // "zh-Hans-US"  (language with ISO 15924 script designator and region)
 115         // "zh-Hans-419" (language with ISO 15924 script designator and UN M.49)
 116         //
 117         // In the case of region designators (alpha-2 and/or UN M.49), we convert
 118         // to our locale string format by changing '-' to '_'.  That is, if
 119         // the '-' is followed by fewer than 4 chars.
 120         char* scriptOrRegion = strchr(retVal, '-');
 121         if (scriptOrRegion != NULL) {
 122             int length = strlen(scriptOrRegion);
 123             if (length > 5) {
 124                 // Region and script both exist. Honor the script for now
 125                 scriptOrRegion[5] = '\0';
 126             } else if (length < 5) {
 127                 *scriptOrRegion = '_';
 128 
 129                 assert((length == 3 &&
 130                     // '-' followed by a 2 character region designator
 131                       isalpha(scriptOrRegion[1]) &&
 132                       isalpha(scriptOrRegion[2])) ||
 133                        (length == 4 &&
 134                     // '-' followed by a 3-digit UN M.49 area code
 135                       isdigit(scriptOrRegion[1]) &&
 136                       isdigit(scriptOrRegion[2]) &&
 137                       isdigit(scriptOrRegion[3])));
 138             }
 139         }
 140 
 141         return strdup(retVal);
 142     }
 143     return NULL;
 144 }
 145 
 146 char *setupMacOSXLocale(int cat) {
 147     char * ret = getMacOSXLocale(cat);
 148 
 149     if (ret == NULL) {
 150         return getPosixLocale(cat);
 151     } else {
 152         return ret;
 153     }
 154 }
 155 
 156 int isInAquaSession() {
 157     // environment variable to bypass the aqua session check
 158     char *ev = getenv("AWT_FORCE_HEADFUL");
 159     if (ev && (strncasecmp(ev, "true", 4) == 0)) {
 160         // if "true" then tell the caller we're in an Aqua session without actually checking
 161         return 1;
 162     }
 163     // Is the WindowServer available?
 164     SecuritySessionId session_id;
 165     SessionAttributeBits session_info;
 166     OSStatus status = SessionGetInfo(callerSecuritySession, &session_id, &session_info);
 167     if (status == noErr) {
 168         if (session_info & sessionHasGraphicAccess) {
 169             return 1;
 170         }
 171     }
 172     return 0;
 173 }
 174 
 175 // 10.9 SDK does not include the NSOperatingSystemVersion struct.
 176 // For now, create our own
 177 typedef struct {
 178         NSInteger majorVersion;
 179         NSInteger minorVersion;
 180         NSInteger patchVersion;
 181 } OSVerStruct;
 182 
 183 void setOSNameAndVersion(java_props_t *sprops) {
 184     // Hardcode os_name, and fill in os_version
 185     sprops->os_name = strdup("Mac OS X");
 186 
 187     char* osVersionCStr = NULL;
 188     // Mac OS 10.9 includes the [NSProcessInfo operatingSystemVersion] function,
 189     // but it's not in the 10.9 SDK.  So, call it via objc_msgSend_stret.
 190     if ([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {
 191         OSVerStruct (*procInfoFn)(id rec, SEL sel) = (OSVerStruct(*)(id, SEL))objc_msgSend_stret;
 192         OSVerStruct osVer = procInfoFn([NSProcessInfo processInfo],
 193                                        @selector(operatingSystemVersion));
 194         NSString *nsVerStr;
 195         if (osVer.patchVersion == 0) { // Omit trailing ".0"
 196             nsVerStr = [NSString stringWithFormat:@"%ld.%ld",
 197                     (long)osVer.majorVersion, (long)osVer.minorVersion];
 198         } else {
 199             nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",
 200                     (long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];
 201         }
 202         // Copy out the char*
 203         osVersionCStr = strdup([nsVerStr UTF8String]);
 204     }
 205     // Fallback if running on pre-10.9 Mac OS
 206     if (osVersionCStr == NULL) {
 207         NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :
 208                                  @"/System/Library/CoreServices/SystemVersion.plist"];
 209         if (version != NULL) {
 210             NSString *nsVerStr = [version objectForKey : @"ProductVersion"];
 211             if (nsVerStr != NULL) {
 212                 osVersionCStr = strdup([nsVerStr UTF8String]);
 213             }
 214         }
 215     }
 216     if (osVersionCStr == NULL) {
 217         osVersionCStr = strdup("Unknown");
 218     }
 219     sprops->os_version = osVersionCStr;
 220 }
 221 
 222 
 223 static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey,
 224                                        CFStringRef inHostKey, CFStringRef inPortKey,
 225                                        CFStringRef *outProxyHost, int *ioProxyPort) {
 226     /* See if the proxy is enabled. */
 227     CFNumberRef cf_enabled = CFDictionaryGetValue(inDict, inEnabledKey);
 228     if (cf_enabled == NULL) {
 229         return false;
 230     }
 231 
 232     int isEnabled = false;
 233     if (!CFNumberGetValue(cf_enabled, kCFNumberIntType, &isEnabled)) {
 234         return isEnabled;
 235     }
 236 
 237     if (!isEnabled) return false;
 238     *outProxyHost = CFDictionaryGetValue(inDict, inHostKey);
 239 
 240     // If cf_host is null, that means the checkbox is set,
 241     //   but no host was entered. We'll treat that as NOT ENABLED.
 242     // If cf_port is null or cf_port isn't a number, that means
 243     //   no port number was entered. Treat this as ENABLED with the
 244     //   protocol's default port.
 245     if (*outProxyHost == NULL) {
 246         return false;
 247     }
 248 
 249     if (CFStringGetLength(*outProxyHost) == 0) {
 250         return false;
 251     }
 252 
 253     int newPort = 0;
 254     CFNumberRef cf_port = NULL;
 255     if ((cf_port = CFDictionaryGetValue(inDict, inPortKey)) != NULL &&
 256         CFNumberGetValue(cf_port, kCFNumberIntType, &newPort) &&
 257         newPort > 0) {
 258         *ioProxyPort = newPort;
 259     } else {
 260         // bad port or no port - leave *ioProxyPort unchanged
 261     }
 262 
 263     return true;
 264 }
 265 
 266 static char *createUTF8CString(const CFStringRef theString) {
 267     if (theString == NULL) return NULL;
 268 
 269     const CFIndex stringLength = CFStringGetLength(theString);
 270     const CFIndex bufSize = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 1;
 271     char *returnVal = (char *)malloc(bufSize);
 272 
 273     if (CFStringGetCString(theString, returnVal, bufSize, kCFStringEncodingUTF8)) {
 274         return returnVal;
 275     }
 276 
 277     free(returnVal);
 278     return NULL;
 279 }
 280 
 281 // Return TRUE if str is a syntactically valid IP address.
 282 // Using inet_pton() instead of inet_aton() for IPv6 support.
 283 // len is only a hint; cstr must still be nul-terminated
 284 static int looksLikeIPAddress(char *cstr, size_t len) {
 285     if (len == 0  ||  (len == 1 && cstr[0] == '.')) return FALSE;
 286 
 287     char dst[16]; // big enough for INET6
 288     return (1 == inet_pton(AF_INET, cstr, dst)  ||
 289             1 == inet_pton(AF_INET6, cstr, dst));
 290 }
 291 
 292 
 293 
 294 // Convert Mac OS X proxy exception entry to Java syntax.
 295 // See Radar #3441134 for details.
 296 // Returns NULL if this exception should be ignored by Java.
 297 // May generate a string with multiple exceptions separated by '|'.
 298 static char * createConvertedException(CFStringRef cf_original) {
 299     // This is done with char* instead of CFString because inet_pton()
 300     // needs a C string.
 301     char *c_exception = createUTF8CString(cf_original);
 302     if (!c_exception) return NULL;
 303 
 304     int c_len = strlen(c_exception);
 305 
 306     // 1. sanitize exception prefix
 307     if (c_len >= 1  &&  0 == strncmp(c_exception, ".", 1)) {
 308         memmove(c_exception, c_exception+1, c_len);
 309         c_len -= 1;
 310     } else if (c_len >= 2  &&  0 == strncmp(c_exception, "*.", 2)) {
 311         memmove(c_exception, c_exception+2, c_len-1);
 312         c_len -= 2;
 313     }
 314 
 315     // 2. pre-reject other exception wildcards
 316     if (strchr(c_exception, '*')) {
 317         free(c_exception);
 318         return NULL;
 319     }
 320 
 321     // 3. no IP wildcarding
 322     if (looksLikeIPAddress(c_exception, c_len)) {
 323         return c_exception;
 324     }
 325 
 326     // 4. allow domain suffixes
 327     // c_exception is now "str\0" - change to "str|*.str\0"
 328     c_exception = reallocf(c_exception, c_len+3+c_len+1);
 329     if (!c_exception) return NULL;
 330 
 331     strncpy(c_exception+c_len, "|*.", 3);
 332     strncpy(c_exception+c_len+3, c_exception, c_len);
 333     c_exception[c_len+3+c_len] = '\0';
 334     return c_exception;
 335 }
 336 
 337 /*
 338  * Method for fetching the user.home path and storing it in the property list.
 339  * For signed .apps running in the Mac App Sandbox, user.home is set to the
 340  * app's sandbox container.
 341  */
 342 void setUserHome(java_props_t *sprops) {
 343     if (sprops == NULL) { return; }
 344     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 345     sprops->user_home = createUTF8CString((CFStringRef)NSHomeDirectory());
 346     [pool drain];
 347 }
 348 
 349 /*
 350  * Method for fetching proxy info and storing it in the property list.
 351  */
 352 void setProxyProperties(java_props_t *sProps) {
 353     if (sProps == NULL) return;
 354 
 355     char buf[16];    /* Used for %d of an int - 16 is plenty */
 356     CFStringRef
 357     cf_httpHost = NULL,
 358     cf_httpsHost = NULL,
 359     cf_ftpHost = NULL,
 360     cf_socksHost = NULL,
 361     cf_gopherHost = NULL;
 362     int
 363     httpPort = 80, // Default proxy port values
 364     httpsPort = 443,
 365     ftpPort = 21,
 366     socksPort = 1080,
 367     gopherPort = 70;
 368 
 369     CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);
 370     if (dict == NULL) return;
 371 
 372     /* Read the proxy exceptions list */
 373     CFArrayRef cf_list = CFDictionaryGetValue(dict, kSCPropNetProxiesExceptionsList);
 374 
 375     CFMutableStringRef cf_exceptionList = NULL;
 376     if (cf_list != NULL) {
 377         CFIndex len = CFArrayGetCount(cf_list), idx;
 378 
 379         cf_exceptionList = CFStringCreateMutable(NULL, 0);
 380         for (idx = (CFIndex)0; idx < len; idx++) {
 381             CFStringRef cf_ehost;
 382             if ((cf_ehost = CFArrayGetValueAtIndex(cf_list, idx))) {
 383                 /* Convert this exception from Mac OS X syntax to Java syntax.
 384                  See Radar #3441134 for details. This may generate a string
 385                  with multiple Java exceptions separated by '|'. */
 386                 char *c_exception = createConvertedException(cf_ehost);
 387                 if (c_exception) {
 388                     /* Append the host to the list of exclusions. */
 389                     if (CFStringGetLength(cf_exceptionList) > 0) {
 390                         CFStringAppendCString(cf_exceptionList, "|", kCFStringEncodingMacRoman);
 391                     }
 392                     CFStringAppendCString(cf_exceptionList, c_exception, kCFStringEncodingMacRoman);
 393                     free(c_exception);
 394                 }
 395             }
 396         }
 397     }
 398 
 399     if (cf_exceptionList != NULL) {
 400         if (CFStringGetLength(cf_exceptionList) > 0) {
 401             sProps->exceptionList = createUTF8CString(cf_exceptionList);
 402         }
 403         CFRelease(cf_exceptionList);
 404     }
 405 
 406 #define CHECK_PROXY(protocol, PROTOCOL)                                     \
 407     sProps->protocol##ProxyEnabled =                                        \
 408     getProxyInfoForProtocol(dict, kSCPropNetProxies##PROTOCOL##Enable,      \
 409     kSCPropNetProxies##PROTOCOL##Proxy,         \
 410     kSCPropNetProxies##PROTOCOL##Port,          \
 411     &cf_##protocol##Host, &protocol##Port);     \
 412     if (sProps->protocol##ProxyEnabled) {                                   \
 413         sProps->protocol##Host = createUTF8CString(cf_##protocol##Host);    \
 414         snprintf(buf, sizeof(buf), "%d", protocol##Port);                   \
 415         sProps->protocol##Port = malloc(strlen(buf) + 1);                   \
 416         strcpy(sProps->protocol##Port, buf);                                \
 417     }
 418 
 419     CHECK_PROXY(http, HTTP);
 420     CHECK_PROXY(https, HTTPS);
 421     CHECK_PROXY(ftp, FTP);
 422     CHECK_PROXY(socks, SOCKS);
 423     CHECK_PROXY(gopher, Gopher);
 424 
 425 #undef CHECK_PROXY
 426 
 427     CFRelease(dict);
 428 }