Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f90600867 | ||
|
|
8e65f49538 | ||
|
|
4d2033330b | ||
|
|
26acea8efe | ||
|
|
a7d7746195 | ||
|
|
ecd3cb5472 | ||
|
|
b0d0be1f9d | ||
|
|
d34ed1642b | ||
|
|
7d8eabd147 | ||
|
|
eee293c072 | ||
|
|
b634ef0d82 | ||
|
|
32d64222b1 | ||
|
|
7a5f4204aa | ||
|
|
7f13b62215 | ||
|
|
9960f87a64 | ||
|
|
afac16997d | ||
|
|
3dff421867 | ||
|
|
6dadff9736 | ||
|
|
35d3707ff2 | ||
|
|
9a959d6aed | ||
|
|
698b924603 | ||
|
|
43611850be | ||
|
|
ac4aeb5218 | ||
|
|
86a2b3f1ab | ||
|
|
74dad98fc1 | ||
|
|
01da6b1131 | ||
|
|
7c5840b288 | ||
|
|
24116b53bc | ||
|
|
cffd9d1eb4 | ||
|
|
3c532f1ac5 | ||
|
|
c64e15acad | ||
|
|
9ff33ec1fd | ||
|
|
a1aed680fd | ||
|
|
dec2059a36 | ||
|
|
f7083025a0 | ||
|
|
74e2935f1e | ||
|
|
0af450008b | ||
|
|
75bc9334ef | ||
|
|
207d76a143 | ||
|
|
f79471407f | ||
|
|
ec803d9859 | ||
|
|
f63842f773 | ||
|
|
f218282e28 | ||
|
|
6d866633bf | ||
|
|
633b9764c6 | ||
|
|
0643c60f0f | ||
|
|
5a562ae343 | ||
|
|
9838875996 | ||
|
|
25aacd20d5 | ||
|
|
7026ca99fc | ||
|
|
258a573e8c | ||
|
|
2b225dbc59 | ||
|
|
c9b48af022 | ||
|
|
984a8c926e | ||
|
|
5cf256f532 | ||
|
|
5f4a4dc1e1 |
+3
-1
@@ -29,10 +29,12 @@ The exclamation mark in the Wi-Fi/cellular icon appears because the system fails
|
||||
3. Some ROM like [Flyme](https://github.com/shadowsocks/shadowsocks-android/issues/1589) has **very** broken direct boot support;
|
||||
4. If you have Xposed framework and/or battery saver apps, it's likely that this app wouldn't work well with these either.
|
||||
|
||||
* Fixes for MIUI: [#772](https://github.com/shadowsocks/shadowsocks-android/issues/772) [#888](https://github.com/shadowsocks/shadowsocks-android/issues/888)
|
||||
* Fixes for MIUI: [#772](https://github.com/shadowsocks/shadowsocks-android/issues/772)
|
||||
* Fixes for EMUI: [#888](https://github.com/shadowsocks/shadowsocks-android/issues/888)
|
||||
* Fixes for Huawei: [#1091 (comment)](https://github.com/shadowsocks/shadowsocks-android/issues/1091#issuecomment-276949836)
|
||||
* Related to Xposed: [#1414](https://github.com/shadowsocks/shadowsocks-android/issues/1414)
|
||||
* Samsung and/or Brevent: [#1410](https://github.com/shadowsocks/shadowsocks-android/issues/1410)
|
||||
* Another Samsung: [#1712](https://github.com/shadowsocks/shadowsocks-android/issues/1712)
|
||||
* Don't install this app on SD card because of permission issues: [#1124 (comment)](https://github.com/shadowsocks/shadowsocks-android/issues/1124#issuecomment-307556453)
|
||||
|
||||
### How to pause Shadowsocks service?
|
||||
|
||||
+2
-6
@@ -12,11 +12,6 @@
|
||||
|
||||
Использйте интеграцию с [Tasker](http://tasker.dinglisch.net/).
|
||||
|
||||
### Как добавить QR код из локальной галереи?
|
||||
|
||||
Отсканируйте его при помощи стороннего сканера, например [QuickMark Barcode Scanner](https://play.google.com/store/apps/details?id=tw.com.quickmark) и нажмите на `ss` ссылку.
|
||||
|
||||
|
||||
### Почему режим NAT более не поддерживается?
|
||||
|
||||
1. Требуются ROOT права;
|
||||
@@ -34,7 +29,8 @@
|
||||
3. Некоторые ROM, такие как [Flyme](https://github.com/shadowsocks/shadowsocks-android/issues/1589) имеют **слишком** испорченную поддержку "непосредственной загрузки";
|
||||
4. Если вы используете фреймворк Xposed и/или приложения для энергосбережения, вероятно наше приложение не будет нормально работать с ними.
|
||||
|
||||
* Иправления для MIUI: [#772](https://github.com/shadowsocks/shadowsocks-android/issues/772) [#888](https://github.com/shadowsocks/shadowsocks-android/issues/888)
|
||||
* Исправления для MIUI: [#772](https://github.com/shadowsocks/shadowsocks-android/issues/772)
|
||||
* Исправления для EMUI: [#888](https://github.com/shadowsocks/shadowsocks-android/issues/888)
|
||||
* Иправления для Huawei: [#1091 (комментарий)](https://github.com/shadowsocks/shadowsocks-android/issues/1091#issuecomment-276949836)
|
||||
* Вызванные из-за Xposed: [#1414](https://github.com/shadowsocks/shadowsocks-android/issues/1414)
|
||||
* Samsung и/или Brevent: [#1410](https://github.com/shadowsocks/shadowsocks-android/issues/1410)
|
||||
|
||||
+4
-4
@@ -4,13 +4,13 @@ apply plugin: 'com.github.ben-manes.versions'
|
||||
|
||||
buildscript {
|
||||
ext {
|
||||
kotlinVersion = '1.2.21'
|
||||
kotlinVersion = '1.2.31'
|
||||
minSdkVersion = 21
|
||||
sdkVersion = 27
|
||||
buildToolsVersion = '27.0.3'
|
||||
supportLibraryVersion = '27.1.0'
|
||||
takisoftFixVersion = '27.1.0.0'
|
||||
playServicesVersion = '11.8.0'
|
||||
playServicesVersion = '12.0.1'
|
||||
junitVersion = '4.12'
|
||||
androidTestVersion = '1.0.1'
|
||||
androidEspressoVersion = '3.0.1'
|
||||
@@ -22,9 +22,9 @@ buildscript {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:3.0.1'
|
||||
classpath 'com.android.tools.build:gradle:3.1.0'
|
||||
classpath 'com.github.ben-manes:gradle-versions-plugin:0.17.0'
|
||||
classpath 'com.google.gms:google-services:3.2.0'
|
||||
classpath 'com.google.gms:google-services:3.2.1'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ android {
|
||||
task goBuild(type: Exec) {
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
executable "cmd.exe"
|
||||
args "/c", "src\\overture\\make.bat " + minSdkVersion
|
||||
args "/c", file("src/overture/make.bat").absolutePath , minSdkVersion
|
||||
} else {
|
||||
executable "sh"
|
||||
args "-c", "src/overture/make.bash " + minSdkVersion
|
||||
@@ -48,7 +48,7 @@ task goBuild(type: Exec) {
|
||||
task goClean(type: Exec) {
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
executable "cmd.exe"
|
||||
args "/c", "src\\overture\\clean.bat"
|
||||
args "/c", file("src/overture/clean.bat").absolutePath
|
||||
} else {
|
||||
executable "sh"
|
||||
args "-c", "src/overture/clean.bash"
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import pkgutil
|
||||
import urlparse
|
||||
import socket
|
||||
import logging
|
||||
from argparse import ArgumentParser
|
||||
from datetime import date
|
||||
|
||||
__all__ = ['main']
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument('-i', '--input', dest='input', required=True,
|
||||
help='path to gfwlist', metavar='GFWLIST')
|
||||
parser.add_argument('-f', '--file', dest='output', required=True,
|
||||
help='path to output acl', metavar='ACL')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def decode_gfwlist(content):
|
||||
# decode base64 if have to
|
||||
try:
|
||||
return content.decode('base64')
|
||||
except:
|
||||
return content
|
||||
|
||||
|
||||
def get_hostname(something):
|
||||
try:
|
||||
# quite enough for GFW
|
||||
if not something.startswith('http:'):
|
||||
something = 'http://' + something
|
||||
r = urlparse.urlparse(something)
|
||||
return r.hostname
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return None
|
||||
|
||||
|
||||
def add_domain_to_set(s, something):
|
||||
hostname = get_hostname(something)
|
||||
if hostname is not None:
|
||||
if hostname.startswith('.'):
|
||||
hostname = hostname.lstrip('.')
|
||||
if hostname.endswith('/'):
|
||||
hostname = hostname.rstrip('/')
|
||||
if hostname:
|
||||
s.add(hostname)
|
||||
|
||||
|
||||
def parse_gfwlist(content):
|
||||
gfwlist = content.splitlines(False)
|
||||
domains = set()
|
||||
for line in gfwlist:
|
||||
if line.find('.*') >= 0:
|
||||
continue
|
||||
elif line.find('*') >= 0:
|
||||
line = line.replace('*', '/')
|
||||
if line.startswith('!'):
|
||||
continue
|
||||
elif line.startswith('['):
|
||||
continue
|
||||
elif line.startswith('@'):
|
||||
# ignore white list
|
||||
continue
|
||||
elif line.startswith('||'):
|
||||
add_domain_to_set(domains, line.lstrip('||'))
|
||||
elif line.startswith('|'):
|
||||
add_domain_to_set(domains, line.lstrip('|'))
|
||||
elif line.startswith('.'):
|
||||
add_domain_to_set(domains, line.lstrip('.'))
|
||||
else:
|
||||
add_domain_to_set(domains, line)
|
||||
# TODO: reduce ['www.google.com', 'google.com'] to ['google.com']
|
||||
return domains
|
||||
|
||||
|
||||
def generate_acl(domains):
|
||||
header ="""#
|
||||
# GFW list from https://github.com/gfwlist/gfwlist/blob/master/gfwlist.txt
|
||||
# updated on DATE
|
||||
#
|
||||
|
||||
[bypass_all]
|
||||
|
||||
[proxy_list]
|
||||
|
||||
"""
|
||||
header = header.replace('DATE', str(date.today()))
|
||||
proxy_content = ""
|
||||
ip_content = ""
|
||||
|
||||
for domain in sorted(domains):
|
||||
try:
|
||||
socket.inet_aton(domain)
|
||||
ip_content += (domain + "\n")
|
||||
except socket.error:
|
||||
domain = domain.replace('.', '\.')
|
||||
proxy_content += ('(^|\.)' + domain + '$\n')
|
||||
|
||||
proxy_content = header + ip_content + proxy_content
|
||||
|
||||
return proxy_content
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args()
|
||||
with open(args.input, 'rb') as f:
|
||||
content = f.read()
|
||||
content = decode_gfwlist(content)
|
||||
domains = parse_gfwlist(content)
|
||||
acl_content = generate_acl(domains)
|
||||
with open(args.output, 'wb') as f:
|
||||
f.write(acl_content)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
Submodule core/src/main/jni/shadowsocks-libev updated: 1a21989566...3e7c852970
@@ -28,21 +28,35 @@ MKDIR %TARGET%\armeabi-v7a>nul 2>nul
|
||||
MKDIR %TARGET%\x86>nul 2>nul
|
||||
MKDIR %TARGET%\arm64-v8a>nul 2>nul
|
||||
|
||||
SET CC=%ANDROID_ARM_TOOLCHAIN%\bin\arm-linux-androideabi-gcc.exe
|
||||
|
||||
REM Check environment availability
|
||||
IF NOT EXIST %CC% (
|
||||
ECHO "gcc not found"
|
||||
EXIT 1
|
||||
)
|
||||
|
||||
WHERE python.exe
|
||||
IF "%ERRORLEVEL%" == 1 (
|
||||
ECHO "python not found"
|
||||
EXIT 1
|
||||
)
|
||||
|
||||
IF NOT EXIST %ANDROID_ARM_CC% (
|
||||
ECHO "Make standalone toolchain for ARM arch"
|
||||
%ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch arm ^
|
||||
python.exe %ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch arm ^
|
||||
--api %MIN_API% --install-dir %ANDROID_ARM_TOOLCHAIN%
|
||||
)
|
||||
|
||||
IF NOT EXIST %ANDROID_ARM64_CC% (
|
||||
ECHO "Make standalone toolchain for ARM64 arch"
|
||||
%ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch arm64 ^
|
||||
python.exe %ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch arm64 ^
|
||||
--api %MIN_API% --install-dir %ANDROID_ARM64_TOOLCHAIN%
|
||||
)
|
||||
|
||||
IF NOT EXIST %ANDROID_X86_CC% (
|
||||
ECHO "Make standalone toolchain for X86 arch"
|
||||
%ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch x86 ^
|
||||
python.exe %ANDROID_NDK_HOME%\build\tools\make_standalone_toolchain.py --arch x86 ^
|
||||
--api %MIN_API% --install-dir %ANDROID_X86_TOOLCHAIN%
|
||||
)
|
||||
|
||||
@@ -118,4 +132,4 @@ IF %BUILD% == 1 (
|
||||
)
|
||||
|
||||
ECHO "Successfully build overture"
|
||||
ENDLOCAL
|
||||
ENDLOCAL
|
||||
|
||||
Submodule core/src/overture/src/github.com/shadowsocks/overture updated: 58ab31a9fd...afe34f99d4
+26
-16
@@ -1,4 +1,4 @@
|
||||
# https://github.com/arturbosch/detekt/blob/801994bd60cc759b181649356cea045b8125301b/detekt-cli/src/main/resources/default-detekt-config.yml
|
||||
# https://github.com/arturbosch/detekt/blob/RC6-4/detekt-cli/src/main/resources/default-detekt-config.yml
|
||||
|
||||
comments:
|
||||
active: false
|
||||
@@ -7,7 +7,7 @@ complexity:
|
||||
active: true
|
||||
ComplexCondition:
|
||||
active: true
|
||||
threshold: 3
|
||||
threshold: 4
|
||||
ComplexInterface:
|
||||
active: true
|
||||
threshold: 10
|
||||
@@ -15,6 +15,7 @@ complexity:
|
||||
ComplexMethod:
|
||||
active: true
|
||||
threshold: 10
|
||||
ignoreSingleWhenExpression: false
|
||||
LabeledExpression:
|
||||
active: true
|
||||
LargeClass:
|
||||
@@ -25,31 +26,32 @@ complexity:
|
||||
threshold: 20
|
||||
LongParameterList:
|
||||
active: true
|
||||
threshold: 5
|
||||
threshold: 6
|
||||
ignoreDefaultParameters: true
|
||||
MethodOverloading:
|
||||
active: false
|
||||
NestedBlockDepth:
|
||||
active: true
|
||||
threshold: 3
|
||||
threshold: 4
|
||||
StringLiteralDuplication:
|
||||
active: true
|
||||
threshold: 2
|
||||
threshold: 3
|
||||
ignoreAnnotation: true
|
||||
excludeStringsWithLessThan5Characters: true
|
||||
ignoreStringsRegex: '$^'
|
||||
TooManyFunctions:
|
||||
active: true
|
||||
thresholdInFiles: 10
|
||||
thresholdInClasses: 10
|
||||
thresholdInInterfaces: 10
|
||||
thresholdInObjects: 10
|
||||
thresholdInEnums: 10
|
||||
thresholdInFiles: 11
|
||||
thresholdInClasses: 11
|
||||
thresholdInInterfaces: 11
|
||||
thresholdInObjects: 11
|
||||
thresholdInEnums: 11
|
||||
|
||||
empty-blocks:
|
||||
active: true
|
||||
EmptyCatchBlock:
|
||||
active: false
|
||||
active: true
|
||||
allowedExceptionNameRegex: "^(_|ignore|expected).*"
|
||||
EmptyClassBlock:
|
||||
active: true
|
||||
EmptyDefaultConstructor:
|
||||
@@ -64,6 +66,7 @@ empty-blocks:
|
||||
active: true
|
||||
EmptyFunctionBlock:
|
||||
active: true
|
||||
ignoreOverriddenFunctions: false
|
||||
EmptyIfBlock:
|
||||
active: true
|
||||
EmptyInitBlock:
|
||||
@@ -105,7 +108,7 @@ exceptions:
|
||||
active: true
|
||||
TooGenericExceptionCaught:
|
||||
active: true
|
||||
exceptions:
|
||||
exceptionNames:
|
||||
- ArrayIndexOutOfBoundsException
|
||||
- Error
|
||||
- Exception
|
||||
@@ -116,10 +119,9 @@ exceptions:
|
||||
- Throwable
|
||||
TooGenericExceptionThrown:
|
||||
active: true
|
||||
exceptions:
|
||||
exceptionNames:
|
||||
- Error
|
||||
- Exception
|
||||
- NullPointerException
|
||||
- Throwable
|
||||
- RuntimeException
|
||||
|
||||
@@ -143,6 +145,7 @@ naming:
|
||||
FunctionNaming:
|
||||
active: true
|
||||
functionPattern: '^([a-z$][a-zA-Z$0-9]*)|(`.*`)$'
|
||||
excludeClassPattern: '$^'
|
||||
MatchingDeclarationName:
|
||||
active: true
|
||||
MemberNameEqualsClassName:
|
||||
@@ -167,6 +170,7 @@ naming:
|
||||
active: true
|
||||
variablePattern: '[a-z][A-Za-z0-9]*'
|
||||
privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*'
|
||||
excludeClassPattern: '$^'
|
||||
|
||||
performance:
|
||||
active: true
|
||||
@@ -239,15 +243,17 @@ style:
|
||||
maxLineLength: 120
|
||||
excludePackageStatements: false
|
||||
excludeImportStatements: false
|
||||
MayBeConst:
|
||||
active: true
|
||||
ModifierOrder:
|
||||
active: true
|
||||
NestedClassesVisibility:
|
||||
active: true
|
||||
NewLineAtEndOfFile:
|
||||
active: true
|
||||
OptionalAbstractKeyword:
|
||||
NoTabs:
|
||||
active: true
|
||||
OptionalReturnKeyword:
|
||||
OptionalAbstractKeyword:
|
||||
active: true
|
||||
OptionalUnit:
|
||||
active: true
|
||||
@@ -268,6 +274,8 @@ style:
|
||||
ThrowsCount:
|
||||
active: true
|
||||
max: 2
|
||||
TrailingWhitespace:
|
||||
active: true
|
||||
UnnecessaryAbstractClass:
|
||||
active: true
|
||||
UnnecessaryInheritance:
|
||||
@@ -278,6 +286,8 @@ style:
|
||||
active: true
|
||||
UnusedImports:
|
||||
active: true
|
||||
UnusedPrivateMember:
|
||||
active: true
|
||||
UseDataClass:
|
||||
active: false
|
||||
UtilityClassWithPublicConstructor:
|
||||
|
||||
+5
-5
@@ -21,8 +21,8 @@ android {
|
||||
applicationId "com.github.shadowsocks"
|
||||
minSdkVersion rootProject.minSdkVersion
|
||||
targetSdkVersion rootProject.sdkVersion
|
||||
versionCode 4050100
|
||||
versionName "4.5.1"
|
||||
versionCode 4050400
|
||||
versionName "4.5.4"
|
||||
testApplicationId "com.github.shadowsocks.test"
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
resConfigs "fa", "fr", "ja", "ko", "ru", "zh-rCN", "zh-rTW"
|
||||
@@ -58,14 +58,14 @@ dependencies {
|
||||
implementation "com.android.support:design:$supportLibraryVersion"
|
||||
implementation "com.android.support:gridlayout-v7:$supportLibraryVersion"
|
||||
implementation 'com.futuremind.recyclerfastscroll:fastscroll:0.2.5'
|
||||
implementation 'com.evernote:android-job:1.2.4'
|
||||
implementation 'com.evernote:android-job:1.2.5'
|
||||
implementation "com.google.android.gms:play-services-ads:$playServicesVersion"
|
||||
implementation "com.google.android.gms:play-services-analytics:$playServicesVersion"
|
||||
implementation "com.google.android.gms:play-services-vision:$playServicesVersion"
|
||||
implementation "com.google.firebase:firebase-config:$playServicesVersion"
|
||||
implementation 'com.j256.ormlite:ormlite-android:5.0'
|
||||
implementation 'com.j256.ormlite:ormlite-android:5.1'
|
||||
implementation 'com.mikepenz:materialdrawer:6.0.6'
|
||||
implementation 'com.squareup.okhttp3:okhttp:3.9.1'
|
||||
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
|
||||
implementation "com.takisoft.fix:preference-v7-simplemenu:$takisoftFixVersion"
|
||||
implementation 'com.twofortyfouram:android-plugin-api-for-locale:1.0.2'
|
||||
implementation 'dnsjava:dnsjava:2.1.8'
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package="com.github.shadowsocks"
|
||||
android:installLocation="internalOnly">
|
||||
|
||||
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<uses-permission android:name="android.permission.NFC" />
|
||||
|
||||
+2450
-1036
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+2456
-1038
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,17 @@
|
||||
0.0.0.0/8
|
||||
10.0.0.0/8
|
||||
100.64.0.0/10
|
||||
127.0.0.0/8
|
||||
169.254.0.0/16
|
||||
172.16.0.0/12
|
||||
192.0.0.0/29
|
||||
192.0.2.0/24
|
||||
192.88.99.0/24
|
||||
192.168.0.0/16
|
||||
198.18.0.0/15
|
||||
198.51.100.0/24
|
||||
203.0.113.0/24
|
||||
224.0.0.0/3
|
||||
1.0.1.0/24
|
||||
1.0.2.0/23
|
||||
1.0.8.0/21
|
||||
|
||||
@@ -23,6 +23,7 @@ package com.github.shadowsocks
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.admin.DevicePolicyManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
@@ -33,8 +34,8 @@ import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.UserManager
|
||||
import android.support.annotation.RequiresApi
|
||||
import android.support.v4.os.UserManagerCompat
|
||||
import android.support.v7.app.AppCompatDelegate
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
@@ -71,7 +72,15 @@ class App : Application() {
|
||||
val deviceContext: Context by lazy { if (Build.VERSION.SDK_INT < 24) this else DeviceContext(this) }
|
||||
val remoteConfig: FirebaseRemoteConfig by lazy { FirebaseRemoteConfig.getInstance() }
|
||||
private val tracker: Tracker by lazy { GoogleAnalytics.getInstance(deviceContext).newTracker(R.xml.tracker) }
|
||||
val info: PackageInfo by lazy { packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) }
|
||||
private val exceptionParser by lazy { StandardExceptionParser(this, null) }
|
||||
val info: PackageInfo by lazy { getPackageInfo(packageName) }
|
||||
val directBootSupported by lazy {
|
||||
Build.VERSION.SDK_INT >= 24 && getSystemService(DevicePolicyManager::class.java)
|
||||
.storageEncryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER
|
||||
}
|
||||
|
||||
fun getPackageInfo(packageName: String) =
|
||||
packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)!!
|
||||
|
||||
fun startService() {
|
||||
val intent = Intent(this, BaseService.serviceClass.java)
|
||||
@@ -98,7 +107,7 @@ class App : Application() {
|
||||
fun track(t: Throwable) = track(Thread.currentThread(), t)
|
||||
fun track(thread: Thread, t: Throwable) {
|
||||
tracker.send(HitBuilders.ExceptionBuilder()
|
||||
.setDescription(StandardExceptionParser(this, null).getDescription(thread.name, t))
|
||||
.setDescription("${exceptionParser.getDescription(thread.name, t)} - ${t.message}")
|
||||
.setFatal(false)
|
||||
.build())
|
||||
t.printStackTrace()
|
||||
@@ -135,14 +144,15 @@ class App : Application() {
|
||||
app.track(e)
|
||||
}
|
||||
|
||||
// handle data restored
|
||||
if (DataStore.directBootAware && UserManagerCompat.isUserUnlocked(this)) DirectBoot.update()
|
||||
// handle data restored/crash
|
||||
if (Build.VERSION.SDK_INT >= 24 && DataStore.directBootAware &&
|
||||
(getSystemService(Context.USER_SERVICE) as UserManager).isUserUnlocked) DirectBoot.flushTrafficStats()
|
||||
TcpFastOpen.enabledAsync(DataStore.publicStore.getBoolean(Key.tfo, TcpFastOpen.sendEnabled))
|
||||
if (DataStore.publicStore.getLong(Key.assetUpdateTime, -1) != info.lastUpdateTime) {
|
||||
val assetManager = assets
|
||||
for (dir in arrayOf("acl", "overture"))
|
||||
try {
|
||||
for (file in assetManager.list(dir)) assetManager.open(dir + '/' + file).use { input ->
|
||||
for (file in assetManager.list(dir)) assetManager.open("$dir/$file").use { input ->
|
||||
File(deviceContext.filesDir, file).outputStream().use { output -> input.copyTo(output) }
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
|
||||
@@ -62,23 +62,21 @@ class AppManager : AppCompatActivity(), Toolbar.OnMenuItemClickListener {
|
||||
|
||||
private var receiver: BroadcastReceiver? = null
|
||||
private var cachedApps: List<PackageInfo>? = null
|
||||
private fun getApps(pm: PackageManager): List<ProxiedApp> {
|
||||
return synchronized(AppManager) {
|
||||
if (receiver == null) receiver = app.listenForPackageChanges {
|
||||
synchronized(AppManager) {
|
||||
receiver = null
|
||||
cachedApps = null
|
||||
}
|
||||
AppManager.instance?.reloadApps()
|
||||
private fun getApps(pm: PackageManager) = synchronized(AppManager) {
|
||||
if (receiver == null) receiver = app.listenForPackageChanges {
|
||||
synchronized(AppManager) {
|
||||
receiver = null
|
||||
cachedApps = null
|
||||
}
|
||||
// Labels and icons can change on configuration (locale, etc.) changes, therefore they are not cached.
|
||||
val cachedApps = cachedApps ?: pm.getInstalledPackages(PackageManager.GET_PERMISSIONS)
|
||||
.filter { it.packageName != app.packageName &&
|
||||
it.requestedPermissions?.contains(Manifest.permission.INTERNET) ?: false }
|
||||
this.cachedApps = cachedApps
|
||||
cachedApps
|
||||
}.map { ProxiedApp(pm, it.applicationInfo, it.packageName) }
|
||||
}
|
||||
AppManager.instance?.reloadApps()
|
||||
}
|
||||
// Labels and icons can change on configuration (locale, etc.) changes, therefore they are not cached.
|
||||
val cachedApps = cachedApps ?: pm.getInstalledPackages(PackageManager.GET_PERMISSIONS)
|
||||
.filter { it.packageName != app.packageName &&
|
||||
it.requestedPermissions?.contains(Manifest.permission.INTERNET) ?: false }
|
||||
this.cachedApps = cachedApps
|
||||
cachedApps
|
||||
}.map { ProxiedApp(pm, it.applicationInfo, it.packageName) }
|
||||
}
|
||||
|
||||
private class ProxiedApp(private val pm: PackageManager, private val appInfo: ApplicationInfo,
|
||||
@@ -155,7 +153,7 @@ class AppManager : AppCompatActivity(), Toolbar.OnMenuItemClickListener {
|
||||
appListView.visibility = View.GONE
|
||||
fastScroller.visibility = View.GONE
|
||||
loadingView.visibility = View.VISIBLE
|
||||
thread {
|
||||
thread("AppManager-loader") {
|
||||
val adapter = appListView.adapter as AppsAdapter
|
||||
do {
|
||||
appsLoading.set(true)
|
||||
|
||||
@@ -20,12 +20,12 @@
|
||||
|
||||
package com.github.shadowsocks
|
||||
|
||||
import android.app.admin.DevicePolicyManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.support.design.widget.Snackbar
|
||||
import android.support.v14.preference.SwitchPreference
|
||||
import android.support.v7.preference.Preference
|
||||
import com.github.shadowsocks.App.Companion.app
|
||||
import com.github.shadowsocks.bg.BaseService
|
||||
import com.github.shadowsocks.preference.DataStore
|
||||
import com.github.shadowsocks.utils.DirectBoot
|
||||
@@ -39,27 +39,24 @@ class GlobalSettingsPreferenceFragment : PreferenceFragmentCompatDividers() {
|
||||
DataStore.initGlobal()
|
||||
addPreferencesFromResource(R.xml.pref_global)
|
||||
val boot = findPreference(Key.isAutoConnect) as SwitchPreference
|
||||
val directBootAwareListener = Preference.OnPreferenceChangeListener { _, newValue ->
|
||||
if (newValue as Boolean) DirectBoot.update() else DirectBoot.clean()
|
||||
true
|
||||
}
|
||||
boot.setOnPreferenceChangeListener { _, value ->
|
||||
BootReceiver.enabled = value as Boolean
|
||||
directBootAwareListener.onPreferenceChange(null, DataStore.directBootAware)
|
||||
true
|
||||
}
|
||||
boot.isChecked = BootReceiver.enabled
|
||||
|
||||
val dba = findPreference(Key.directBootAware)
|
||||
if (Build.VERSION.SDK_INT >= 24 && context!!.getSystemService(DevicePolicyManager::class.java)
|
||||
.storageEncryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER)
|
||||
dba.onPreferenceChangeListener = directBootAwareListener else dba.parent!!.removePreference(dba)
|
||||
val canToggleLocked = findPreference(Key.directBootAware)
|
||||
if (Build.VERSION.SDK_INT >= 24) canToggleLocked.setOnPreferenceChangeListener { _, newValue ->
|
||||
if (app.directBootSupported && newValue as Boolean) DirectBoot.update() else DirectBoot.clean()
|
||||
true
|
||||
} else canToggleLocked.parent!!.removePreference(canToggleLocked)
|
||||
|
||||
val tfo = findPreference(Key.tfo) as SwitchPreference
|
||||
tfo.isChecked = TcpFastOpen.sendEnabled
|
||||
tfo.setOnPreferenceChangeListener { _, value ->
|
||||
val result = TcpFastOpen.enabled(value as Boolean)
|
||||
if (result != null && result != "Success.")
|
||||
Snackbar.make(activity!!.findViewById(R.id.snackbar), result, Snackbar.LENGTH_LONG).show()
|
||||
Snackbar.make(requireActivity().findViewById(R.id.snackbar), result, Snackbar.LENGTH_LONG).show()
|
||||
value == TcpFastOpen.sendEnabled
|
||||
}
|
||||
if (!TcpFastOpen.supported) {
|
||||
|
||||
@@ -266,18 +266,20 @@ class MainActivity : AppCompatActivity(), ShadowsocksConnection.Interface, Drawe
|
||||
++testCount
|
||||
statusText.setText(R.string.connection_test_testing)
|
||||
val id = testCount // it would change by other code
|
||||
thread { testConnection(id) }
|
||||
thread("ConnectionTest") { testConnection(id) }
|
||||
}
|
||||
}
|
||||
|
||||
fab = findViewById(R.id.fab)
|
||||
fab.setOnClickListener {
|
||||
if (state == BaseService.CONNECTED) app.stopService() else thread {
|
||||
if (BaseService.usingVpnMode) {
|
||||
when {
|
||||
state == BaseService.CONNECTED -> app.stopService()
|
||||
BaseService.usingVpnMode -> {
|
||||
val intent = VpnService.prepare(this)
|
||||
if (intent != null) startActivityForResult(intent, REQUEST_CONNECT)
|
||||
else app.handler.post { onActivityResult(REQUEST_CONNECT, Activity.RESULT_OK, null) }
|
||||
} else app.startService()
|
||||
else onActivityResult(REQUEST_CONNECT, Activity.RESULT_OK, null)
|
||||
}
|
||||
else -> app.startService()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ class ProfileConfigFragment : PreferenceFragmentCompatDividers(), Toolbar.OnMenu
|
||||
private const val REQUEST_CODE_PLUGIN_CONFIGURE = 1
|
||||
}
|
||||
|
||||
private lateinit var profile: Profile
|
||||
private var profileId = -1
|
||||
private lateinit var isProxyApps: SwitchPreference
|
||||
private lateinit var plugin: IconListPreference
|
||||
private lateinit var pluginConfigure: EditTextPreference
|
||||
@@ -65,14 +65,8 @@ class ProfileConfigFragment : PreferenceFragmentCompatDividers(), Toolbar.OnMenu
|
||||
|
||||
override fun onCreatePreferencesFix(savedInstanceState: Bundle?, rootKey: String?) {
|
||||
preferenceManager.preferenceDataStore = DataStore.privateStore
|
||||
val activity = activity!!
|
||||
val profile = ProfileManager.getProfile(activity.intent.getIntExtra(Action.EXTRA_PROFILE_ID, -1))
|
||||
if (profile == null) {
|
||||
activity.finish()
|
||||
return
|
||||
}
|
||||
this.profile = profile
|
||||
profile.serialize()
|
||||
val activity = requireActivity()
|
||||
profileId = activity.intent.getIntExtra(Action.EXTRA_PROFILE_ID, -1)
|
||||
addPreferencesFromResource(R.xml.pref_profile)
|
||||
if (Build.VERSION.SDK_INT >= 25 && activity.getSystemService(UserManager::class.java).isDemoUser) {
|
||||
findPreference(Key.host).summary = "shadowsocks.example.org"
|
||||
@@ -130,11 +124,13 @@ class ProfileConfigFragment : PreferenceFragmentCompatDividers(), Toolbar.OnMenu
|
||||
}
|
||||
|
||||
fun saveAndExit() {
|
||||
val profile = ProfileManager.getProfile(profileId) ?: Profile()
|
||||
profile.id = profileId
|
||||
profile.deserialize()
|
||||
ProfileManager.updateProfile(profile)
|
||||
ProfilesFragment.instance?.profilesAdapter?.deepRefreshId(profile.id)
|
||||
if (DataStore.profileId == profile.id && DataStore.directBootAware) DirectBoot.update()
|
||||
activity!!.finish()
|
||||
ProfilesFragment.instance?.profilesAdapter?.deepRefreshId(profileId)
|
||||
if (DataStore.profileId == profileId && DataStore.directBootAware) DirectBoot.update()
|
||||
requireActivity().finish()
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
@@ -161,7 +157,7 @@ class ProfileConfigFragment : PreferenceFragmentCompatDividers(), Toolbar.OnMenu
|
||||
override fun onDisplayPreferenceDialog(preference: Preference) {
|
||||
if (preference.key == Key.pluginConfigure) {
|
||||
val intent = PluginManager.buildIntent(pluginConfiguration.selected, PluginContract.ACTION_CONFIGURE)
|
||||
if (intent.resolveActivity(activity!!.packageManager) != null)
|
||||
if (intent.resolveActivity(requireContext().packageManager) != null)
|
||||
startActivityForResult(intent.putExtra(PluginContract.EXTRA_OPTIONS,
|
||||
pluginConfiguration.selectedOptions.toString()), REQUEST_CODE_PLUGIN_CONFIGURE) else {
|
||||
showPluginEditor()
|
||||
@@ -183,11 +179,11 @@ class ProfileConfigFragment : PreferenceFragmentCompatDividers(), Toolbar.OnMenu
|
||||
|
||||
override fun onMenuItemClick(item: MenuItem) = when (item.itemId) {
|
||||
R.id.action_delete -> {
|
||||
val activity = activity!!
|
||||
val activity = requireActivity()
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle(R.string.delete_confirm_prompt)
|
||||
.setPositiveButton(R.string.yes, { _, _ ->
|
||||
ProfileManager.delProfile(profile.id)
|
||||
ProfileManager.delProfile(profileId)
|
||||
activity.finish()
|
||||
})
|
||||
.setNegativeButton(R.string.no, null)
|
||||
|
||||
@@ -123,12 +123,12 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
private var adView: AdView? = null
|
||||
|
||||
init {
|
||||
edit.setOnClickListener { startConfig(item.id) }
|
||||
edit.setOnClickListener { startConfig(item) }
|
||||
TooltipCompat.setTooltipText(edit, edit.contentDescription)
|
||||
itemView.setOnClickListener(this)
|
||||
val share = itemView.findViewById<View>(R.id.share)
|
||||
share.setOnClickListener {
|
||||
val popup = PopupMenu(activity!!, share)
|
||||
val popup = PopupMenu(requireContext(), share)
|
||||
popup.menuInflater.inflate(R.menu.profile_share_popup, popup.menu)
|
||||
popup.setOnMenuItemClickListener(this)
|
||||
popup.show()
|
||||
@@ -173,10 +173,10 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
var adView = adView
|
||||
if (item.host == "198.199.101.152") {
|
||||
if (adView == null) {
|
||||
val params =
|
||||
LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||
ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||
params.gravity = Gravity.CENTER_HORIZONTAL
|
||||
val context = context!!
|
||||
val context = requireContext()
|
||||
adView = AdView(context)
|
||||
adView.layoutParams = params
|
||||
adView.adUnitId = "ca-app-pub-9097031975646651/7760346322"
|
||||
@@ -208,7 +208,7 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
|
||||
override fun onMenuItemClick(item: MenuItem): Boolean = when (item.itemId) {
|
||||
R.id.action_qr_code_nfc -> {
|
||||
fragmentManager!!.beginTransaction().add(QRCodeDialog(this.item.toString()), "")
|
||||
requireFragmentManager().beginTransaction().add(QRCodeDialog(this.item.toString()), "")
|
||||
.commitAllowingStateLoss()
|
||||
true
|
||||
}
|
||||
@@ -230,7 +230,7 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
|
||||
override fun onBindViewHolder(holder: ProfileViewHolder, position: Int) = holder.bind(profiles[position])
|
||||
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProfileViewHolder = ProfileViewHolder(
|
||||
LayoutInflater.from(parent!!.context).inflate(R.layout.layout_profile, parent, false))
|
||||
LayoutInflater.from(parent.context).inflate(R.layout.layout_profile, parent, false))
|
||||
override fun getItemCount(): Int = profiles.size
|
||||
override fun getItemId(position: Int): Long = profiles[position].id.toLong()
|
||||
|
||||
@@ -305,10 +305,12 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
private var txTotal: Long = 0L
|
||||
private var rxTotal: Long = 0L
|
||||
|
||||
private val clipboard by lazy { activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||
private val clipboard by lazy { requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||
|
||||
private fun startConfig(id: Int) = startActivity(Intent(context, ProfileConfigActivity::class.java)
|
||||
.putExtra(Action.EXTRA_PROFILE_ID, id))
|
||||
private fun startConfig(profile: Profile) {
|
||||
profile.serialize()
|
||||
startActivity(Intent(context, ProfileConfigActivity::class.java).putExtra(Action.EXTRA_PROFILE_ID, profile.id))
|
||||
}
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
|
||||
inflater.inflate(R.layout.layout_list, container, false)
|
||||
@@ -331,7 +333,7 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
profilesList.itemAnimator = animator
|
||||
profilesList.adapter = profilesAdapter
|
||||
instance = this
|
||||
undoManager = UndoSnackbarManager(activity!!.findViewById(R.id.snackbar),
|
||||
undoManager = UndoSnackbarManager(requireActivity().findViewById(R.id.snackbar),
|
||||
profilesAdapter::undo, profilesAdapter::commit)
|
||||
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN,
|
||||
ItemTouchHelper.START or ItemTouchHelper.END) {
|
||||
@@ -351,7 +353,7 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
profilesAdapter.move(viewHolder.adapterPosition, target.adapterPosition)
|
||||
return true
|
||||
}
|
||||
override fun clearView(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?) {
|
||||
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
|
||||
super.clearView(recyclerView, viewHolder)
|
||||
profilesAdapter.commitMove()
|
||||
}
|
||||
@@ -366,25 +368,25 @@ class ProfilesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener {
|
||||
}
|
||||
R.id.action_import -> {
|
||||
try {
|
||||
val profiles = Profile.findAll(clipboard.primaryClip.getItemAt(0).text).toList()
|
||||
val profiles = Profile.findAll(clipboard.primaryClip!!.getItemAt(0).text).toList()
|
||||
if (profiles.isNotEmpty()) {
|
||||
profiles.forEach { ProfileManager.createProfile(it) }
|
||||
Snackbar.make(activity!!.findViewById(R.id.snackbar), R.string.action_import_msg,
|
||||
Snackbar.make(requireActivity().findViewById(R.id.snackbar), R.string.action_import_msg,
|
||||
Snackbar.LENGTH_LONG).show()
|
||||
return true
|
||||
}
|
||||
} catch (_: IndexOutOfBoundsException) { }
|
||||
Snackbar.make(activity!!.findViewById(R.id.snackbar), R.string.action_import_err, Snackbar.LENGTH_LONG)
|
||||
.show()
|
||||
} catch (_: Exception) { }
|
||||
Snackbar.make(requireActivity().findViewById(R.id.snackbar), R.string.action_import_err,
|
||||
Snackbar.LENGTH_LONG).show()
|
||||
true
|
||||
}
|
||||
R.id.action_manual_settings -> {
|
||||
startConfig(ProfileManager.createProfile().id)
|
||||
startConfig(ProfileManager.createProfile())
|
||||
true
|
||||
}
|
||||
R.id.action_export -> {
|
||||
val profiles = ProfileManager.getAllProfiles()
|
||||
Snackbar.make(activity!!.findViewById(R.id.snackbar), if (profiles != null) {
|
||||
Snackbar.make(requireActivity().findViewById(R.id.snackbar), if (profiles != null) {
|
||||
clipboard.primaryClip = ClipData.newPlainText(null, profiles.joinToString("\n"))
|
||||
R.string.action_export_msg
|
||||
} else R.string.action_export_err, Snackbar.LENGTH_LONG).show()
|
||||
|
||||
@@ -80,7 +80,7 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
private lateinit var positive: Button
|
||||
|
||||
init {
|
||||
val activity = activity!!
|
||||
val activity = requireActivity()
|
||||
val view = activity.layoutInflater.inflate(R.layout.dialog_acl_rule, null)
|
||||
templateSelector = view.findViewById(R.id.template_selector)
|
||||
editText = view.findViewById(R.id.content)
|
||||
@@ -360,7 +360,7 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
private lateinit var list: RecyclerView
|
||||
private var mode: ActionMode? = null
|
||||
private lateinit var undoManager: UndoSnackbarManager<Any>
|
||||
private val clipboard by lazy { activity!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||
private val clipboard by lazy { requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||
|
||||
private fun onSelectedItemsUpdated() {
|
||||
if (selectedItems.isEmpty()) mode?.finish() else if (mode == null) mode = toolbar.startActionMode(this)
|
||||
@@ -383,12 +383,13 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
toolbar.setTitle(R.string.custom_rules)
|
||||
toolbar.inflateMenu(R.menu.custom_rules_menu)
|
||||
toolbar.setOnMenuItemClickListener(this)
|
||||
val activity = requireActivity()
|
||||
list = view.findViewById(R.id.list)
|
||||
list.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
|
||||
list.itemAnimator = DefaultItemAnimator()
|
||||
list.adapter = adapter
|
||||
view.findViewById<FastScroller>(R.id.fastscroller).setRecyclerView(list)
|
||||
undoManager = UndoSnackbarManager(activity!!.findViewById(R.id.snackbar), adapter::undo)
|
||||
undoManager = UndoSnackbarManager(activity.findViewById(R.id.snackbar), adapter::undo)
|
||||
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.START or ItemTouchHelper.END) {
|
||||
override fun getSwipeDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int =
|
||||
if (isEnabled && selectedItems.isEmpty()) super.getSwipeDirs(recyclerView, viewHolder) else 0
|
||||
@@ -437,10 +438,10 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
}
|
||||
R.id.action_import -> {
|
||||
try {
|
||||
adapter.addToProxy(clipboard.primaryClip.getItemAt(0).text.toString()) != null
|
||||
check(adapter.addToProxy(clipboard.primaryClip!!.getItemAt(0).text.toString()) != null)
|
||||
} catch (exc: Exception) {
|
||||
Snackbar.make(activity!!.findViewById(R.id.snackbar), R.string.action_import_err, Snackbar.LENGTH_LONG)
|
||||
.show()
|
||||
Snackbar.make(requireActivity().findViewById(R.id.snackbar), R.string.action_import_err,
|
||||
Snackbar.LENGTH_LONG).show()
|
||||
app.track(exc)
|
||||
}
|
||||
true
|
||||
@@ -462,7 +463,7 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
}
|
||||
|
||||
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
|
||||
val activity = activity!!
|
||||
val activity = requireActivity()
|
||||
val window = activity.window
|
||||
// In the end material_grey_100 is used for background, see AppCompatDrawableManager (very complicated)
|
||||
if (Build.VERSION.SDK_INT >= 23) {
|
||||
@@ -495,7 +496,7 @@ class CustomRulesFragment : ToolbarFragment(), Toolbar.OnMenuItemClickListener,
|
||||
else -> false
|
||||
}
|
||||
override fun onDestroyActionMode(mode: ActionMode) {
|
||||
val activity = activity!!
|
||||
val activity = requireActivity()
|
||||
val window = activity.window
|
||||
window.statusBarColor = ContextCompat.getColor(activity,
|
||||
activity.theme.resolveResourceId(android.R.attr.statusBarColor))
|
||||
|
||||
@@ -49,6 +49,7 @@ import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.UnknownHostException
|
||||
import java.security.MessageDigest
|
||||
import java.util.*
|
||||
@@ -116,7 +117,10 @@ object BaseService {
|
||||
val item = callbacks.getBroadcastItem(i)
|
||||
if (bandwidthListeners.contains(item.asBinder()))
|
||||
item.trafficUpdated(profile!!.id, txRate, rxRate, txTotal, rxTotal)
|
||||
} catch (_: Exception) { } // ignore
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
app.track(e)
|
||||
}
|
||||
callbacks.finishBroadcast()
|
||||
}
|
||||
}
|
||||
@@ -145,22 +149,35 @@ object BaseService {
|
||||
}
|
||||
|
||||
internal fun updateTrafficTotal(tx: Long, rx: Long) {
|
||||
// this.profile may have host, etc. modified and thus a re-fetch is necessary (possible race condition)
|
||||
val profile = ProfileManager.getProfile((profile ?: return).id) ?: return
|
||||
profile.tx += tx
|
||||
profile.rx += rx
|
||||
ProfileManager.updateProfile(profile)
|
||||
app.handler.post {
|
||||
if (bandwidthListeners.isNotEmpty()) {
|
||||
val n = callbacks.beginBroadcast()
|
||||
for (i in 0 until n) {
|
||||
try {
|
||||
val item = callbacks.getBroadcastItem(i)
|
||||
if (bandwidthListeners.contains(item.asBinder())) item.trafficPersisted(profile.id)
|
||||
} catch (_: Exception) { } // ignore
|
||||
try {
|
||||
// this.profile may have host, etc. modified and thus a re-fetch is necessary (possible race condition)
|
||||
val profile = ProfileManager.getProfile((profile ?: return).id) ?: return
|
||||
profile.tx += tx
|
||||
profile.rx += rx
|
||||
ProfileManager.updateProfile(profile)
|
||||
app.handler.post {
|
||||
if (bandwidthListeners.isNotEmpty()) {
|
||||
val n = callbacks.beginBroadcast()
|
||||
for (i in 0 until n) {
|
||||
try {
|
||||
val item = callbacks.getBroadcastItem(i)
|
||||
if (bandwidthListeners.contains(item.asBinder())) item.trafficPersisted(profile.id)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
app.track(e)
|
||||
}
|
||||
}
|
||||
callbacks.finishBroadcast()
|
||||
}
|
||||
callbacks.finishBroadcast()
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
if (!DataStore.directBootAware) throw e // we should only reach here because we're in direct boot
|
||||
val profile = DirectBoot.getDeviceProfile()!!
|
||||
profile.tx += tx
|
||||
profile.rx += rx
|
||||
profile.dirty = true
|
||||
DirectBoot.update(profile)
|
||||
DirectBoot.listenForUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +217,10 @@ object BaseService {
|
||||
val n = callbacks.beginBroadcast()
|
||||
for (i in 0 until n) try {
|
||||
callbacks.getBroadcastItem(i).stateChanged(s, binder.profileName, msg)
|
||||
} catch (_: Exception) { } // ignore
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
app.track(e)
|
||||
}
|
||||
callbacks.finishBroadcast()
|
||||
}
|
||||
state = s
|
||||
@@ -235,6 +255,7 @@ object BaseService {
|
||||
|
||||
fun startNativeProcesses() {
|
||||
val data = data
|
||||
val profile = data.profile!!
|
||||
val cmd = buildAdditionalArguments(arrayListOf(
|
||||
File((this as Context).applicationInfo.nativeLibraryDir, Executable.SS_LOCAL).absolutePath,
|
||||
"-u",
|
||||
@@ -249,6 +270,8 @@ object BaseService {
|
||||
cmd += acl.absolutePath
|
||||
}
|
||||
|
||||
if (profile.udpdns) cmd += "-D"
|
||||
|
||||
if (TcpFastOpen.sendEnabled) cmd += "--fast-open"
|
||||
|
||||
data.sslocalProcess = GuardedProcess(cmd).start()
|
||||
@@ -341,7 +364,7 @@ object BaseService {
|
||||
|
||||
data.changeState(CONNECTING)
|
||||
|
||||
thread {
|
||||
thread("$tag-Connecting") {
|
||||
try {
|
||||
if (profile.host == "198.199.101.152") {
|
||||
val client = OkHttpClient.Builder()
|
||||
|
||||
@@ -28,6 +28,7 @@ import com.github.shadowsocks.BuildConfig
|
||||
import com.github.shadowsocks.JniHelper
|
||||
import com.github.shadowsocks.utils.Commandline
|
||||
import com.github.shadowsocks.utils.thread
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.util.concurrent.Semaphore
|
||||
@@ -42,8 +43,9 @@ class GuardedProcess(private val cmd: List<String>) {
|
||||
private var isDestroyed = false
|
||||
@Volatile
|
||||
private lateinit var process: Process
|
||||
private val name = File(cmd.first()).nameWithoutExtension
|
||||
|
||||
private fun streamLogger(input: InputStream, logger: (String, String) -> Int) = thread {
|
||||
private fun streamLogger(input: InputStream, logger: (String, String) -> Int) = thread("StreamLogger-$name") {
|
||||
try {
|
||||
input.bufferedReader().useLines { it.forEach { logger(TAG, it) } }
|
||||
} catch (_: IOException) { } // ignore
|
||||
@@ -53,7 +55,7 @@ class GuardedProcess(private val cmd: List<String>) {
|
||||
val semaphore = Semaphore(1)
|
||||
semaphore.acquire()
|
||||
var ioException: IOException? = null
|
||||
guardThread = thread(name = "GuardThread-" + cmd.first()) {
|
||||
guardThread = thread("GuardThread-$name") {
|
||||
try {
|
||||
var callback: (() -> Unit)? = null
|
||||
while (!isDestroyed) {
|
||||
|
||||
@@ -72,12 +72,11 @@ object LocalDnsService {
|
||||
.put("MinimumTTL", 120)
|
||||
.put("CacheSize", 4096)
|
||||
val remoteDns = JSONArray(profile.remoteDns.split(",")
|
||||
.mapIndexed { i, dns -> makeDns("UserDef-" + i,
|
||||
dns.trim() + ":53", 9) })
|
||||
.mapIndexed { i, dns -> makeDns("UserDef-$i", dns.trim() + ":53", 9) })
|
||||
val localDns = JSONArray(arrayOf(
|
||||
makeDns("Primary-1", "119.29.29.29:53", 3, false),
|
||||
makeDns("Primary-2", "114.114.114.114:53", 3, false),
|
||||
makeDns("Primary-3", "208.67.222.222:443", 3, false)
|
||||
makeDns("Primary-1", "208.67.222.222:443", 3, false),
|
||||
makeDns("Primary-2", "119.29.29.29:53", 3, false),
|
||||
makeDns("Primary-3", "114.114.114.114:53", 3, false)
|
||||
))
|
||||
|
||||
when (profile.route) {
|
||||
@@ -85,7 +84,6 @@ object LocalDnsService {
|
||||
.put("PrimaryDNS", localDns)
|
||||
.put("AlternativeDNS", remoteDns)
|
||||
.put("IPNetworkFile", "china_ip_list.txt")
|
||||
.put("DomainFile", data.aclFile!!.absolutePath)
|
||||
Acl.CHINALIST -> config
|
||||
.put("PrimaryDNS", localDns)
|
||||
.put("AlternativeDNS", remoteDns)
|
||||
|
||||
@@ -28,7 +28,7 @@ import com.github.shadowsocks.App.Companion.app
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
abstract class LocalSocketListener(protected val tag: String) : Thread() {
|
||||
abstract class LocalSocketListener(protected val tag: String) : Thread(tag) {
|
||||
init {
|
||||
setUncaughtExceptionHandler(app::track)
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ class TileService : BaseTileService(), ShadowsocksConnection.Interface {
|
||||
}
|
||||
|
||||
override fun onClick() {
|
||||
if (isLocked && !DataStore.directBootAware) unlockAndRun(this::toggle) else toggle()
|
||||
if (isLocked && !DataStore.canToggleLocked) unlockAndRun(this::toggle) else toggle()
|
||||
}
|
||||
|
||||
private fun toggle() {
|
||||
|
||||
@@ -20,12 +20,16 @@
|
||||
|
||||
package com.github.shadowsocks.bg
|
||||
|
||||
import android.annotation.TargetApi
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.LocalSocket
|
||||
import android.net.*
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.support.v4.os.BuildCompat
|
||||
import android.util.Log
|
||||
import com.github.shadowsocks.App.Companion.app
|
||||
import com.github.shadowsocks.JniHelper
|
||||
@@ -50,6 +54,21 @@ class VpnService : BaseVpnService(), LocalDnsService.Interface {
|
||||
private const val PRIVATE_VLAN6 = "fdfe:dcba:9876::%s"
|
||||
|
||||
private val getInt: Method = FileDescriptor::class.java.getDeclaredMethod("getInt$")
|
||||
|
||||
/**
|
||||
* Unfortunately registerDefaultNetworkCallback is going to return VPN interface since Android P DP1:
|
||||
* https://android.googlesource.com/platform/frameworks/base/+/dda156ab0c5d66ad82bdcf76cda07cbc0a9c8a2e
|
||||
*
|
||||
* This makes doing a requestNetwork with REQUEST necessary so that we don't get ALL possible networks that
|
||||
* satisfies default network capabilities but only THE default network. Unfortunately we need to have
|
||||
* android.permission.CHANGE_NETWORK_STATE to be able to call requestNetwork.
|
||||
*
|
||||
* Source: https://android.googlesource.com/platform/frameworks/base/+/2df4c7d/services/core/java/com/android/server/ConnectivityService.java#887
|
||||
*/
|
||||
private val defaultNetworkRequest = NetworkRequest.Builder()
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
||||
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
|
||||
.build()
|
||||
}
|
||||
|
||||
private inner class ProtectWorker : LocalSocketListener("ShadowsocksVpnThread") {
|
||||
@@ -59,13 +78,22 @@ class VpnService : BaseVpnService(), LocalDnsService.Interface {
|
||||
var success = false
|
||||
try {
|
||||
socket.inputStream.read()
|
||||
val fds = socket.ancillaryFileDescriptors
|
||||
if (fds.isEmpty()) return
|
||||
val fd = getInt.invoke(fds.first()) as Int
|
||||
success = protect(fd)
|
||||
JniHelper.close(fd) // Trick to close file decriptor
|
||||
val fd = socket.ancillaryFileDescriptors!!.single()!!
|
||||
val fdInt = getInt.invoke(fd) as Int
|
||||
try {
|
||||
val network = underlyingNetwork
|
||||
success = if (network != null && Build.VERSION.SDK_INT >= 23) {
|
||||
network.bindSocket(fd)
|
||||
true
|
||||
} else protect(fdInt)
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Error when protect socket", e)
|
||||
app.track(e)
|
||||
} finally {
|
||||
JniHelper.close(fdInt) // Trick to close file decriptor
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(tag, "Error when protect socket", e)
|
||||
Log.e(tag, "Error when receiving ancillary fd", e)
|
||||
app.track(e)
|
||||
}
|
||||
try {
|
||||
@@ -89,6 +117,28 @@ class VpnService : BaseVpnService(), LocalDnsService.Interface {
|
||||
private var conn: ParcelFileDescriptor? = null
|
||||
private var worker: ProtectWorker? = null
|
||||
private var tun2socksProcess: GuardedProcess? = null
|
||||
private var underlyingNetwork: Network? = null
|
||||
@TargetApi(28)
|
||||
set(value) {
|
||||
setUnderlyingNetworks(if (value == null) null else arrayOf(value))
|
||||
field = value
|
||||
}
|
||||
|
||||
private val connectivity by lazy { getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager }
|
||||
@TargetApi(28)
|
||||
private val defaultNetworkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
underlyingNetwork = network
|
||||
}
|
||||
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities?) {
|
||||
// it's a good idea to refresh capabilities
|
||||
underlyingNetwork = network
|
||||
}
|
||||
override fun onLost(network: Network) {
|
||||
underlyingNetwork = null
|
||||
}
|
||||
}
|
||||
private var listeningForDefaultNetwork = false
|
||||
|
||||
override fun onBind(intent: Intent): IBinder? = when (intent.action) {
|
||||
SERVICE_INTERFACE -> super<BaseVpnService>.onBind(intent)
|
||||
@@ -98,6 +148,10 @@ class VpnService : BaseVpnService(), LocalDnsService.Interface {
|
||||
override fun onRevoke() = stopRunner(true)
|
||||
|
||||
override fun killProcesses() {
|
||||
if (listeningForDefaultNetwork) {
|
||||
connectivity.unregisterNetworkCallback(defaultNetworkCallback)
|
||||
listeningForDefaultNetwork = false
|
||||
}
|
||||
worker?.stopThread()
|
||||
worker = null
|
||||
super.killProcesses()
|
||||
@@ -179,6 +233,12 @@ class VpnService : BaseVpnService(), LocalDnsService.Interface {
|
||||
this.conn = conn
|
||||
val fd = conn.fd
|
||||
|
||||
if (BuildCompat.isAtLeastP()) {
|
||||
// we want REQUEST here instead of LISTEN
|
||||
connectivity.requestNetwork(defaultNetworkRequest, defaultNetworkCallback)
|
||||
listeningForDefaultNetwork = true
|
||||
}
|
||||
|
||||
val cmd = arrayListOf(File(applicationInfo.nativeLibraryDir, Executable.TUN2SOCKS).absolutePath,
|
||||
"--netif-ipaddr", PRIVATE_VLAN.format(Locale.ENGLISH, "2"),
|
||||
"--netif-netmask", "255.255.255.0",
|
||||
|
||||
@@ -31,6 +31,7 @@ import com.j256.ormlite.field.DataType
|
||||
import com.j256.ormlite.field.DatabaseField
|
||||
import java.io.Serializable
|
||||
import java.net.URI
|
||||
import java.net.URISyntaxException
|
||||
import java.util.*
|
||||
|
||||
class Profile : Serializable {
|
||||
@@ -43,41 +44,51 @@ class Profile : Serializable {
|
||||
|
||||
fun findAll(data: CharSequence?) = pattern.findAll(data ?: "").map {
|
||||
val uri = Uri.parse(it.value)
|
||||
if (uri.userInfo == null) {
|
||||
val match = legacyPattern.matchEntire(String(Base64.decode(uri.host, Base64.NO_PADDING)))
|
||||
if (match != null) {
|
||||
val profile = Profile()
|
||||
profile.method = match.groupValues[1].toLowerCase()
|
||||
profile.password = match.groupValues[2]
|
||||
profile.host = match.groupValues[3]
|
||||
profile.remotePort = match.groupValues[4].toInt()
|
||||
profile.plugin = uri.getQueryParameter(Key.plugin)
|
||||
profile.name = uri.fragment
|
||||
profile
|
||||
try {
|
||||
if (uri.userInfo == null) {
|
||||
val match = legacyPattern.matchEntire(String(Base64.decode(uri.host, Base64.NO_PADDING)))
|
||||
if (match != null) {
|
||||
val profile = Profile()
|
||||
profile.method = match.groupValues[1].toLowerCase()
|
||||
profile.password = match.groupValues[2]
|
||||
profile.host = match.groupValues[3]
|
||||
profile.remotePort = match.groupValues[4].toInt()
|
||||
profile.plugin = uri.getQueryParameter(Key.plugin)
|
||||
profile.name = uri.fragment
|
||||
profile
|
||||
} else {
|
||||
Log.e(TAG, "Unrecognized URI: ${it.value}")
|
||||
null
|
||||
}
|
||||
} else {
|
||||
Log.e(TAG, "Unrecognized URI: ${it.value}")
|
||||
null
|
||||
}
|
||||
} else {
|
||||
val match = userInfoPattern.matchEntire(String(Base64.decode(uri.userInfo,
|
||||
Base64.NO_PADDING or Base64.NO_WRAP or Base64.URL_SAFE)))
|
||||
if (match != null) {
|
||||
val profile = Profile()
|
||||
profile.method = match.groupValues[1]
|
||||
profile.password = match.groupValues[2]
|
||||
// bug in Android: https://code.google.com/p/android/issues/detail?id=192855
|
||||
val javaURI = URI(it.value)
|
||||
profile.host = javaURI.host
|
||||
if (profile.host.firstOrNull() == '[' && profile.host.lastOrNull() == ']')
|
||||
profile.host = profile.host.substring(1, profile.host.length - 1)
|
||||
profile.remotePort = javaURI.port
|
||||
profile.plugin = uri.getQueryParameter(Key.plugin)
|
||||
profile.name = uri.fragment ?: ""
|
||||
profile
|
||||
} else {
|
||||
Log.e(TAG, "Unknown user info: ${it.value}")
|
||||
null
|
||||
val match = userInfoPattern.matchEntire(String(Base64.decode(uri.userInfo,
|
||||
Base64.NO_PADDING or Base64.NO_WRAP or Base64.URL_SAFE)))
|
||||
if (match != null) {
|
||||
val profile = Profile()
|
||||
profile.method = match.groupValues[1]
|
||||
profile.password = match.groupValues[2]
|
||||
// bug in Android: https://code.google.com/p/android/issues/detail?id=192855
|
||||
try {
|
||||
val javaURI = URI(it.value)
|
||||
profile.host = javaURI.host ?: ""
|
||||
if (profile.host.firstOrNull() == '[' && profile.host.lastOrNull() == ']')
|
||||
profile.host = profile.host.substring(1, profile.host.length - 1)
|
||||
profile.remotePort = javaURI.port
|
||||
profile.plugin = uri.getQueryParameter(Key.plugin)
|
||||
profile.name = uri.fragment ?: ""
|
||||
profile
|
||||
} catch (e: URISyntaxException) {
|
||||
Log.e(TAG, "Invalid URI: ${it.value}")
|
||||
null
|
||||
}
|
||||
} else {
|
||||
Log.e(TAG, "Unknown user info: ${it.value}")
|
||||
null
|
||||
}
|
||||
}
|
||||
} catch (e: IllegalArgumentException) {
|
||||
Log.e(TAG, "Invalid base64 detected: ${it.value}")
|
||||
null
|
||||
}
|
||||
}.filterNotNull()
|
||||
}
|
||||
@@ -136,6 +147,9 @@ class Profile : Serializable {
|
||||
@DatabaseField
|
||||
var plugin: String? = null
|
||||
|
||||
// not persisted in db, only used by direct boot
|
||||
var dirty: Boolean = false
|
||||
|
||||
val formattedAddress get() = (if (host.contains(":")) "[%s]:%d" else "%s:%d").format(host, remotePort)
|
||||
val formattedName get() = if (name.isNullOrEmpty()) formattedAddress else name!!
|
||||
|
||||
|
||||
@@ -20,11 +20,13 @@
|
||||
|
||||
package com.github.shadowsocks.database
|
||||
|
||||
import android.database.sqlite.SQLiteCantOpenDatabaseException
|
||||
import android.util.Log
|
||||
import com.github.shadowsocks.App.Companion.app
|
||||
import com.github.shadowsocks.ProfilesFragment
|
||||
import com.github.shadowsocks.preference.DataStore
|
||||
import com.github.shadowsocks.utils.DirectBoot
|
||||
import java.io.IOException
|
||||
import java.sql.SQLException
|
||||
|
||||
/**
|
||||
@@ -62,9 +64,11 @@ object ProfileManager {
|
||||
@Throws(SQLException::class)
|
||||
fun updateProfile(profile: Profile) = PrivateDatabase.profileDao.update(profile)
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun getProfile(id: Int): Profile? = try {
|
||||
PrivateDatabase.profileDao.queryForId(id)
|
||||
} catch (ex: SQLException) {
|
||||
if (ex.cause is SQLiteCantOpenDatabaseException) throw IOException(ex)
|
||||
Log.e(TAG, "getProfile", ex)
|
||||
app.track(ex)
|
||||
null
|
||||
@@ -77,17 +81,21 @@ object ProfileManager {
|
||||
if (id == DataStore.profileId && DataStore.directBootAware) DirectBoot.clean()
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun getFirstProfile(): Profile? = try {
|
||||
PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().limit(1L).prepare()).singleOrNull()
|
||||
} catch (ex: SQLException) {
|
||||
if (ex.cause is SQLiteCantOpenDatabaseException) throw IOException(ex)
|
||||
Log.e(TAG, "getFirstProfile", ex)
|
||||
app.track(ex)
|
||||
null
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun getAllProfiles(): List<Profile>? = try {
|
||||
PrivateDatabase.profileDao.query(PrivateDatabase.profileDao.queryBuilder().orderBy("userOrder", true).prepare())
|
||||
} catch (ex: SQLException) {
|
||||
if (ex.cause is SQLiteCantOpenDatabaseException) throw IOException(ex)
|
||||
Log.e(TAG, "getAllProfiles", ex)
|
||||
app.track(ex)
|
||||
null
|
||||
|
||||
@@ -25,7 +25,7 @@ import android.os.Bundle
|
||||
|
||||
class NativePlugin(resolveInfo: ResolveInfo) : ResolvedPlugin(resolveInfo) {
|
||||
init {
|
||||
assert(resolveInfo.providerInfo != null)
|
||||
check(resolveInfo.providerInfo != null)
|
||||
}
|
||||
|
||||
override val metaData: Bundle get() = resolveInfo.providerInfo.metaData
|
||||
|
||||
@@ -87,21 +87,19 @@ object PluginManager {
|
||||
|
||||
private var receiver: BroadcastReceiver? = null
|
||||
private var cachedPlugins: Map<String, Plugin>? = null
|
||||
fun fetchPlugins(): Map<String, Plugin> {
|
||||
return synchronized(this) {
|
||||
if (receiver == null) receiver = app.listenForPackageChanges {
|
||||
synchronized(this) {
|
||||
receiver = null
|
||||
cachedPlugins = null
|
||||
}
|
||||
fun fetchPlugins(): Map<String, Plugin> = synchronized(this) {
|
||||
if (receiver == null) receiver = app.listenForPackageChanges {
|
||||
synchronized(this) {
|
||||
receiver = null
|
||||
cachedPlugins = null
|
||||
}
|
||||
if (cachedPlugins == null) {
|
||||
val pm = app.packageManager
|
||||
cachedPlugins = (pm.queryIntentContentProviders(Intent(PluginContract.ACTION_NATIVE_PLUGIN),
|
||||
PackageManager.GET_META_DATA).map { NativePlugin(it) } + NoPlugin).associate { it.id to it }
|
||||
}
|
||||
cachedPlugins!!
|
||||
}
|
||||
if (cachedPlugins == null) {
|
||||
val pm = app.packageManager
|
||||
cachedPlugins = (pm.queryIntentContentProviders(Intent(PluginContract.ACTION_NATIVE_PLUGIN),
|
||||
PackageManager.GET_META_DATA).map { NativePlugin(it) } + NoPlugin).associate { it.id to it }
|
||||
}
|
||||
cachedPlugins!!
|
||||
}
|
||||
|
||||
private fun buildUri(id: String) = Uri.Builder()
|
||||
@@ -134,10 +132,10 @@ object PluginManager {
|
||||
private fun initNative(options: PluginOptions): String? {
|
||||
val providers = app.packageManager.queryIntentContentProviders(
|
||||
Intent(PluginContract.ACTION_NATIVE_PLUGIN, buildUri(options.id)), 0)
|
||||
assert(providers.size == 1)
|
||||
if (providers.isEmpty()) return null
|
||||
val uri = Uri.Builder()
|
||||
.scheme(ContentResolver.SCHEME_CONTENT)
|
||||
.authority(providers[0].providerInfo.authority)
|
||||
.authority(providers.single().providerInfo.authority)
|
||||
.build()
|
||||
val cr = app.contentResolver
|
||||
return try {
|
||||
@@ -154,7 +152,7 @@ object PluginManager {
|
||||
out.putString(PluginContract.EXTRA_OPTIONS, options.id)
|
||||
val result = cr.call(uri, PluginContract.METHOD_GET_EXECUTABLE, null, out)
|
||||
.getString(PluginContract.EXTRA_ENTRY)
|
||||
assert(File(result).canExecute())
|
||||
check(File(result).canExecute())
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -173,7 +171,7 @@ object PluginManager {
|
||||
do {
|
||||
val path = cursor.getString(0)
|
||||
val file = File(pluginDir, path)
|
||||
assert(file.absolutePath.startsWith(pluginDirPath))
|
||||
check(file.absolutePath.startsWith(pluginDirPath))
|
||||
cr.openInputStream(uri.buildUpon().path(path).build()).use { inStream ->
|
||||
file.outputStream().use { outStream -> inStream.copyTo(outStream) }
|
||||
}
|
||||
|
||||
@@ -33,5 +33,7 @@ abstract class ResolvedPlugin(protected val resolveInfo: ResolveInfo) : Plugin()
|
||||
override val icon: Drawable by lazy { resolveInfo.loadIcon(app.packageManager) }
|
||||
override val defaultConfig: String by lazy { metaData.getString(PluginContract.METADATA_KEY_DEFAULT_CONFIG) }
|
||||
override val packageName: String get() = resolveInfo.resolvePackageName
|
||||
override val trusted by lazy { app.info.signatures.any(PluginManager.trustedSignatures::contains) }
|
||||
override val trusted by lazy {
|
||||
app.getPackageInfo(packageName).signatures.any(PluginManager.trustedSignatures::contains)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -101,8 +101,8 @@ class BottomSheetPreferenceDialogFragment : PreferenceDialogFragmentCompat() {
|
||||
private var clickedIndex = -1
|
||||
|
||||
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
|
||||
val activity = activity
|
||||
val dialog = BottomSheetDialog(activity!!, theme)
|
||||
val activity = requireActivity()
|
||||
val dialog = BottomSheetDialog(activity, theme)
|
||||
val recycler = RecyclerView(activity)
|
||||
val padding = resources.getDimensionPixelOffset(R.dimen.bottom_sheet_padding)
|
||||
recycler.setPadding(0, padding, 0, padding)
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
package com.github.shadowsocks.preference
|
||||
|
||||
import android.os.Binder
|
||||
import com.github.shadowsocks.BootReceiver
|
||||
import com.github.shadowsocks.App.Companion.app
|
||||
import com.github.shadowsocks.database.PrivateDatabase
|
||||
import com.github.shadowsocks.database.PublicDatabase
|
||||
import com.github.shadowsocks.utils.DirectBoot
|
||||
@@ -49,10 +49,8 @@ object DataStore {
|
||||
publicStore.putInt(Key.id, value)
|
||||
if (DataStore.directBootAware) DirectBoot.update()
|
||||
}
|
||||
/**
|
||||
* Setter is defined in MainActivity.onPreferenceDataStoreChanged.
|
||||
*/
|
||||
val directBootAware: Boolean get() = BootReceiver.enabled && publicStore.getBoolean(Key.directBootAware) == true
|
||||
val canToggleLocked: Boolean get() = publicStore.getBoolean(Key.directBootAware) == true
|
||||
val directBootAware: Boolean get() = app.directBootSupported && canToggleLocked
|
||||
var serviceMode: String
|
||||
get() = publicStore.getString(Key.serviceMode) ?: Key.modeVpn
|
||||
set(value) = publicStore.putString(Key.serviceMode, value)
|
||||
|
||||
+3
-2
@@ -40,8 +40,9 @@ class PluginConfigurationDialogFragment : EditTextPreferenceDialogFragmentCompat
|
||||
super.onPrepareDialogBuilder(builder)
|
||||
val intent = PluginManager.buildIntent(arguments!!.getString(PLUGIN_ID_FRAGMENT_TAG),
|
||||
PluginContract.ACTION_HELP)
|
||||
if (intent.resolveActivity(activity!!.packageManager) != null) builder.setNeutralButton("?", { _, _ ->
|
||||
activity!!.startActivityForResult(intent.putExtra(PluginContract.EXTRA_OPTIONS, editText.text.toString()),
|
||||
val activity = requireActivity()
|
||||
if (intent.resolveActivity(activity.packageManager) != null) builder.setNeutralButton("?", { _, _ ->
|
||||
activity.startActivityForResult(intent.putExtra(PluginContract.EXTRA_OPTIONS, editText.text.toString()),
|
||||
ProfileConfigActivity.REQUEST_CODE_PLUGIN_HELP)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -29,8 +29,8 @@ import com.twofortyfouram.locale.api.Intent as ApiIntent
|
||||
|
||||
class Settings(bundle: Bundle?) {
|
||||
companion object {
|
||||
private val KEY_SWITCH_ON = "switch_on"
|
||||
private val KEY_PROFILE_ID = "profile_id"
|
||||
private const val KEY_SWITCH_ON = "switch_on"
|
||||
private const val KEY_PROFILE_ID = "profile_id"
|
||||
|
||||
fun fromIntent(intent: Intent) = Settings(intent.getBundleExtra(ApiIntent.EXTRA_BUNDLE))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package com.github.shadowsocks.utils
|
||||
|
||||
import android.annotation.TargetApi
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import com.github.shadowsocks.App.Companion.app
|
||||
import com.github.shadowsocks.bg.BaseService
|
||||
import com.github.shadowsocks.database.Profile
|
||||
@@ -12,8 +16,9 @@ import java.io.ObjectInputStream
|
||||
import java.io.ObjectOutputStream
|
||||
|
||||
@TargetApi(24)
|
||||
object DirectBoot {
|
||||
object DirectBoot : BroadcastReceiver() {
|
||||
private val file = File(app.deviceContext.noBackupFilesDir, "directBootProfile")
|
||||
private var registered = false
|
||||
|
||||
fun getDeviceProfile(): Profile? = try {
|
||||
ObjectInputStream(file.inputStream()).use { it.readObject() as Profile }
|
||||
@@ -24,8 +29,26 @@ object DirectBoot {
|
||||
File(app.deviceContext.noBackupFilesDir, BaseService.CONFIG_FILE).delete()
|
||||
}
|
||||
|
||||
fun update() {
|
||||
val profile = ProfileManager.getProfile(DataStore.profileId) // app.currentProfile will call this
|
||||
if (profile == null) clean() else ObjectOutputStream(file.outputStream()).use { it.writeObject(profile) }
|
||||
/**
|
||||
* app.currentProfile will call this.
|
||||
*/
|
||||
fun update(profile: Profile? = ProfileManager.getProfile(DataStore.profileId)) =
|
||||
if (profile == null) clean() else ObjectOutputStream(file.outputStream()).use { it.writeObject(profile) }
|
||||
|
||||
fun flushTrafficStats() {
|
||||
val profile = getDeviceProfile()
|
||||
if (profile?.dirty == true) ProfileManager.updateProfile(profile)
|
||||
update()
|
||||
}
|
||||
|
||||
fun listenForUnlock() {
|
||||
if (registered) return
|
||||
app.registerReceiver(this, IntentFilter(Intent.ACTION_BOOT_COMPLETED))
|
||||
registered = true
|
||||
}
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
flushTrafficStats()
|
||||
app.unregisterReceiver(this)
|
||||
registered = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,5 +52,5 @@ object TcpFastOpen {
|
||||
"else",
|
||||
" echo Failed.",
|
||||
"fi"), null, true)?.joinToString("\n")
|
||||
fun enabledAsync(value: Boolean) = thread { enabled(value) }.join(1000)
|
||||
fun enabledAsync(value: Boolean) = thread("TcpFastOpen") { enabled(value) }.join(1000)
|
||||
}
|
||||
|
||||
@@ -39,8 +39,8 @@ fun broadcastReceiver(callback: (Context, Intent) -> Unit): BroadcastReceiver =
|
||||
/**
|
||||
* Wrapper for kotlin.concurrent.thread that tracks uncaught exceptions.
|
||||
*/
|
||||
fun thread(start: Boolean = true, isDaemon: Boolean = false, contextClassLoader: ClassLoader? = null,
|
||||
name: String? = null, priority: Int = -1, block: () -> Unit): Thread {
|
||||
fun thread(name: String? = null, start: Boolean = true, isDaemon: Boolean = false,
|
||||
contextClassLoader: ClassLoader? = null, priority: Int = -1, block: () -> Unit): Thread {
|
||||
val thread = kotlin.concurrent.thread(false, isDaemon, contextClassLoader, name, priority, block)
|
||||
thread.setUncaughtExceptionHandler(app::track)
|
||||
if (start) thread.start()
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/material_grey_100"/>
|
||||
<foreground>
|
||||
<!-- 44dp icon scaled to 52dp in 72dp, padding = (1-52/44*24/72)/2 -->
|
||||
<inset
|
||||
android:drawable="@drawable/ic_image_camera_alt"
|
||||
android:inset="30.303%"/>
|
||||
</foreground>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/material_grey_100"/>
|
||||
<foreground>
|
||||
<!-- 44dp icon scaled to 52dp in 72dp, padding = (1-52/44*24/72)/2 -->
|
||||
<inset
|
||||
android:drawable="@drawable/ic_qu_shadowsocks_foreground"
|
||||
android:inset="30.303%"/>
|
||||
</foreground>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Copyright 2017 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
|
||||
in compliance with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software distributed under the License
|
||||
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
|
||||
or implied. See the License for the specific language governing permissions and limitations under
|
||||
the License.
|
||||
-->
|
||||
|
||||
<shape
|
||||
xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="oval">
|
||||
<solid android:color="@color/material_grey_100" />
|
||||
<size android:width="44dp" android:height="44dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24.0"
|
||||
android:viewportHeight="24.0">
|
||||
<path
|
||||
android:fillColor="@color/material_primary_600"
|
||||
android:pathData="M12,12m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0"/>
|
||||
<path
|
||||
android:fillColor="@color/material_primary_600"
|
||||
android:pathData="M9,2L7.17,4L4,4c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2h-3.17L15,2L9,2zM12,17c-2.76,0 -5,-2.24 -5,-5s2.24,-5 5,-5 5,2.24 5,5 -2.24,5 -5,5z"/>
|
||||
</vector>
|
||||
@@ -1,20 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="48"
|
||||
android:viewportHeight="48">
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<path
|
||||
android:fillColor="#f5f5f5"
|
||||
android:pathData="M24,24m-22,0a22,22 0,1 1,44 0a22,22 0,1 1,-44 0Z" />
|
||||
<path
|
||||
android:fillColor="#546e7a"
|
||||
android:pathData="M24,21.8 C25.7673,21.8,27.2,23.2327,27.2,25 C27.2,26.7673,25.7673,28.2,24,28.2
|
||||
C22.2327,28.2,20.8,26.7673,20.8,25 C20.8,23.2327,22.2327,21.8,24,21.8 Z" />
|
||||
<path
|
||||
android:fillColor="#546e7a"
|
||||
android:pathData="M21,15 L19.17,17 L16,17 A2,2,0,0,0,14,19 L14,31 A2,2,0,0,0,16,33 L32,33
|
||||
A2,2,0,0,0,34,31 L34,19 A2,2,0,0,0,32,17 L28.83,17 L27,15 Z M24,30
|
||||
A5,5,0,1,1,29,25 A5,5,0,0,1,24,30 Z" />
|
||||
</vector>
|
||||
<item
|
||||
android:drawable="@drawable/ic_app_shortcut_background"
|
||||
android:left="2dp"
|
||||
android:top="2dp"
|
||||
android:right="2dp"
|
||||
android:bottom="2dp" />
|
||||
|
||||
<item
|
||||
android:drawable="@drawable/ic_image_camera_alt"
|
||||
android:left="12dp"
|
||||
android:top="12dp"
|
||||
android:right="12dp"
|
||||
android:bottom="12dp" />
|
||||
|
||||
</layer-list>
|
||||
@@ -0,0 +1,11 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
|
||||
<path
|
||||
android:name="path"
|
||||
android:fillColor="@color/material_blue_grey_600"
|
||||
android:pathData="M 21.25 2.28 L 17.55 18.55 L 9.26 15.89 L 16.58 7.16 L 6.83 15.37 L 0 12.8 L 21.25 2.28 ZM 9.45 17.56 L 12.09 18.41 L 9.46 22 L 9.45 17.56 Z" />
|
||||
</vector>
|
||||
@@ -1,18 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="48"
|
||||
android:viewportHeight="48">
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<path
|
||||
android:fillColor="#f5f5f5"
|
||||
android:pathData="M24,24m-22,0a22,22 0,1 1,44 0a22,22 0,1 1,-44 0Z" />
|
||||
<path
|
||||
android:fillColor="#546e7a"
|
||||
android:pathData="M34,14.72 L30.52,30.04 L22.72,27.53 L29.61,19.31 L20.43,27.04 L14,24.62
|
||||
L34,14.72 Z" />
|
||||
<path
|
||||
android:fillColor="#546e7a"
|
||||
android:pathData="M22.89,29.1 L25.38,29.9 L22.9,33.28 L22.89,29.1 Z" />
|
||||
</vector>
|
||||
<item
|
||||
android:drawable="@drawable/ic_app_shortcut_background"
|
||||
android:left="2dp"
|
||||
android:top="2dp"
|
||||
android:right="2dp"
|
||||
android:bottom="2dp" />
|
||||
|
||||
<item
|
||||
android:drawable="@drawable/ic_qu_shadowsocks_foreground"
|
||||
android:left="12dp"
|
||||
android:top="12dp"
|
||||
android:right="12dp"
|
||||
android:bottom="12dp" />
|
||||
|
||||
</layer-list>
|
||||
@@ -57,9 +57,8 @@
|
||||
<string name="auto_connect_summary">Enable Shadowsocks on startup</string>
|
||||
<string name="auto_connect_summary_v24">Enable Shadowsocks on startup. Recommended to use always-on VPN
|
||||
instead</string>
|
||||
<string name="direct_boot_aware">Direct Boot Aware</string>
|
||||
<string name="direct_boot_aware_summary">Allow Shadowsocks to start before your device is unlocked (your selected
|
||||
profile information will be less protected)</string>
|
||||
<string name="direct_boot_aware">Allow Toggling in Lock Screen</string>
|
||||
<string name="direct_boot_aware_summary">Your selected profile information will be less protected</string>
|
||||
<string name="tcp_fastopen_summary">Toggling requires ROOT permission</string>
|
||||
<string name="tcp_fastopen_summary_unsupported">Unsupported kernel version: %s < 3.7.1</string>
|
||||
<string name="udp_dns">DNS Forwarding</string>
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
android:title="@string/auto_connect"/>
|
||||
<!-- Direct Boot Aware alone doesn't do anything without auto connect -->
|
||||
<SwitchPreference android:key="directBootAware"
|
||||
android:dependency="isAutoConnect"
|
||||
android:summary="@string/direct_boot_aware_summary"
|
||||
android:title="@string/direct_boot_aware"/>
|
||||
<SwitchPreference android:key="tcp_fastopen"
|
||||
|
||||
@@ -61,7 +61,7 @@ abstract class NativePluginProvider : ContentProvider() {
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?,
|
||||
sortOrder: String?): Cursor {
|
||||
assert(selection == null && selectionArgs == null && sortOrder == null)
|
||||
check(selection == null && selectionArgs == null && sortOrder == null)
|
||||
val result = MatrixCursor(projection)
|
||||
populateFiles(PathProvider(uri, result))
|
||||
return result
|
||||
@@ -79,7 +79,7 @@ abstract class NativePluginProvider : ContentProvider() {
|
||||
|
||||
abstract fun openFile(uri: Uri?): ParcelFileDescriptor
|
||||
override fun openFile(uri: Uri?, mode: String?): ParcelFileDescriptor {
|
||||
assert(mode == "r")
|
||||
check(mode == "r")
|
||||
return openFile(uri)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
<color name="material_blue_grey_100">#CFD8DC</color>
|
||||
<color name="material_blue_grey_300">#90A4AE</color>
|
||||
<color name="material_blue_grey_500">#607D8B</color>
|
||||
<color name="material_blue_grey_600">#546E7A</color>
|
||||
<color name="material_blue_grey_700">#455A64</color>
|
||||
<color name="material_primary_100">@color/material_blue_grey_100</color>
|
||||
<color name="material_primary_300">@color/material_blue_grey_300</color>
|
||||
<color name="material_primary_500">@color/material_blue_grey_500</color>
|
||||
<color name="material_primary_600">@color/material_blue_grey_600</color>
|
||||
<color name="material_primary_700">@color/material_blue_grey_700</color>
|
||||
<color name="material_accent_200">@color/material_green_a700</color>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user