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