Skip to content

Commit

Permalink
Add support for "optimize tcp buffers" option per profile.
Browse files Browse the repository at this point in the history
 - It tunes down the local sslocal listener socket buffers which is the right thing to do in 99.999% of cases of mobile app.
 - It additionally also tunes down the remote socket buffers of sslocal when a plugin is used. This is needed to ensure there's no bufferbloat between sslocal and the plugin itself.
 - Ideally the plugin on its side should also choke its local listening socket buffers and leave only its remote side socket buffers unrestricted.
  • Loading branch information
notsure2 committed Dec 11, 2023
1 parent 5a10078 commit 87458e3
Show file tree
Hide file tree
Showing 20 changed files with 69 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
"formatVersion": 1,
"database": {
"version": 29,
"identityHash": "5b5c55a1277c63e14416316f9198ed43",
"identityHash": "edf35c5851b4cb55bb5dbbf278199450",
"entities": [
{
"tableName": "Profile",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `host` TEXT NOT NULL, `remotePort` INTEGER NOT NULL, `password` TEXT NOT NULL, `method` TEXT NOT NULL, `route` TEXT NOT NULL, `remoteDns` TEXT NOT NULL, `proxyApps` INTEGER NOT NULL, `bypass` INTEGER NOT NULL, `udpdns` INTEGER NOT NULL, `ipv6` INTEGER NOT NULL, `metered` INTEGER NOT NULL, `individual` TEXT NOT NULL, `plugin` TEXT, `udpFallback` INTEGER, `subscription` INTEGER NOT NULL, `tx` INTEGER NOT NULL, `rx` INTEGER NOT NULL, `userOrder` INTEGER NOT NULL)",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `host` TEXT NOT NULL, `remotePort` INTEGER NOT NULL, `password` TEXT NOT NULL, `method` TEXT NOT NULL, `route` TEXT NOT NULL, `remoteDns` TEXT NOT NULL, `proxyApps` INTEGER NOT NULL, `bypass` INTEGER NOT NULL, `udpdns` INTEGER NOT NULL, `ipv6` INTEGER NOT NULL, `metered` INTEGER NOT NULL, `individual` TEXT NOT NULL, `plugin` TEXT, `udpFallback` INTEGER, `optimizeBuffers` INTEGER NOT NULL, `subscription` INTEGER NOT NULL, `tx` INTEGER NOT NULL, `rx` INTEGER NOT NULL, `userOrder` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
Expand Down Expand Up @@ -104,6 +104,12 @@
"affinity": "INTEGER",
"notNull": false
},
{
"fieldPath": "optimizeBuffers",
"columnName": "optimizeBuffers",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "subscription",
"columnName": "subscription",
Expand All @@ -130,10 +136,10 @@
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
],
"autoGenerate": true
]
},
"indices": [],
"foreignKeys": []
Expand Down Expand Up @@ -162,10 +168,10 @@
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"key"
],
"autoGenerate": false
]
},
"indices": [],
"foreignKeys": []
Expand All @@ -174,7 +180,7 @@
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '5b5c55a1277c63e14416316f9198ed43')"
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'edf35c5851b4cb55bb5dbbf278199450')"
]
}
}
16 changes: 14 additions & 2 deletions core/src/main/java/com/github/shadowsocks/bg/ProxyInstance.kt
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,22 @@ class ProxyInstance(val profile: Profile, private val route: String = profile.ro
val cmd = arrayListOf(
File((service as Context).applicationInfo.nativeLibraryDir, Executable.SS_LOCAL).absolutePath,
"--stat-path", stat.absolutePath,
"-c", configFile.absolutePath,
"-c", configFile.absolutePath
)

if (service.isVpnService) cmd += "--vpn"
if (profile.optimizeBuffers) {
cmd += "--inbound-send-buffer-size 16384"
cmd += "--inbound-recv-buffer-size 16384"

if (profile.plugin?.isNotBlank() == true) {
cmd += "--outbound-send-buffer-size 16384"
cmd += "--outbound-recv-buffer-size 16384"
}
}

if (service.isVpnService) {
cmd += "--vpn"
}

if (route != Acl.ALL) {
cmd += "--acl"
Expand Down
3 changes: 3 additions & 0 deletions core/src/main/java/com/github/shadowsocks/database/Profile.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ data class Profile(
var individual: String = "",
var plugin: String? = null,
var udpFallback: Long? = null,
var optimizeBuffers: Boolean = true,

// managed fields
var subscription: SubscriptionStatus = SubscriptionStatus.UserConfigured,
Expand Down Expand Up @@ -355,6 +356,7 @@ data class Profile(
DataStore.individual = individual
DataStore.plugin = plugin ?: ""
DataStore.udpFallback = udpFallback
DataStore.optimizeBuffers = optimizeBuffers
DataStore.privateStore.remove(Key.dirty)
}

Expand All @@ -378,5 +380,6 @@ data class Profile(
individual = DataStore.individual
plugin = DataStore.plugin
udpFallback = DataStore.udpFallback
optimizeBuffers = DataStore.optimizeBuffers
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ object DataStore : OnPreferenceDataStoreChangeListener {
var udpFallback: Long?
get() = privateStore.getLong(Key.udpFallback)
set(value) = privateStore.putLong(Key.udpFallback, value)
var optimizeBuffers: Boolean
get() = privateStore.getBoolean(Key.optimizeBuffers) ?: true
set(value) = privateStore.putBoolean(Key.optimizeBuffers, value)
var dirty: Boolean
get() = privateStore.getBoolean(Key.dirty) ?: false
set(value) = privateStore.putBoolean(Key.dirty, value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ object Key {
const val plugin = "plugin"
const val pluginConfigure = "plugin.configure"
const val udpFallback = "udpFallback"
const val optimizeBuffers = "optimizeBuffers";

const val dirty = "profileDirty"

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@
<string name="remote_port">"المنفذ"</string>
<string name="sitekey">"كلمة المرور"</string>
<string name="enc_method">"طريقة التشفير"</string>
<string name="optimize_buffers">حسِن مخازن الذاكرة ل TCP</string>
<string name="optimize_buffers_summary">يعالج مشكلة نفاذ الوقت اثناء الرفع نتيجة تضخم مخازن الذاكرة</string>
</resources>
2 changes: 2 additions & 0 deletions core/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Empfangen: \t%4$s\t↓\t%2$s"</string>
<string name="enc_method">"Verschlüsselungsmethode"</string>

<!-- feature category -->
<string name="optimize_buffers">TCP-Puffer optimieren</string>
<string name="ipv6">"IPv6-Route"</string>
<string name="ipv6_summary">"Leite IPv6-Traffic zu Remote um"</string>
<string name="route_entry_gfwlist">"GFW-Liste"</string>
Expand All @@ -49,6 +50,7 @@ Empfangen: \t%4$s\t↓\t%2$s"</string>
<string name="bypass_apps_summary">"Aktiviere um ausgewählte Apps zu umgehen"</string>
<string name="auto_connect">"Automatisch verbinden"</string>
<string name="auto_connect_summary">"Starte Shadowsocks bei Systemstart/nach App-Update automatisch, falls es zuvor aktiv war"</string>
<string name="optimize_buffers_summary">Upload-Zeitüberschreitung (Bufferbloat) beheben</string>
<string name="tcp_fastopen_summary">"Umschalten benötigt eventuell ROOT-Zugriff"</string>
<string name="tcp_fastopen_summary_unsupported">"Nicht unterstützte Kernel-Version: %s &lt; 3.7.1"</string>
<string name="udp_dns">"Sende DNS über UDP"</string>
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-es/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Recibido: \t%4$s\t↓\t%2$s"</string>
<string name="enc_method">"Método de Cifrado"</string>

<!-- feature category -->
<string name="optimize_buffers">Optimizar buffers TCP</string>
<string name="ipv6">"Ruta IPv6"</string>
<string name="ipv6_summary">"Redireccionar tráfico IPv6 a ruta"</string>
<string name="route_list">"Ruta"</string>
Expand All @@ -54,6 +55,7 @@ Recibido: \t%4$s\t↓\t%2$s"</string>

<!-- Fuzzy -->
<string name="auto_connect_summary">"Activar Shadowsocks al iniciar"</string>
<string name="optimize_buffers_summary">Corregir el error de tiempo de espera de carga debido a bufferbloat</string>
<string name="tcp_fastopen_summary_unsupported">"Versión del Núcleo sin soporte: %s &lt; 3.7.1"</string>
<string name="udp_dns">"Enviar DNS sobre UDP"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-fa/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<string name="enc_method">"روش رمزگذاری"</string>

<!-- feature category -->
<string name="optimize_buffers">بهینه‌سازی بافرهای TCP</string>
<string name="ipv6">"مسیر IPv6"</string>
<string name="ipv6_summary">"ترافیک IPv6 را به سرور هدایت کن"</string>
<string name="route_list">"مسیر"</string>
Expand All @@ -52,6 +53,7 @@
<string name="bypass_apps_summary">"این گزینه را فعال کنید تا اپلیکیشن‌های انتخاب شده از VPN استفاده نکنند"</string>
<string name="auto_connect">"وصل‌شدن اتوماتیک"</string>
<string name="auto_connect_summary">"فعال‌شدن شدوساکس لحظه روشن‌شدن گوشی بروزرسانی شود اگر از قبل درحال اجرا بوده است"</string>
<string name="optimize_buffers_summary">رفع مشکل تایم اوت آپلود به دلیل بافرهای بزرگ</string>
<string name="tcp_fastopen_summary">"تغییر وضعیت ممکن است به مجوز ROOT نیاز داشته باشد"</string>
<string name="tcp_fastopen_summary_unsupported">"نسخه هسته پشتیبانی نشده: %s &lt;3.7.1"</string>
<string name="udp_dns">"ارسال DNS از طریق UDP"</string>
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-fr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Reçu : \t\t\t%4$s\t↓\t%2$s"</string>
<string name="enc_method">"Méthode d'Encryption"</string>

<!-- feature category -->
<string name="optimize_buffers">Optimiser les tampons TCP</string>
<string name="ipv6">"Route IPv6"</string>
<string name="ipv6_summary">"Rediriger le trafic IPv6 vers le serveur distant"</string>
<string name="route_list">"Route"</string>
Expand All @@ -57,6 +58,7 @@ Reçu : \t\t\t%4$s\t↓\t%2$s"</string>
<string name="auto_connect_summary">"Activer Shadowsocks au démarrage"</string>

<!-- Fuzzy -->
<string name="optimize_buffers_summary">Résoudre le problème de délai d\'envoi lié au bufferbloat</string>
<string name="tcp_fastopen_summary">"Activer nécessite la permission ROOT"</string>
<string name="tcp_fastopen_summary_unsupported">"Version du noyau non supportée : %s &lt;3.7.1"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-ja/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<string name="enc_method">"暗号化方式"</string>

<!-- feature category -->
<string name="optimize_buffers">TCP バッファを最適化</string>
<string name="ipv6">"IPv6 プロキシ"</string>
<string name="ipv6_summary">"リモートサーバーに IPv6 パケットを転送"</string>
<string name="route_list">"プロキシ方式"</string>
Expand All @@ -59,6 +60,7 @@
<string name="auto_connect_summary">"システム起動時にバックグラウンドで本サービスを開始"</string>

<!-- Fuzzy -->
<string name="optimize_buffers_summary">バッファブロートによるアップロード遅延を解消する</string>
<string name="tcp_fastopen_summary">"使用するには ROOT 権限が必要"</string>
<string name="tcp_fastopen_summary_unsupported">"ご利用のカーネルバージョンはサポートしておりません:%s &lt; 3.7.1"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-ko/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
<string name="enc_method">"암호화 방법"</string>

<!-- feature category -->
<string name="optimize_buffers">TCP 버퍼 최적화</string>
<string name="ipv6">"IPv6 라우팅"</string>
<string name="ipv6_summary">"IPv6 트래픽도 원격으로 리다이렉트 합니다"</string>
<string name="route_list">"라우팅 대상"</string>
Expand All @@ -58,6 +59,7 @@
<string name="auto_connect_summary">"장치가 켜질 때 Shadowsocks를 자동으로 활성화합니다"</string>

<!-- Fuzzy -->
<string name="optimize_buffers_summary">업로드 버퍼 크기 초과로 인한 시간 초과 해결</string>
<string name="tcp_fastopen_summary">"루트 권한이 필요합니다"</string>
<string name="tcp_fastopen_summary_unsupported">"지원하지 않는 버전의 커널입니다: %s &lt; 3.7.1"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-ru/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
<string name="enc_method">"Метод шифрования"</string>

<!-- feature category -->
<string name="optimize_buffers">Оптимизировать буферы TCP</string>
<string name="ipv6">"Маршрутизация IPv6"</string>
<string name="ipv6_summary">"Перенаправлять трафик IPv6 на удалённый сервер"</string>
<string name="route_list">"Маршрут"</string>
Expand All @@ -52,6 +53,7 @@
<string name="bypass_apps_summary">"Включите эту функцию для работы выбранных приложений в обход прокси"</string>
<string name="auto_connect">"Автоподключение"</string>
<string name="auto_connect_summary">"Запускать Shadowsocks при включении/после обновления приложения, если оно было запущено до этого"</string>
<string name="optimize_buffers_summary">Устранить таймаут загрузки из-за переполнения буфера</string>
<string name="tcp_fastopen_summary">"Переключение может запрашивать Root (права суперпользователя)"</string>
<string name="tcp_fastopen_summary_unsupported">"Неподдерживаемая версия ядра: %s &lt; 3.7.1"</string>
<string name="udp_dns">"Посылать DNS-запросы через UDP"</string>
Expand Down
3 changes: 3 additions & 0 deletions core/src/main/res/values-tr/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
<string name="remote_port">"Uzaktan Port"</string>
<string name="sitekey">"Şifre"</string>
<string name="enc_method">"Şifreleme Methodu"</string>
<string name="optimize_buffers">TCP Arabelleklerini Optimize Edin</string>
<string name="ipv6_summary">"IPv6 trafiğini remote'a yönlendir"</string>
<string name="route_list">"Rota"</string>
<string name="route_entry_gfwlist">"GFW Listesi"</string>
Expand All @@ -53,6 +54,8 @@
<string name="auto_connect_summary">"Shadowsocks'ı cihazı başlatırken aç"</string>

<!-- Fuzzy -->
<string name="optimize_buffers_summary">Aşırı boyutlu arabelleklerden kaynaklanan yükleme zaman aşımını düzeltin.
</string>
<string name="tcp_fastopen_summary">"Açıp kapamak için ROOT yetkisi gerekiyor"</string>
<string name="tcp_fastopen_summary_unsupported">"Desteklenmeyen kernel sürümü: %s &lt; 3.7.1"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-uk/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
<string name="profile_default">"Використовувати поточний профіль"</string>

<!-- status -->
<string name="optimize_buffers_summary">Виправити таймаут завантаження через завеликі буфери</string>
<string name="sent">"Надіслано:"</string>
<string name="received">"Отримано:"</string>

Expand All @@ -92,6 +93,7 @@
<string name="custom_rules">"Власні правила"</string>
<string name="action_add_rule">"Додати правило…"</string>
<string name="edit_rule">"Редагувати правило"</string>
<string name="optimize_buffers">Оптимізувати буфери TCP</string>
<string name="route_entry_all">"Всі"</string>
<string name="route_entry_bypass_lan">"Оминати локальні мережі"</string>
<string name="route_entry_bypass_chn">"Оминати Китай"</string>
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-zh-rCN/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
<string name="enc_method">"加密方式"</string>

<!-- feature category -->
<string name="optimize_buffers">优化 TCP 缓冲区</string>
<string name="ipv6">"IPv6 路由"</string>
<string name="ipv6_summary">"转发 IPv6 流量到远程服务器"</string>
<string name="route_list">"路由"</string>
Expand All @@ -51,6 +52,7 @@
<string name="bypass_apps_summary">"绕过选择的应用"</string>
<string name="auto_connect">"自动连接"</string>
<string name="auto_connect_summary">"系统启动或应用更新后自动恢复运行"</string>
<string name="optimize_buffers_summary">解决因缓冲区过大导致的上传超时问题</string>
<string name="tcp_fastopen_summary">"切换可能需要 ROOT 权限"</string>
<string name="tcp_fastopen_summary_unsupported">"不支持的内核版本: %s &lt; 3.7.1"</string>
<string name="udp_dns">"使用 UDP DNS"</string>
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values-zh-rTW/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<string name="enc_method">"加密方法"</string>

<!-- feature category -->
<string name="optimize_buffers">最佳化 TCP 緩衝區</string>
<string name="ipv6">"IPv6 路由"</string>
<string name="ipv6_summary">"向遠端重新導向 IPv6 流量"</string>
<string name="route_list">"路由"</string>
Expand All @@ -58,6 +59,7 @@
<string name="auto_connect_summary">"在裝置啟動時啟用 Shadowsocks"</string>

<!-- Fuzzy -->
<string name="optimize_buffers_summary">修正因緩衝區過大導致上傳逾時的問題</string>
<string name="tcp_fastopen_summary">"切換需要 ROOT 權限"</string>
<string name="tcp_fastopen_summary_unsupported">"不支援的核心版本:%s &lt; 3.7.1"</string>

Expand Down
2 changes: 2 additions & 0 deletions core/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
<string name="remote_port">Remote Port</string>
<string name="sitekey">Password</string>
<string name="enc_method">Encrypt Method</string>
<string name="optimize_buffers">Optimize TCP Buffers</string>
<string name="optimize_buffers_summary">Fix upload timeout (bufferbloat)</string>

<!-- feature category -->
<string name="ipv6">IPv6 Route</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class ProfileConfigFragment : PreferenceFragmentCompat(),
private lateinit var pluginConfiguration: PluginConfiguration
private lateinit var receiver: BroadcastReceiver
private lateinit var udpFallback: Preference
private lateinit var optimizeBuffers: SwitchPreference

private fun makeDirt() {
DataStore.dirty = true
Expand Down Expand Up @@ -115,6 +116,8 @@ class ProfileConfigFragment : PreferenceFragmentCompat(),
pluginConfiguration = PluginConfiguration(DataStore.plugin)
initPlugins()
udpFallback = findPreference(Key.udpFallback)!!
optimizeBuffers = findPreference(Key.optimizeBuffers)!!
optimizeBuffers.isChecked = DataStore.optimizeBuffers
DataStore.privateStore.registerChangeListener(this)

val profile = ProfileManager.getProfile(profileId) ?: Profile()
Expand Down
7 changes: 5 additions & 2 deletions mobile/src/main/res/xml/pref_profile.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@
app:key="remoteDns"
app:icon="@drawable/ic_action_dns"
app:title="@string/remote_dns"
app:useSimpleSummaryProvider="true"/>

app:useSimpleSummaryProvider="true" />
<SwitchPreference
app:key="optimizeBuffers"
app:title="@string/optimize_buffers"
app:summary="@string/optimize_buffers_summary" />
</PreferenceCategory>

<PreferenceCategory
Expand Down

0 comments on commit 87458e3

Please sign in to comment.