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