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