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