Path: blob/master/src/java.base/macosx/native/libjava/java_props_macosx.c
41119 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#ifndef TARGET_IOS26#include <sys/socket.h>27#include <netinet/in.h>28#include <arpa/inet.h>29#include <objc/objc-runtime.h>3031#include <CoreFoundation/CoreFoundation.h>32#include <SystemConfiguration/SystemConfiguration.h>33#include <Foundation/Foundation.h>3435#else36#include <stdlib.h>37#include <string.h>38#include <sys/param.h>39#include <objc/runtime.h>40#include <objc/objc.h>41#include <objc/message.h>42#include <CoreFoundation/CoreFoundation.h>43#include <CoreFoundation/CFlocale.h>4445#endif4647#include "java_props_macosx.h"4849#ifndef TARGET_IOS5051char *getPosixLocale(int cat) {52char *lc = setlocale(cat, NULL);53if ((lc == NULL) || (strcmp(lc, "C") == 0)) {54lc = getenv("LANG");55}56if (lc == NULL) return NULL;57return strdup(lc);58}5960#define LOCALEIDLENGTH 12861#ifndef kCFCoreFoundationVersionNumber10_11_Max62#define kCFCoreFoundationVersionNumber10_11_Max 129963#endif64char *getMacOSXLocale(int cat) {65const char* retVal = NULL;66char languageString[LOCALEIDLENGTH];67char localeString[LOCALEIDLENGTH];6869// Since macOS 10.12, there is no separate language selection for70// "format" locale, e.g., date format. Use the preferred language71// for all LC_* categories.72if (kCFCoreFoundationVersionNumber >73kCFCoreFoundationVersionNumber10_11_Max) {74cat = LC_MESSAGES;75}7677switch (cat) {78case LC_MESSAGES:79{80// get preferred language code81CFArrayRef languages = CFLocaleCopyPreferredLanguages();82if (languages == NULL) {83return NULL;84}85if (CFArrayGetCount(languages) <= 0) {86CFRelease(languages);87return NULL;88}8990CFStringRef primaryLanguage = (CFStringRef)CFArrayGetValueAtIndex(languages, 0);91if (primaryLanguage == NULL) {92CFRelease(languages);93return NULL;94}95if (CFStringGetCString(primaryLanguage, languageString,96LOCALEIDLENGTH, CFStringGetSystemEncoding()) == false) {97CFRelease(languages);98return NULL;99}100CFRelease(languages);101102// Explicitly supply region, if there is none103char *hyphenPos = strchr(languageString, '-');104int langStrLen = strlen(languageString);105106if (hyphenPos == NULL || // languageString contains ISO639 only, e.g., "en"107languageString + langStrLen - hyphenPos == 5) { // ISO639-ScriptCode, e.g., "en-Latn"108CFLocaleRef cflocale = CFLocaleCopyCurrent();109if (cflocale != NULL) {110CFStringGetCString(CFLocaleGetIdentifier(cflocale),111localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding());112char *underscorePos = strrchr(localeString, '_');113char *region = NULL;114115if (underscorePos != NULL) {116region = underscorePos + 1;117}118119if (region != NULL) {120strcat(languageString, "-");121strcat(languageString, region);122}123CFRelease(cflocale);124}125}126127retVal = languageString;128}129break;130131default:132{133CFLocaleRef cflocale = CFLocaleCopyCurrent();134if (cflocale != NULL) {135if (!CFStringGetCString(CFLocaleGetIdentifier(cflocale),136localeString, LOCALEIDLENGTH, CFStringGetSystemEncoding())) {137CFRelease(cflocale);138return NULL;139}140141retVal = localeString;142CFRelease(cflocale);143} else {144return NULL;145}146}147break;148}149150if (retVal != NULL) {151// convertToPOSIXLocale() does not expect any variant codes, so ignore152// '@' and anything following, if present.153char* rmAt = strchr(retVal, '@');154if (rmAt != NULL) {155*rmAt = '\0';156}157return strdup(convertToPOSIXLocale(retVal));158}159160return NULL;161}162163/* Language IDs use the language designators and (optional) region164* and script designators of BCP 47. So possible formats are:165*166* "en" (language designator only)167* "haw" (3-letter lanuage designator)168* "en-GB" (language with alpha-2 region designator)169* "es-419" (language with 3-digit UN M.49 area code)170* "zh-Hans" (language with ISO 15924 script designator)171* "zh-Hans-US" (language with ISO 15924 script designator and region)172* "zh-Hans-419" (language with ISO 15924 script designator and UN M.49)173*174* convert these tags into POSIX conforming locale string, i.e.,175* lang{_region}{@script}. e.g., for "zh-Hans-US" into "zh_US@Hans"176*/177const char * convertToPOSIXLocale(const char* src) {178char* scriptRegion = strchr(src, '-');179if (scriptRegion != NULL) {180int length = strlen(scriptRegion);181char* region = strchr(scriptRegion + 1, '-');182char* atMark = NULL;183184if (region == NULL) {185// CFLocaleGetIdentifier() returns '_' before region186region = strchr(scriptRegion + 1, '_');187}188189*scriptRegion = '_';190if (length > 5) {191// Region and script both exist.192char tmpScript[4];193int regionLength = length - 6;194atMark = scriptRegion + 1 + regionLength;195memcpy(tmpScript, scriptRegion + 1, 4);196memmove(scriptRegion + 1, region + 1, regionLength);197memcpy(atMark + 1, tmpScript, 4);198} else if (length == 5) {199// script only200atMark = scriptRegion;201}202203if (atMark != NULL) {204*atMark = '@';205206// assert script code207assert(isalpha(atMark[1]) &&208isalpha(atMark[2]) &&209isalpha(atMark[3]) &&210isalpha(atMark[4]));211}212213assert(((length == 3 || length == 8) &&214// '_' followed by a 2 character region designator215isalpha(scriptRegion[1]) &&216isalpha(scriptRegion[2])) ||217((length == 4 || length == 9) &&218// '_' followed by a 3-digit UN M.49 area code219isdigit(scriptRegion[1]) &&220isdigit(scriptRegion[2]) &&221isdigit(scriptRegion[3])) ||222// '@' followed by a 4 character script code (already validated above)223(length == 5));224}225226return src;227}228229char *setupMacOSXLocale(int cat) {230char * ret = getMacOSXLocale(cat);231232if (ret == NULL) {233return getPosixLocale(cat);234} else {235return ret;236}237}238239// 10.9 SDK does not include the NSOperatingSystemVersion struct.240// For now, create our own241typedef struct {242NSInteger majorVersion;243NSInteger minorVersion;244NSInteger patchVersion;245} OSVerStruct;246247void setOSNameAndVersion(java_props_t *sprops) {248// Hardcode os_name, and fill in os_version249sprops->os_name = strdup("Mac OS X");250251char* osVersionCStr = NULL;252// Mac OS 10.9 includes the [NSProcessInfo operatingSystemVersion] function,253// but it's not in the 10.9 SDK. So, call it via NSInvocation.254if ([[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {255OSVerStruct osVer;256NSMethodSignature *sig = [[NSProcessInfo processInfo] methodSignatureForSelector:257@selector(operatingSystemVersion)];258NSInvocation *invoke = [NSInvocation invocationWithMethodSignature:sig];259invoke.selector = @selector(operatingSystemVersion);260[invoke invokeWithTarget:[NSProcessInfo processInfo]];261[invoke getReturnValue:&osVer];262263NSString *nsVerStr;264// Copy out the char* if running on version other than 10.16 Mac OS (10.16 == 11.x)265// or explicitly requesting version compatibility266if (!((long)osVer.majorVersion == 10 && (long)osVer.minorVersion >= 16) ||267(getenv("SYSTEM_VERSION_COMPAT") != NULL)) {268if (osVer.patchVersion == 0) { // Omit trailing ".0"269nsVerStr = [NSString stringWithFormat:@"%ld.%ld",270(long)osVer.majorVersion, (long)osVer.minorVersion];271} else {272nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",273(long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];274}275// Copy out the char*276osVersionCStr = strdup([nsVerStr UTF8String]);277} else {278// Version 10.16, without explicit env setting of SYSTEM_VERSION_COMPAT279// AKA 11.x; compute the version number from the letter in the ProductBuildVersion280NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :281@"/System/Library/CoreServices/SystemVersion.plist"];282if (version != NULL) {283NSString *nsBuildVerStr = [version objectForKey : @"ProductBuildVersion"];284if (nsBuildVerStr != NULL && nsBuildVerStr.length >= 3) {285int letter = [nsBuildVerStr characterAtIndex:2];286if (letter >= 'B' && letter <= 'Z') {287int vers = letter - 'A' - 1;288asprintf(&osVersionCStr, "11.%d", vers);289}290}291}292}293}294// Fallback if running on pre-10.9 Mac OS295if (osVersionCStr == NULL) {296NSDictionary *version = [NSDictionary dictionaryWithContentsOfFile :297@"/System/Library/CoreServices/SystemVersion.plist"];298if (version != NULL) {299NSString *nsVerStr = [version objectForKey : @"ProductVersion"];300if (nsVerStr != NULL) {301osVersionCStr = strdup([nsVerStr UTF8String]);302}303}304}305if (osVersionCStr == NULL) {306osVersionCStr = strdup("Unknown");307}308sprops->os_version = osVersionCStr;309}310311312static Boolean getProxyInfoForProtocol(CFDictionaryRef inDict, CFStringRef inEnabledKey,313CFStringRef inHostKey, CFStringRef inPortKey,314CFStringRef *outProxyHost, int *ioProxyPort) {315/* See if the proxy is enabled. */316CFNumberRef cf_enabled = CFDictionaryGetValue(inDict, inEnabledKey);317if (cf_enabled == NULL) {318return false;319}320321int isEnabled = false;322if (!CFNumberGetValue(cf_enabled, kCFNumberIntType, &isEnabled)) {323return isEnabled;324}325326if (!isEnabled) return false;327*outProxyHost = CFDictionaryGetValue(inDict, inHostKey);328329// If cf_host is null, that means the checkbox is set,330// but no host was entered. We'll treat that as NOT ENABLED.331// If cf_port is null or cf_port isn't a number, that means332// no port number was entered. Treat this as ENABLED with the333// protocol's default port.334if (*outProxyHost == NULL) {335return false;336}337338if (CFStringGetLength(*outProxyHost) == 0) {339return false;340}341342int newPort = 0;343CFNumberRef cf_port = NULL;344if ((cf_port = CFDictionaryGetValue(inDict, inPortKey)) != NULL &&345CFNumberGetValue(cf_port, kCFNumberIntType, &newPort) &&346newPort > 0) {347*ioProxyPort = newPort;348} else {349// bad port or no port - leave *ioProxyPort unchanged350}351352return true;353}354355static char *createUTF8CString(const CFStringRef theString) {356if (theString == NULL) return NULL;357358const CFIndex stringLength = CFStringGetLength(theString);359const CFIndex bufSize = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 1;360char *returnVal = (char *)malloc(bufSize);361362if (CFStringGetCString(theString, returnVal, bufSize, kCFStringEncodingUTF8)) {363return returnVal;364}365366free(returnVal);367return NULL;368}369370// Return TRUE if str is a syntactically valid IP address.371// Using inet_pton() instead of inet_aton() for IPv6 support.372// len is only a hint; cstr must still be nul-terminated373static int looksLikeIPAddress(char *cstr, size_t len) {374if (len == 0 || (len == 1 && cstr[0] == '.')) return FALSE;375376char dst[16]; // big enough for INET6377return (1 == inet_pton(AF_INET, cstr, dst) ||3781 == inet_pton(AF_INET6, cstr, dst));379}380381382383// Convert Mac OS X proxy exception entry to Java syntax.384// See Radar #3441134 for details.385// Returns NULL if this exception should be ignored by Java.386// May generate a string with multiple exceptions separated by '|'.387static char * createConvertedException(CFStringRef cf_original) {388// This is done with char* instead of CFString because inet_pton()389// needs a C string.390char *c_exception = createUTF8CString(cf_original);391if (!c_exception) return NULL;392393int c_len = strlen(c_exception);394395// 1. sanitize exception prefix396if (c_len >= 1 && 0 == strncmp(c_exception, ".", 1)) {397memmove(c_exception, c_exception+1, c_len);398c_len -= 1;399} else if (c_len >= 2 && 0 == strncmp(c_exception, "*.", 2)) {400memmove(c_exception, c_exception+2, c_len-1);401c_len -= 2;402}403404// 2. pre-reject other exception wildcards405if (strchr(c_exception, '*')) {406free(c_exception);407return NULL;408}409410// 3. no IP wildcarding411if (looksLikeIPAddress(c_exception, c_len)) {412return c_exception;413}414415// 4. allow domain suffixes416// c_exception is now "str\0" - change to "str|*.str\0"417c_exception = reallocf(c_exception, c_len+3+c_len+1);418if (!c_exception) return NULL;419420strncpy(c_exception+c_len, "|*.", 3);421strncpy(c_exception+c_len+3, c_exception, c_len);422c_exception[c_len+3+c_len] = '\0';423return c_exception;424}425426/*427* Method for fetching the user.home path and storing it in the property list.428* For signed .apps running in the Mac App Sandbox, user.home is set to the429* app's sandbox container.430*/431void setUserHome(java_props_t *sprops) {432if (sprops == NULL) { return; }433NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];434sprops->user_home = createUTF8CString((CFStringRef)NSHomeDirectory());435[pool drain];436}437438/*439* Method for fetching proxy info and storing it in the property list.440*/441void setProxyProperties(java_props_t *sProps) {442if (sProps == NULL) return;443444char buf[16]; /* Used for %d of an int - 16 is plenty */445CFStringRef446cf_httpHost = NULL,447cf_httpsHost = NULL,448cf_ftpHost = NULL,449cf_socksHost = NULL;450int451httpPort = 80, // Default proxy port values452httpsPort = 443,453ftpPort = 21,454socksPort = 1080;455456CFDictionaryRef dict = SCDynamicStoreCopyProxies(NULL);457if (dict == NULL) return;458459/* Read the proxy exceptions list */460CFArrayRef cf_list = CFDictionaryGetValue(dict, kSCPropNetProxiesExceptionsList);461462CFMutableStringRef cf_exceptionList = NULL;463if (cf_list != NULL) {464CFIndex len = CFArrayGetCount(cf_list), idx;465466cf_exceptionList = CFStringCreateMutable(NULL, 0);467for (idx = (CFIndex)0; idx < len; idx++) {468CFStringRef cf_ehost;469if ((cf_ehost = CFArrayGetValueAtIndex(cf_list, idx))) {470/* Convert this exception from Mac OS X syntax to Java syntax.471See Radar #3441134 for details. This may generate a string472with multiple Java exceptions separated by '|'. */473char *c_exception = createConvertedException(cf_ehost);474if (c_exception) {475/* Append the host to the list of exclusions. */476if (CFStringGetLength(cf_exceptionList) > 0) {477CFStringAppendCString(cf_exceptionList, "|", kCFStringEncodingMacRoman);478}479CFStringAppendCString(cf_exceptionList, c_exception, kCFStringEncodingMacRoman);480free(c_exception);481}482}483}484}485486if (cf_exceptionList != NULL) {487if (CFStringGetLength(cf_exceptionList) > 0) {488sProps->exceptionList = createUTF8CString(cf_exceptionList);489}490CFRelease(cf_exceptionList);491}492493#define CHECK_PROXY(protocol, PROTOCOL) \494sProps->protocol##ProxyEnabled = \495getProxyInfoForProtocol(dict, kSCPropNetProxies##PROTOCOL##Enable, \496kSCPropNetProxies##PROTOCOL##Proxy, \497kSCPropNetProxies##PROTOCOL##Port, \498&cf_##protocol##Host, &protocol##Port); \499if (sProps->protocol##ProxyEnabled) { \500sProps->protocol##Host = createUTF8CString(cf_##protocol##Host); \501snprintf(buf, sizeof(buf), "%d", protocol##Port); \502sProps->protocol##Port = malloc(strlen(buf) + 1); \503strcpy(sProps->protocol##Port, buf); \504}505506CHECK_PROXY(http, HTTP);507CHECK_PROXY(https, HTTPS);508CHECK_PROXY(ftp, FTP);509CHECK_PROXY(socks, SOCKS);510511#undef CHECK_PROXY512513CFRelease(dict);514}515#else516#define LOCALEIDLENGTH 128517char *getPosixLocale(int cat) {518char *lc = setlocale(cat, NULL);519if ((lc == NULL) || (strcmp(lc, "C") == 0)) {520lc = getenv("LANG");521}522if (lc == NULL) return NULL;523return strdup(lc);524}525526char *getMacOSXLocale(int cat) {527char localeString[LOCALEIDLENGTH];528// Get current user locale.529CFLocaleRef loc = CFLocaleCopyCurrent();530char *localstr;531if (CFStringGetCString(CFLocaleGetIdentifier(loc),532localeString, LOCALEIDLENGTH,533kCFStringEncodingUTF8))534localstr = strdup(localeString);535else536localstr = NULL;537538CFRelease(loc);539return (localstr);540}541542#endif543544545