V1.4.6: 点歌取址失败——修裸 Socket 通道两处缺陷 + 打通 JS 侧日志
现象: 曲库正常后点歌失败「详情=无法生成下载地址」,且远程日志里没有任何线索。
排查(本地复现源站协议):
- 用同一套签名从本机请求 i.php / music/do.php 全部正常,能拿到这首歌的真实地址;
换 App 注入的版本号(VER=2.0/VN=4.1.3.03281430) 也正常 → 源站没问题,是设备侧。
- 根因在 KtvJsBridge.rawRequest() 这条裸 Socket 通道(点歌取址正是走它):
1. 连接阶段没有超时: `Socket(host, port)` 不受 soTimeout 约束,遇路由黑洞按系统
TCP 超时(~2min)干等;7 个源叠加远超 JS_REQUEST_TIMEOUT_MS(180s) →
桥返回空 → 「无法生成下载地址」,而日志里连失败都没有(请求还没失败);
2. HTTPS 分支用 SSLSocketFactory.getDefault(),既不受
HttpsURLConnection.setDefaultSSLSocketFactory 影响,也不受
network_security_config 约束 → 老设备缺 ISRG 新根时握手必失败。
修复:
- rawRequest 连接改为显式 connect(timeout): Socket().connect(InetSocketAddress, t);
HTTPS 改用 TlsCompat.sslSocketFactory()(系统信任 ∪ 内置根证书)。
- TlsCompat 暴露 sslSocketFactory(),并按 API 分级: 裸通道始终用增强工厂,
HttpsURLConnection 默认工厂仅在 API<24 接管。
- 裸通道失败上报 RAW-ERR(原来只在 logcat)。
- 打通 JS 侧日志: wrapHtml 注入 console 桥,把 ktv_api.js 的 _log()/console.log
转发到 android.log → MiliLog("JS ...");点歌失败时可通过
「JS ...」逐步过程 + 「点歌失败 ... 详情=」汇总原因定位。
版本 1.4.5(25) 到 1.4.6(26);签名证书不变。ktv_api.js 未改动,KTV_BRIDGE_API 仍为 8。
This commit is contained in:
@@ -160,7 +160,7 @@ $BT/apksigner verify 目标名.apk
|
|||||||
|
|
||||||
### 版本号
|
### 版本号
|
||||||
|
|
||||||
- `app/build.gradle`:`versionName "1.4.5"` / `versionCode 25`(18~21 被本机临时诊断包占用过)
|
- `app/build.gradle`:`versionName "1.4.6"` / `versionCode 26`(18~21 被本机临时诊断包占用过)
|
||||||
- App 内显示统一用纯版本号(不加 `(versionCode)` 括号)
|
- App 内显示统一用纯版本号(不加 `(versionCode)` 括号)
|
||||||
- ⚠️ **发布构建已开启 NewApi 闸门**(`lint { checkReleaseBuilds true; fatal += ['NewApi'] }`):
|
- ⚠️ **发布构建已开启 NewApi 闸门**(`lint { checkReleaseBuilds true; fatal += ['NewApi'] }`):
|
||||||
任何「调用了高于 `minSdk 21` 且未做版本守卫的 API」都会让 `assembleRelease` 直接失败。
|
任何「调用了高于 `minSdk 21` 且未做版本守卫的 API」都会让 `assembleRelease` 直接失败。
|
||||||
|
|||||||
+2
-2
@@ -11,8 +11,8 @@ android {
|
|||||||
applicationId "com.local.ktv"
|
applicationId "com.local.ktv"
|
||||||
minSdk 21
|
minSdk 21
|
||||||
targetSdk 25
|
targetSdk 25
|
||||||
versionCode 25
|
versionCode 26
|
||||||
versionName "1.4.5"
|
versionName "1.4.6"
|
||||||
ndk {
|
ndk {
|
||||||
// 双 ABI 打包:兼容 64 位(Exynos 1580 等 arm64-v8a)与 32 位设备(极米 Play 超越版
|
// 双 ABI 打包:兼容 64 位(Exynos 1580 等 arm64-v8a)与 32 位设备(极米 Play 超越版
|
||||||
// 的 Amlogic 950X2/S905X2 采用 32 位 Android 用户态,必须包含 armeabi-v7a,否则
|
// 的 Amlogic 950X2/S905X2 采用 32 位 Android 用户态,必须包含 armeabi-v7a,否则
|
||||||
|
|||||||
@@ -330,12 +330,32 @@ class KtvJsBridge(context: Context) {
|
|||||||
|
|
||||||
private fun wrapHtml(script: String): String {
|
private fun wrapHtml(script: String): String {
|
||||||
val escaped = script.replace("</script", "<\\/script", ignoreCase = true)
|
val escaped = script.replace("</script", "<\\/script", ignoreCase = true)
|
||||||
return "<!doctype html><html><head><meta charset=\"utf-8\"></head><body><script>$escaped</script></body></html>"
|
// console.log 桥接:ktv_api.js 的 _log()/_log 细节(Try source / Token FAIL / do.php code=
|
||||||
|
// 等)原本只进 WebView 控制台,远程日志里完全看不到,点歌失败无从定位。
|
||||||
|
// 这里把它转发到 android.log → MiliLog,并保留原始 console 行为。
|
||||||
|
val consoleBridge = """
|
||||||
|
(function(){
|
||||||
|
try {
|
||||||
|
var orig = console.log;
|
||||||
|
console.log = function(){
|
||||||
|
try { android.log(Array.prototype.map.call(arguments, String).join(' ')); } catch(e) {}
|
||||||
|
if (orig) { try { orig.apply(console, arguments); } catch(e) {} }
|
||||||
|
};
|
||||||
|
} catch(e) {}
|
||||||
|
})();
|
||||||
|
""".trimIndent()
|
||||||
|
return "<!doctype html><html><head><meta charset=\"utf-8\"></head><body><script>$consoleBridge</script>" +
|
||||||
|
"<script>$escaped</script></body></html>"
|
||||||
}
|
}
|
||||||
|
|
||||||
inner class NativeBridge {
|
inner class NativeBridge {
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun log(message: String) = Log.d(TAG, message)
|
fun log(message: String) {
|
||||||
|
Log.d(TAG, message)
|
||||||
|
// 把 JS 侧日志接进远程日志:歌曲源解析(token/do.php/多源排序)的失败原因
|
||||||
|
// 以前只走 console.log,现场完全看不到。加上前缀便于检索与过滤。
|
||||||
|
runCatching { MiliLog.info("JS ${message.take(180)}") }
|
||||||
|
}
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun onUrl(requestId: String, url: String) {
|
fun onUrl(requestId: String, url: String) {
|
||||||
@@ -450,10 +470,22 @@ class KtvJsBridge(context: Context) {
|
|||||||
val isHttps = url.startsWith("https://")
|
val isHttps = url.startsWith("https://")
|
||||||
val uri = URL(url).toURI()
|
val uri = URL(url).toURI()
|
||||||
val port = if (uri.port > 0) uri.port else if (isHttps) 443 else 80
|
val port = if (uri.port > 0) uri.port else if (isHttps) 443 else 80
|
||||||
|
val connectTimeout = timeoutMs.coerceIn(1_000, 30_000)
|
||||||
socket = if (isHttps) {
|
socket = if (isHttps) {
|
||||||
(SSLSocketFactory.getDefault().createSocket(uri.host, port) as SSLSocket).apply { startHandshake() }
|
// 用 TlsCompat 的工厂(系统信任 ∪ 内置根证书):裸 socket 走的是
|
||||||
|
// SSLSocketFactory.getDefault(),不受 HttpsURLConnection 的默认工厂影响,
|
||||||
|
// network_security_config 也管不到它 —— 老设备上会因缺 ISRG 新根握手失败。
|
||||||
|
(TlsCompat.sslSocketFactory().createSocket() as SSLSocket).apply {
|
||||||
|
connect(java.net.InetSocketAddress(uri.host, port), connectTimeout)
|
||||||
|
startHandshake()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Socket(uri.host, port)
|
// ⚠️ 必须显式给连接超时:原写法 `Socket(host, port)` 的连接阶段**不受**
|
||||||
|
// soTimeout 约束,遇到路由黑洞会按系统 TCP 超时(约 2 分钟)干等,
|
||||||
|
// 多个源叠加会把 JS 的 3 分钟预算耗光,表现为「无法生成下载地址」。
|
||||||
|
Socket().apply {
|
||||||
|
connect(java.net.InetSocketAddress(uri.host, port), connectTimeout)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
socket.soTimeout = timeoutMs.coerceIn(1_000, 30_000)
|
socket.soTimeout = timeoutMs.coerceIn(1_000, 30_000)
|
||||||
val path = if (uri.rawQuery != null) "${uri.rawPath}?${uri.rawQuery}" else uri.rawPath
|
val path = if (uri.rawQuery != null) "${uri.rawPath}?${uri.rawQuery}" else uri.rawPath
|
||||||
@@ -494,6 +526,11 @@ class KtvJsBridge(context: Context) {
|
|||||||
JSONObject().put("status", status).put("body", responseBody).toString()
|
JSONObject().put("status", status).put("body", responseBody).toString()
|
||||||
} catch (error: Throwable) {
|
} catch (error: Throwable) {
|
||||||
Log.w(TAG, "raw request failed: ${error.message}")
|
Log.w(TAG, "raw request failed: ${error.message}")
|
||||||
|
// 裸 Socket 失败原因以前只在 logcat:点歌失败时远程日志里什么都看不到。
|
||||||
|
MiliLog.warn(
|
||||||
|
"RAW-ERR $method ${runCatching { java.net.URI(url).host }.getOrNull() ?: url} " +
|
||||||
|
"${error.javaClass.simpleName}: ${error.message}",
|
||||||
|
)
|
||||||
JSONObject().put("status", 0).put("body", "").put("error", error.message.orEmpty()).toString()
|
JSONObject().put("status", 0).put("body", "").put("error", error.message.orEmpty()).toString()
|
||||||
} finally {
|
} finally {
|
||||||
try { socket?.close() } catch (ignored: Exception) {}
|
try { socket?.close() } catch (ignored: Exception) {}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import java.util.concurrent.ConcurrentHashMap
|
|||||||
import javax.net.ssl.HttpsURLConnection
|
import javax.net.ssl.HttpsURLConnection
|
||||||
import javax.net.ssl.SSLContext
|
import javax.net.ssl.SSLContext
|
||||||
import javax.net.ssl.SSLException
|
import javax.net.ssl.SSLException
|
||||||
|
import javax.net.ssl.SSLSocketFactory
|
||||||
import javax.net.ssl.TrustManager
|
import javax.net.ssl.TrustManager
|
||||||
import javax.net.ssl.TrustManagerFactory
|
import javax.net.ssl.TrustManagerFactory
|
||||||
import javax.net.ssl.X509TrustManager
|
import javax.net.ssl.X509TrustManager
|
||||||
@@ -47,6 +48,20 @@ object TlsCompat {
|
|||||||
|
|
||||||
@Volatile private var installed = false
|
@Volatile private var installed = false
|
||||||
|
|
||||||
|
/** 「系统信任 ∪ 内置根证书」的 SSLSocketFactory,供裸 Socket 通道复用。 */
|
||||||
|
@Volatile private var patchedFactory: SSLSocketFactory? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 给**裸 Socket** 通道用的 SSLSocketFactory。
|
||||||
|
*
|
||||||
|
* ⚠️ 必须单独提供:`HttpsURLConnection.setDefaultSSLSocketFactory` **不会**影响
|
||||||
|
* `SSLSocketFactory.getDefault()`,而 `KtvJsBridge.rawRequest()` 的 HTTPS 分支正是用后者
|
||||||
|
* (`network_security_config` 也只作用于 HttpsURLConnection / WebView,管不到裸 socket)。
|
||||||
|
* 未初始化时回退系统默认。
|
||||||
|
*/
|
||||||
|
fun sslSocketFactory(): SSLSocketFactory =
|
||||||
|
patchedFactory ?: (SSLSocketFactory.getDefault() as SSLSocketFactory)
|
||||||
|
|
||||||
/** 主机 → 是否已被增强信任库校验通过(只缓存肯定结果)。 */
|
/** 主机 → 是否已被增强信任库校验通过(只缓存肯定结果)。 */
|
||||||
private val trustedHosts = ConcurrentHashMap<String, Boolean>()
|
private val trustedHosts = ConcurrentHashMap<String, Boolean>()
|
||||||
|
|
||||||
@@ -63,15 +78,18 @@ object TlsCompat {
|
|||||||
Log.w(TAG, "no bundled certs loaded; keep system trust only")
|
Log.w(TAG, "no bundled certs loaded; keep system trust only")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (android.os.Build.VERSION.SDK_INT >= 24) {
|
|
||||||
// 新系统由 network_security_config 负责,无需接管(避免多此一举)。
|
|
||||||
Log.i(TAG, "API>=24, network-security-config handles bundled roots")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
val composite = CompositeTrustManager(system, bundled)
|
val composite = CompositeTrustManager(system, bundled)
|
||||||
val sslContext = SSLContext.getInstance("TLS")
|
val sslContext = SSLContext.getInstance("TLS")
|
||||||
sslContext.init(null, arrayOf<TrustManager>(composite), null)
|
sslContext.init(null, arrayOf<TrustManager>(composite), null)
|
||||||
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory)
|
val factory = sslContext.socketFactory as SSLSocketFactory
|
||||||
|
// 裸 Socket 通道始终使用它(系统信任 + 内置根证书,二者取并集)。
|
||||||
|
patchedFactory = factory
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= 24) {
|
||||||
|
// 新系统由 network_security_config 负责 HttpsURLConnection,无需接管默认工厂。
|
||||||
|
Log.i(TAG, "API>=24, keep system default for HttpsURLConnection")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
HttpsURLConnection.setDefaultSSLSocketFactory(factory)
|
||||||
Log.i(
|
Log.i(
|
||||||
TAG,
|
TAG,
|
||||||
"legacy TLS trust installed: system(${system?.acceptedIssuers?.size ?: 0} CAs) " +
|
"legacy TLS trust installed: system(${system?.acceptedIssuers?.size ?: 0} CAs) " +
|
||||||
|
|||||||
Reference in New Issue
Block a user