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