1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
package sh.lajo.buddy
import android.content.Intent
import android.net.VpnService
import android.os.IBinder
import android.util.Log
import java.io.BufferedReader
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.Locale
import java.util.concurrent.atomic.AtomicReference
import java.util.zip.GZIPInputStream
class BuddyVPNService : VpnService() {
private companion object {
private const val TAG = "BuddyVPNService"
private const val BLOCKLIST_URL_PRIMARY =
"https://cdn.jsdelivr.net/gh/lajo-sh/assets/domains.gz"
private const val BLOCKLIST_URL_FALLBACK =
"https://github.com/lajo-sh/assets/raw/refs/heads/main/domains.gz"
private const val CONNECT_TIMEOUT_MS = 10_000
private const val READ_TIMEOUT_MS = 20_000
private const val MAX_DOMAINS = 2_000_000
}
/** In-memory only. Rebuilt on every service start. */
private val blockedDomainsRef = AtomicReference<Set<String>>(emptySet())
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Thread {
val loaded = loadRemoteBlocklist()
if (loaded != null) {
blockedDomainsRef.set(loaded)
Log.i(TAG, "Loaded blocklist: ${loaded.size} domains")
} else {
Log.w(TAG, "Blocklist load failed; continuing with empty list")
}
}.start()
val builder = Builder()
.setSession("BuddyVPN")
.addAddress("10.0.0.2", 32)
.addRoute("10.0.0.1", 32)
.addDnsServer("10.0.0.1")
val vpnInterface = builder.establish() ?: return START_STICKY
Thread {
try {
val input = FileInputStream(vpnInterface.fileDescriptor)
val output = FileOutputStream(vpnInterface.fileDescriptor)
val buffer = ByteArray(32767)
val dnsSocket = java.net.DatagramSocket()
protect(dnsSocket)
while (true) {
val length = input.read(buffer)
if (length > 0) {
try {
handlePacket(buffer, length, output, dnsSocket)
} catch (e: Exception) {
Log.e(TAG, "Packet handling error", e)
}
}
}
} catch (e: Exception) {
Log.e(TAG, "VPN loop error: ${e.message}", e)
}
}.start()
return START_STICKY
}
private fun loadRemoteBlocklist(): Set<String>? {
return try {
fetchAndParseDomains(BLOCKLIST_URL_PRIMARY) ?: fetchAndParseDomains(BLOCKLIST_URL_FALLBACK)
} catch (e: Exception) {
Log.w(TAG, "Unexpected blocklist load error: ${e.message}", e)
null
}
}
private fun fetchAndParseDomains(url: String): Set<String>? {
var conn: HttpURLConnection? = null
return try {
conn = (URL(url).openConnection() as HttpURLConnection).apply {
instanceFollowRedirects = true
connectTimeout = CONNECT_TIMEOUT_MS
readTimeout = READ_TIMEOUT_MS
requestMethod = "GET"
setRequestProperty("Accept-Encoding", "gzip")
setRequestProperty("User-Agent", "BuddyVPNService")
}
val code = conn.responseCode
if (code !in 200..299) {
Log.w(TAG, "Blocklist fetch failed ($code) from $url")
return null
}
conn.inputStream.use { raw ->
GZIPInputStream(raw).use { gz ->
return parseDomainsFromGzipStream(gz)
}
}
} catch (e: Exception) {
Log.w(TAG, "Blocklist fetch/parse failed from $url: ${e.message}")
null
} finally {
conn?.disconnect()
}
}
private fun parseDomainsFromGzipStream(stream: java.io.InputStream): Set<String> {
val result = HashSet<String>(256 * 1024)
BufferedReader(InputStreamReader(stream)).useLines { lines ->
for (line in lines) {
val d = normalizeDomain(line) ?: continue
result.add(d)
if (result.size >= MAX_DOMAINS) break
}
}
return result
}
private fun normalizeDomain(raw: String): String? {
var s = raw.trim()
if (s.isEmpty()) return null
val hash = s.indexOf('#')
if (hash >= 0) s = s.substring(0, hash).trim()
if (s.isEmpty()) return null
val parts = s.split(Regex("\\s+"))
val candidate = parts.lastOrNull()?.trim().orEmpty()
if (candidate.isEmpty()) return null
val cleaned = candidate
.trimEnd('.')
.lowercase(Locale.US)
if (cleaned.length !in 1..253) return null
if (!cleaned.any { it == '.' }) return null
return cleaned
}
private fun isBlocked(domain: String): Boolean {
// Check if blocking is enabled in config
val config = ConfigManager.getConfig(this)
if (!config.blockAdultSites) {
return false
}
val blockedDomains = blockedDomainsRef.get()
if (blockedDomains.isEmpty()) return false
val d = normalizeDomain(domain) ?: return false
if (blockedDomains.contains(d)) return true
var idx = d.indexOf('.')
while (idx >= 0 && idx + 1 < d.length) {
val suffix = d.substring(idx + 1)
if (blockedDomains.contains(suffix)) return true
idx = d.indexOf('.', idx + 1)
}
return false
}
private fun isDns(packet: ByteArray, length: Int): Boolean {
if (length < 28) return false
val protocol = packet.getOrNull(9)?.toInt() ?: return false
if (protocol != 17) return false
val destPort = ((packet[22].toInt() and 0xFF) shl 8) or (packet[23].toInt() and 0xFF)
return destPort == 53
}
private fun extractDomain(packet: ByteArray): String? {
var index = 40
val labels = mutableListOf<String>()
try {
while (index < packet.size) {
val len = packet[index].toInt() and 0xFF
if (len == 0) break
if ((len and 0xC0) == 0xC0) {
return null
}
index++
if (index + len > packet.size) return null
labels.add(String(packet, index, len))
index += len
}
} catch (_: Exception) {
return null
}
return if (labels.isEmpty()) null else labels.joinToString(".")
}
private fun handlePacket(packet: ByteArray, length: Int, output: OutputStream, dnsSocket: java.net.DatagramSocket) {
if (!isDns(packet, length)) {
return
}
val domain = extractDomain(packet)
if (domain == null) {
forwardDns(packet, length, output, dnsSocket)
return
}
if (isBlocked(domain)) {
Log.w(TAG, "blocked: $domain")
sendNxDomain(packet, length, output)
} else {
forwardDns(packet, length, output, dnsSocket)
}
}
private fun forwardDns(packet: ByteArray, length: Int, output: OutputStream, dnsSocket: java.net.DatagramSocket) {
val dnsPayloadLen = length - 28
if (dnsPayloadLen <= 0) return
val buf = ByteArray(dnsPayloadLen)
System.arraycopy(packet, 28, buf, 0, dnsPayloadLen)
val outPacket = java.net.DatagramPacket(buf, dnsPayloadLen,
java.net.InetAddress.getByName("9.9.9.9"), 53) // quad 9
dnsSocket.send(outPacket)
val respBuf = ByteArray(4096)
val inPacket = java.net.DatagramPacket(respBuf, respBuf.size)
try {
dnsSocket.soTimeout = 2000
dnsSocket.receive(inPacket)
val response = checkAndConstructResponse(packet, inPacket.data, inPacket.length)
output.write(response)
} catch (_: Exception) {
}
}
private fun sendNxDomain(packet: ByteArray, length: Int, output: OutputStream) {
val dnsLen = length - 28
val responseDns = ByteArray(dnsLen)
System.arraycopy(packet, 28, responseDns, 0, dnsLen)
responseDns[2] = 0x81.toByte()
responseDns[3] = 0x03.toByte()
val ipPacket = checkAndConstructResponse(packet, responseDns, responseDns.size)
output.write(ipPacket)
}
private fun checkAndConstructResponse(request: ByteArray, dnsPayload: ByteArray, dnsLen: Int): ByteArray {
val totalLen = 28 + dnsLen
val response = ByteArray(totalLen)
response[0] = 0x45 // IPv4
response[1] = 0x00
// Length
response[2] = (totalLen shr 8).toByte()
response[3] = (totalLen and 0xFF).toByte()
// ID (random or 0)
response[4] = 0x00
response[5] = 0x00
// Flags/Frag
response[6] = 0x40 // Don't fragment
response[7] = 0x00
// TTL
response[8] = 64
// Protocol
response[9] = 17 // UDP
// Checksum (calc later)
response[10] = 0; response[11] = 0
System.arraycopy(request, 16, response, 12, 4) // Old Dst is new Src
System.arraycopy(request, 12, response, 16, 4) // Old Src is new Dst
// Calc IP Checksum
fillIpChecksum(response)
// 2. UDP Header (8 bytes)
// Src Port = Request Dst Port
response[20] = request[22]
response[21] = request[23]
// Dst Port = Request Src Port
response[22] = request[20]
response[23] = request[21]
// Length
val udpLen = 8 + dnsLen
response[24] = (udpLen shr 8).toByte()
response[25] = (udpLen and 0xFF).toByte()
// Checksum = 0 (valid for UDP)
response[26] = 0
response[27] = 0
// 3. DNS Payload
System.arraycopy(dnsPayload, 0, response, 28, dnsLen)
return response
}
private fun fillIpChecksum(packet: ByteArray) {
var sum = 0
// Header length 20 bytes = 10 shorts
for (i in 0 until 10) {
// Skip checksum field itself (10, 11)
if (i == 5) continue
val b1 = packet[i * 2].toInt() and 0xFF
val b2 = packet[i * 2 + 1].toInt() and 0xFF
sum += (b1 shl 8) + b2
}
while ((sum shr 16) > 0) {
sum = (sum and 0xFFFF) + (sum shr 16)
}
val checksum = sum.inv() and 0xFFFF
packet[10] = (checksum shr 8).toByte()
packet[11] = (checksum and 0xFF).toByte()
}
override fun onBind(intent: Intent?): IBinder? = super.onBind(intent)
}
|