blob: 45f901bdb498cd29f61bde56455b9f6927e54b12 (
plain)
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
|
package org.pacien.tincapp.service
import android.app.Service
import android.content.Intent
import android.net.VpnService
import android.os.ParcelFileDescriptor
import org.pacien.tincapp.BuildConfig
import org.pacien.tincapp.commands.Tinc
import org.pacien.tincapp.commands.Tincd
import org.pacien.tincapp.context.App
import org.pacien.tincapp.context.AppPaths
import org.pacien.tincapp.utils.applyIgnoringException
import java.io.IOException
/**
* @author pacien
*/
class TincVpnService : VpnService() {
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
when (intent.getSerializableExtra(INTENT_EXTRA_ACTION)) {
Action.START -> startVpn(intent.getStringExtra(INTENT_EXTRA_NET_NAME)!!)
Action.STOP -> onDestroy()
}
return Service.START_STICKY
}
override fun onDestroy() {
connected = false
try {
if (netName != null) Tinc.stop(netName!!)
fd?.close()
} catch (e: IOException) {
e.printStackTrace()
} finally {
netName = null
interfaceCfg = null
fd = null
super.onDestroy()
}
}
private fun startVpn(netName: String) {
if (isConnected()) onDestroy()
TincVpnService.netName = netName
TincVpnService.interfaceCfg = VpnInterfaceConfiguration(AppPaths.netConfFile(netName))
val net = Builder().setSession(netName).apply(TincVpnService.interfaceCfg!!)
applyIgnoringException(net::addDisallowedApplication, BuildConfig.APPLICATION_ID)
try {
fd = net.establish()
Tincd.start(netName, fd!!.fd)
} catch (e: IOException) {
e.printStackTrace()
}
connected = true
}
companion object {
private val INTENT_EXTRA_ACTION = "action"
private val INTENT_EXTRA_NET_NAME = "netName"
private enum class Action { START, STOP }
private var connected: Boolean = false
private var netName: String? = null
private var interfaceCfg: VpnInterfaceConfiguration? = null
private var fd: ParcelFileDescriptor? = null
fun startVpn(netName: String) {
App.getContext().startService(Intent(App.getContext(), TincVpnService::class.java)
.putExtra(INTENT_EXTRA_ACTION, Action.START)
.putExtra(TincVpnService.INTENT_EXTRA_NET_NAME, netName))
}
fun stopVpn() {
App.getContext().startService(Intent(App.getContext(), TincVpnService::class.java)
.putExtra(INTENT_EXTRA_ACTION, Action.STOP))
}
fun getCurrentNetName() = netName
fun getCurrentInterfaceCfg() = interfaceCfg
fun isConnected() = connected
}
}
|