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