Path: blob/master/src/java.base/macosx/native/libjava/java_props_macosx.c
67769 views
/*1* Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425#include <sys/socket.h>26#include <netinet/in.h>27#include <arpa/inet.h>28#include <objc/objc-runtime.h>2930#include <CoreFoundation/CoreFoundation.h>31#ifndef TARGET_OS_IOS32#include <SystemConfiguration/SystemConfiguration.h>33#else34#include "OSXSCSchemaDefinitions.h"35#include <SystemConfiguration/SCDynamicStore.h>36CFDictionaryRef SCDynamicStoreCopyProxies(SCDynamicStoreRef store);37#endif38#include <Foundation/Foundation.h>3940#include "java_props_macosx.h"4142char *getPosixLocale(int cat) {43char *lc = setlocale(cat, NULL);44if ((lc == NULL) || (strcmp(lc, "C") == 0)) {45lc = getenv("LANG");46}47if (lc == NULL) return NULL;48return strdup(lc);49}5051#define LOCALEIDLENGTH 12852#ifndef kCFCoreFoundationVersionNumber10_11_Max53#define kCFCoreFoundationVersionNumber10_11_Max 129954#endif55char *getMacOSXLocale(int cat) {56const char* retVal = NULL;57char languageString[LOCALEIDLENGTH];58char localeString[LOCALEIDLENGTH];5960// Since macOS 10.12, there is no separate language selection for61// "format" locale, e.g., date format. Use the preferred language62// for all LC_* categories.63if (kCFCoreFoundationVersionNumber >64kCFCoreFoundationVersionNumber10_11_Max) {65cat = LC_MESSAGES;66}6768switch (cat) {69case LC_MESSAGES:70{71// get preferred language code72CFArrayRef languages = CFLocaleCopyPreferredLanguages();73if (languages == NULL) {74return NULL;75}76if (CFArrayGetCount(languages) <= 0) {77CFRelease(languages);78return NULL;79}8081CFStringRef primaryLanguage = (CFStringRef)CFArrayGetValueAtIndex(languages, 0);82if (primaryLanguage == NULL) {83CFRelease(languages);84return NULL;85}86if (CFStringGetCString(primaryLanguage, languageString,87LOCALEIDLENGTH, CFStringGetSystemEncoding()) == false) {88CFRelease(languages);89return NULL;90}91CFRelease(languages);9293// Explicitly supply region, if there is none94char *hyphenPos = strchr(languageString, '-');95int langStrLen = strlen(languageString);9697if (hyphenPos == NULL || // languageString contains ISO639 only, e.g., "en"98languageString + langStrLen - hyphenPos == 5) { // ISO639-ScriptCode, e.g., "en-Latn"99CFLocaleRef cflocale = CFLocaleCopyCurrent();100if (cflocale != NULL) {101CFStringGetCString(CFLocaleGetIdentifier(cflocale),102localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding());103char *underscorePos = strrchr(localeString, '_');104char *region = NULL;105106if (underscorePos != NULL) {107region = underscorePos + 1;108}109110if (region != NULL) {111strcat(languageString, "-");112strcat(languageString, region);113}114CFRelease(cflocale);115}116}117118retVal = languageString;119}120break;121122default:123{124CFLocaleRef cflocale = CFLocaleCopyCurrent();125if (cflocale != NULL) {126if (!CFStringGetCString(CFLocaleGetIdentifier(cflocale),127localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {128CFRelease(cflocale);129return NULL;130}131132retVal = localeString;133CFRelease(cflocale);134} else {135return NULL;136}137}138break;139}140141if (retVal != NULL) {142// convertToPOSIXLocale() does not expect any variant codes, so ignore143// '@' and anything following, if present.144char* rmAt = strchr(retVal, '@');145if (rmAt != NULL) {146*rmAt = '\0';147}148return strdup(convertToPOSIXLocale(retVal));149}150151return NULL;152}153154/* Language IDs use the language designators and (optional) region155* and script designators of BCP 47. So possible formats are:156*157* "en" (language designator only)158* "haw" (3-letter lanuage designator)159* "en-GB" (language with alpha-2 region designator)160* "es-419" (language with 3-digit UN M.49 area code)161* "zh-Hans" (language with ISO 15924 script designator)162* "zh-Hans-US" (language with ISO 15924 script designator and region)163* "zh-Hans-419" (language with ISO 15924 script designator and UN M.49)164*165* convert these tags into POSIX conforming locale string, i.e.,166* lang{_region}{@script}. e.g., for "zh-Hans-US" into "zh_US@Hans"167*/168const char * convertToPOSIXLocale(const char* src) {169char* scriptRegion = strchr(src, '-');170if (scriptRegion != NULL) {171int length = strlen(scriptRegion);172char* region = strchr(scriptRegion + 1, '-');173char* atMark = NULL;174175if (region == NULL) {176// CFLocaleGetIdentifier() returns '_' before region177region = strchr(scriptRegion + 1, '_');178}179180*scriptRegion = '_';181if (length > 5) {182// Region and script both exist.183char tmpScript[4];184int regionLength = length - 6;185atMark = scriptRegion + 1 + regionLength;186memcpy(tmpScript, scriptRegion + 1, 4);187memmove(scriptRegion + 1, region + 1, regionLength);188memcpy(atMark + 1, tmpScript, 4);189} else if (length == 5) {190// script only191atMark = scriptRegion;192}193194if (atMark != NULL) {195*atMark = '@';196197// assert script code198assert(isalpha(atMark[1]) &&199isalpha(atMark[2]) &&200isalpha(atMark[3]) &&201isalpha(atMark[4]));202}203204assert(((length == 3 || length == 8) &&205// '_' followed by a 2 character region designator206isalpha(scriptRegion[1]) &&207isalpha(scriptRegion[2])) ||208((length == 4 || length == 9) &&209// '_' followed by a 3-digit UN M.49 area code210isdigit(scriptRegion[1]) &&211isdigit(scriptRegion[2]) &&212isdigit(scriptRegion[3])) ||213// '@' followed by a 4 character script code (already validated above)214(length == 5));215}216217return src;218}219220char *setupMacOSXLocale(int cat) {221char * ret = getMacOSXLocale(cat);222223if (ret == NULL) {224return getPosixLocale(cat);225} else {226return ret;227}228}229230// 10.9 SDK does not include the NSOperatingSystemVersion struct.231// For now, create our own232typedef struct {233NSInteger majorVersion;234NSInteger minorVersion;235NSInteger patchVersion;236} OSVerStruct;237238void setOSNameAndVersion(java_props_t *sprops) {239// Hardcode os_name, and fill in os_version240sprops->os_name = strdup("Mac OS X");241242NSString *nsVerStr = NULL;243char* osVersionCStr = NULL;244// Mac OS 10.9 includes the [NSProcessInfo operatingSystemVersion] function,245// but it's not in the 10.9 SDK. So, call it via NSInvocation.246if ([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {247OSVerStruct osVer;248NSMethodSignature *sig = [[NSProcessInfo processInfo] methodSignatureForSelector:249@selector(operatingSystemVersion)];250NSInvocation *invoke = [NSInvocation invocationWithMethodSignature:sig];251invoke.selector = @selector(operatingSystemVersion);252[invoke invokeWithTarget:[NSProcessInfo processInfo]];253[invoke getReturnValue:&osVer];254255// Copy out the char* if running on version other than 10.16 Mac OS (10.16 == 11.x)256// or explicitly requesting version compatibility257if (!((long)osVer.majorVersion == 10 && (long)osVer.minorVersion >= 16) ||258(getenv("SYSTEM_VERSION_COMPAT") != NULL)) {259if (osVer.patchVersion == 0) { // Omit trailing ".0"260nsVerStr = [NSString stringWithFormat:@"%ld.%ld",261(long)osVer.majorVersion, (long)osVer.minorVersion];262} else {263nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",264(long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];265}266} else {267// Version 10.16, without explicit env setting of SYSTEM_VERSION_COMPAT268// AKA 11+ Read the *real* ProductVersion from the hidden link to avoid SYSTEM_VERSION_COMPAT269// If not found, fallback below to the SystemVersion.plist270NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :271@"/System/Library/CoreServices/.SystemVersionPlatform.plist"];272if (version != NULL) {273nsVerStr = [version objectForKey : @"ProductVersion"];274}275}276}277// Fallback if running on pre-10.9 Mac OS278if (nsVerStr == NULL) {279NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :280@"/System/Library/CoreServices/SystemVersion.plist"];281if (version != NULL) {282nsVerStr = [version objectForKey : @"ProductVersion"];283}284}285286if (nsVerStr != NULL) {287// Copy out the char*288osVersionCStr = strdup([nsVerStr UTF8String]);289}290if (osVersionCStr == NULL) {291osVersionCStr = strdup("Unknown");292}293sprops->os_version = osVersionCStr;294}295296297static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey,298CFStringRef inHostKey, CFStringRef inPortKey,299CFStringRef *outProxyHost, int *ioProxyPort) {300/* See if the proxy is enabled. */301CFNumberRef cf_enabled = CFDictionaryGetValue(inDict, inEnabledKey);302if (cf_enabled == NULL) {303return false;304}305306int isEnabled = false;307if (!CFNumberGetValue(cf_enabled, kCFNumberIntType, &isEnabled)) {308return isEnabled;309}310311if (!isEnabled) return false;312*outProxyHost = CFDictionaryGetValue(inDict, inHostKey);313314// If cf_host is null, that means the checkbox is set,315// but no host was entered. We'll treat that as NOT ENABLED.316// If cf_port is null or cf_port isn't a number, that means317// no port number was entered. Treat this as ENABLED with the318// protocol's default port.319if (*outProxyHost == NULL) {320return false;321}322323if (CFStringGetLength(*outProxyHost) == 0) {324return false;325}326327int newPort = 0;328CFNumberRef cf_port = NULL;329if ((cf_port = CFDictionaryGetValue(inDict, inPortKey)) != NULL &&330CFNumberGetValue(cf_port, kCFNumberIntType, &newPort) &&331newPort > 0) {332*ioProxyPort = newPort;333} else {334// bad port or no port - leave *ioProxyPort unchanged335}336337return true;338}339340static char *createUTF8CString(const CFStringRef theString) {341if (theString == NULL) return NULL;342343const CFIndex stringLength = CFStringGetLength(theString);344const CFIndex bufSize = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 1;345char *returnVal = (char *)malloc(bufSize);346347if (CFStringGetCString(theString, returnVal, bufSize, kCFStringEncodingUTF8)) {348return returnVal;349}350351free(returnVal);352return NULL;353}354355// Return TRUE if str is a syntactically valid IP address.356// Using inet_pton() instead of inet_aton() for IPv6 support.357// len is only a hint; cstr must still be nul-terminated358static int looksLikeIPAddress(char *cstr, size_t len) {359if (len == 0 || (len == 1 && cstr[0] == '.')) return FALSE;360361char dst[16]; // big enough for INET6362return (1 == inet_pton(AF_INET, cstr, dst) ||3631 == inet_pton(AF_INET6, cstr, dst));364}365366367368// Convert Mac OS X proxy exception entry to Java syntax.369// See Radar #3441134 for details.370// Returns NULL if this exception should be ignored by Java.371// May generate a string with multiple exceptions separated by '|'.372static char * createConvertedException(CFStringRef cf_original) {373// This is done with char* instead of CFString because inet_pton()374// needs a C string.375char *c_exception = createUTF8CString(cf_original);376if (!c_exception) return NULL;377378int c_len = strlen(c_exception);379380// 1. sanitize exception prefix381if (c_len >= 1 && 0 == strncmp(c_exception, ".", 1)) {382memmove(c_exception, c_exception+1, c_len);383c_len -= 1;384} else if (c_len >= 2 && 0 == strncmp(c_exception, "*.", 2)) {385memmove(c_exception, c_exception+2, c_len-1);386c_len -= 2;387}388389// 2. pre-reject other exception wildcards390if (strchr(c_exception, '*')) {391free(c_exception);392return NULL;393}394395// 3. no IP wildcarding396if (looksLikeIPAddress(c_exception, c_len)) {397return c_exception;398}399400// 4. allow domain suffixes401// c_exception is now "str\0" - change to "str|*.str\0"402c_exception = reallocf(c_exception, c_len+3+c_len+1);403if (!c_exception) return NULL;404405strncpy(c_exception+c_len, "|*.", 3);406strncpy(c_exception+c_len+3, c_exception, c_len);407c_exception[c_len+3+c_len] = '\0';408return c_exception;409}410411/*412* Method for fetching the user.home path and storing it in the property list.413* For signed .apps running in the Mac App Sandbox, user.home is set to the414* app's sandbox container.415*/416void setUserHome(java_props_t *sprops) {417if (sprops == NULL) { return; }418NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];419sprops->user_home = createUTF8CString((CFStringRef)NSHomeDirectory());420[pool drain];421}422423/*424* Method for fetching proxy info and storing it in the property list.425*/426void setProxyProperties(java_props_t *sProps) {427if (sProps == NULL) return;428429char buf[16]; /* Used for %d of an int - 16 is plenty */430CFStringRef431cf_httpHost = NULL,432cf_httpsHost = NULL,433cf_ftpHost = NULL,434cf_socksHost = NULL;435int436httpPort = 80, // Default proxy port values437httpsPort = 443,438ftpPort = 21,439socksPort = 1080;440441CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);442if (dict == NULL) return;443444/* Read the proxy exceptions list */445CFArrayRef cf_list = CFDictionaryGetValue(dict, kSCPropNetProxiesExceptionsList);446447CFMutableStringRef cf_exceptionList = NULL;448if (cf_list != NULL) {449CFIndex len = CFArrayGetCount(cf_list), idx;450451cf_exceptionList = CFStringCreateMutable(NULL, 0);452for (idx = (CFIndex)0; idx < len; idx++) {453CFStringRef cf_ehost;454if ((cf_ehost = CFArrayGetValueAtIndex(cf_list, idx))) {455/* Convert this exception from Mac OS X syntax to Java syntax.456See Radar #3441134 for details. This may generate a string457with multiple Java exceptions separated by '|'. */458char *c_exception = createConvertedException(cf_ehost);459if (c_exception) {460/* Append the host to the list of exclusions. */461if (CFStringGetLength(cf_exceptionList) > 0) {462CFStringAppendCString(cf_exceptionList, "|", kCFStringEncodingMacRoman);463}464CFStringAppendCString(cf_exceptionList, c_exception, kCFStringEncodingMacRoman);465free(c_exception);466}467}468}469}470471if (cf_exceptionList != NULL) {472if (CFStringGetLength(cf_exceptionList) > 0) {473sProps->exceptionList = createUTF8CString(cf_exceptionList);474}475CFRelease(cf_exceptionList);476}477478#define CHECK_PROXY(protocol, PROTOCOL) \479sProps->protocol##ProxyEnabled = \480getProxyInfoForProtocol(dict, kSCPropNetProxies##PROTOCOL##Enable, \481kSCPropNetProxies##PROTOCOL##Proxy, \482kSCPropNetProxies##PROTOCOL##Port, \483&cf_##protocol##Host, &protocol##Port); \484if (sProps->protocol##ProxyEnabled) { \485sProps->protocol##Host = createUTF8CString(cf_##protocol##Host); \486snprintf(buf, sizeof(buf), "%d", protocol##Port); \487sProps->protocol##Port = malloc(strlen(buf) + 1); \488strcpy(sProps->protocol##Port, buf); \489}490491CHECK_PROXY(http, HTTP);492CHECK_PROXY(https, HTTPS);493CHECK_PROXY(ftp, FTP);494CHECK_PROXY(socks, SOCKS);495496#undef CHECK_PROXY497498CFRelease(dict);499}500501502