Commit b8d7ade4 authored by Mygod's avatar Mygod

Rewrite network ACLs

* A cleaner format;
* Provides better behavior when importing a non-compatible ACL;
* Supports importing URL from a imported file with up to 10 layers.
parent d7183fe1
...@@ -224,5 +224,6 @@ ...@@ -224,5 +224,6 @@
<string-array name="acl_rule_templates"> <string-array name="acl_rule_templates">
<item>@string/acl_rule_templates_generic</item> <item>@string/acl_rule_templates_generic</item>
<item>@string/acl_rule_templates_domain</item> <item>@string/acl_rule_templates_domain</item>
<item>URL</item>
</string-array> </string-array>
</resources> </resources>
...@@ -132,7 +132,7 @@ ...@@ -132,7 +132,7 @@
<string name="custom_rules">Custom rules</string> <string name="custom_rules">Custom rules</string>
<string name="action_selection">Selection…</string> <string name="action_selection">Selection…</string>
<string name="action_add_rule">Add rule(s)…</string> <string name="action_add_rule">Add rule(s)…</string>
<string name="acl_rule_templates_generic">URL, Subnet or Hostname PCRE pattern</string> <string name="acl_rule_templates_generic">Subnet or Hostname PCRE pattern</string>
<string name="acl_rule_templates_domain">Domain name and all its subdomain names</string> <string name="acl_rule_templates_domain">Domain name and all its subdomain names</string>
<string name="edit_rule">Edit rule</string> <string name="edit_rule">Edit rule</string>
......
...@@ -150,8 +150,7 @@ trait BaseService extends Service { ...@@ -150,8 +150,7 @@ trait BaseService extends Service {
profile.method = proxy(3).trim profile.method = proxy(3).trim
} }
if (profile.route == Acl.CUSTOM_RULES) // rationalize custom rules if (profile.route == Acl.CUSTOM_RULES) Acl.save(Acl.CUSTOM_RULES_FLATTENED, Acl.customRules.flatten(10))
Acl.save(Acl.CUSTOM_RULES, new Acl().fromId(Acl.CUSTOM_RULES), true)
plugin = new PluginConfiguration(profile.plugin).selectedOptions plugin = new PluginConfiguration(profile.plugin).selectedOptions
pluginPath = PluginManager.init(plugin) pluginPath = PluginManager.init(plugin)
......
...@@ -63,7 +63,10 @@ class ShadowsocksNatService extends BaseService { ...@@ -63,7 +63,10 @@ class ShadowsocksNatService extends BaseService {
if (profile.route != Acl.ALL) { if (profile.route != Acl.ALL) {
cmd += "--acl" cmd += "--acl"
cmd += Acl.getFile(profile.route).getAbsolutePath cmd += Acl.getFile(profile.route match {
case Acl.CUSTOM_RULES => Acl.CUSTOM_RULES_FLATTENED
case route => route
}).getAbsolutePath
} }
sslocalProcess = new GuardedProcess(cmd: _*).start() sslocalProcess = new GuardedProcess(cmd: _*).start()
......
...@@ -161,7 +161,10 @@ class ShadowsocksVpnService extends VpnService with BaseService { ...@@ -161,7 +161,10 @@ class ShadowsocksVpnService extends VpnService with BaseService {
if (profile.route != Acl.ALL) { if (profile.route != Acl.ALL) {
cmd += "--acl" cmd += "--acl"
cmd += Acl.getFile(profile.route).getAbsolutePath cmd += Acl.getFile(profile.route match {
case Acl.CUSTOM_RULES => Acl.CUSTOM_RULES_FLATTENED
case route => route
}).getAbsolutePath
} }
if (TcpFastOpen.sendEnabled) cmd += "--fast-open" if (TcpFastOpen.sendEnabled) cmd += "--fast-open"
......
package com.github.shadowsocks.acl package com.github.shadowsocks.acl
import java.io.{File, FileNotFoundException, IOException} import java.io.{File, FileNotFoundException}
import java.net.URL
import android.util.Log
import com.github.shadowsocks.ShadowsocksApplication.app import com.github.shadowsocks.ShadowsocksApplication.app
import com.github.shadowsocks.utils.IOUtils import com.github.shadowsocks.utils.IOUtils
import com.j256.ormlite.field.DatabaseField import com.j256.ormlite.field.DatabaseField
...@@ -17,21 +19,44 @@ import scala.io.Source ...@@ -17,21 +19,44 @@ import scala.io.Source
* @author Mygod * @author Mygod
*/ */
class Acl { class Acl {
import Acl._
@DatabaseField(generatedId = true) @DatabaseField(generatedId = true)
var id: Int = _ var id: Int = _
val bypassHostnames = new mutable.SortedList[String]()
val hostnames = new mutable.SortedList[String]() val proxyHostnames = new mutable.SortedList[String]()
val subnets = new mutable.SortedList[Subnet]() val subnets = new mutable.SortedList[Subnet]()
val urls = new mutable.SortedList[String]() val urls = new mutable.SortedList[URL]()(urlOrdering)
@DatabaseField @DatabaseField
var bypass: Boolean = _ var bypass: Boolean = _
def isUrl(url: String): Boolean = url.startsWith("http://") || url.startsWith("https://") def getBypassHostnamesString: String = bypassHostnames.mkString("\n")
def getProxyHostnamesString: String = proxyHostnames.mkString("\n")
def getSubnetsString: String = subnets.mkString("\n")
def getUrlsString: String = urls.mkString("\n")
def setBypassHostnamesString(value: String) {
bypassHostnames.clear()
bypassHostnames ++= value.split("\n")
}
def setProxyHostnamesString(value: String) {
proxyHostnames.clear()
proxyHostnames ++= value.split("\n")
}
def setSubnetsString(value: String) {
subnets.clear()
subnets ++= value.split("\n").map(Subnet.fromString)
}
def setUrlsString(value: String) {
urls.clear()
urls ++= value.split("\n").map(new URL(_))
}
def fromAcl(other: Acl): Acl = { def fromAcl(other: Acl): Acl = {
hostnames.clear() bypassHostnames.clear()
hostnames ++= other.hostnames bypassHostnames ++= other.bypassHostnames
proxyHostnames.clear()
proxyHostnames ++= other.proxyHostnames
subnets.clear() subnets.clear()
subnets ++= other.subnets subnets ++= other.subnets
urls.clear() urls.clear()
...@@ -39,78 +64,83 @@ class Acl { ...@@ -39,78 +64,83 @@ class Acl {
bypass = other.bypass bypass = other.bypass
this this
} }
def fromSource(value: Source, defaultBypass: Boolean = false): Acl = {
def fromSource(value: Source, defaultBypass: Boolean = true): Acl = { bypassHostnames.clear()
subnets.clear() proxyHostnames.clear()
this.subnets.clear()
urls.clear() urls.clear()
bypass = defaultBypass bypass = defaultBypass
var in_urls = false lazy val bypassSubnets = new mutable.SortedList[Subnet]()
for (line <- value.getLines()) (line.trim.indexOf('#') match { lazy val proxySubnets = new mutable.SortedList[Subnet]()
case 0 => { var hostnames: mutable.SortedList[String] = if (defaultBypass) proxyHostnames else bypassHostnames
line.indexOf("NETWORK_ACL_BEGIN") match { var subnets: mutable.SortedList[Subnet] = if (defaultBypass) proxySubnets else bypassSubnets
case -1 => for (line <- value.getLines()) (line.indexOf('#') match {
case index => in_urls = true case -1 => line
} case index =>
line.indexOf("NETWORK_ACL_END") match { line.substring(index + 1) match {
case -1 => case networkAclParser(url) => urls.add(new URL(url))
case index => in_urls = false case _ => // ignore
} }
"" // ignore any comment lines line.substring(0, index) // trim comments
}
case index => if (!in_urls) line else ""
}).trim match { }).trim match {
// Ignore all section controls
case "[outbound_block_list]" => case "[outbound_block_list]" =>
hostnames = null
subnets = null
case "[black_list]" | "[bypass_list]" => case "[black_list]" | "[bypass_list]" =>
hostnames = bypassHostnames
subnets = bypassSubnets
case "[white_list]" | "[proxy_list]" => case "[white_list]" | "[proxy_list]" =>
case "[reject_all]" | "[bypass_all]" => hostnames = proxyHostnames
case "[accept_all]" | "[proxy_all]" => subnets = proxySubnets
case "[reject_all]" | "[bypass_all]" => bypass = true
case "[accept_all]" | "[proxy_all]" => bypass = false
case input if subnets != null && input.nonEmpty => try subnets += Subnet.fromString(input) catch { case input if subnets != null && input.nonEmpty => try subnets += Subnet.fromString(input) catch {
case _: IllegalArgumentException => if (isUrl(input)) { case _: IllegalArgumentException => hostnames += input
urls += input
} else {
hostnames += input
}
} }
case _ => case _ =>
} }
this.subnets ++= (if (bypass) proxySubnets else bypassSubnets)
this this
} }
final def fromId(id: String): Acl = fromSource(Source.fromFile(Acl.getFile(id))) final def fromId(id: String): Acl = fromSource(Source.fromFile(Acl.getFile(id)))
def getAclString(network: Boolean): String = { def flatten(depth: Int): Acl = {
val result = new StringBuilder() if (depth > 0) for (url <- urls) {
if (urls.nonEmpty) { val child = new Acl().fromSource(Source.fromURL(url), bypass).flatten(depth - 1)
result.append(urls.mkString("\n")) if (bypass != child.bypass) {
if (network) { Log.w(TAG, "Imported network ACL has a conflicting mode set. This will probably not work as intended. URL: %s"
result.append("\n#NETWORK_ACL_BEGIN\n") .format(url))
try { child.subnets.clear() // subnets for the different mode are discarded
urls.foreach((url: String) => result.append(Source.fromURL(url).mkString)) child.bypass = bypass
} catch {
case e: IOException => // ignore
} }
result.append("\n#NETWORK_ACL_END\n") bypassHostnames ++= child.bypassHostnames
proxyHostnames ++= child.proxyHostnames
subnets ++= child.subnets
} }
result.append("\n") urls.clear()
this
} }
if (result.isEmpty) {
result.append("[bypass_all]\n") override def toString: String = {
val result = new StringBuilder()
result.append(if (bypass) "[bypass_all]\n" else "[proxy_all]\n")
val (bypassList, proxyList) =
if (bypass) (bypassHostnames.toStream, subnets.toStream.map(_.toString) #::: proxyHostnames.toStream)
else (subnets.toStream.map(_.toString) #::: bypassHostnames.toStream, proxyHostnames.toStream)
if (bypassList.nonEmpty) {
result.append("[bypass_list]\n")
result.append(bypassList.mkString("\n"))
result.append('\n')
} }
val list = subnets.toStream.map(_.toString) #::: hostnames.toStream if (proxyList.nonEmpty) {
if (list.nonEmpty) {
result.append("[proxy_list]\n") result.append("[proxy_list]\n")
result.append(list.mkString("\n")) result.append(proxyList.mkString("\n"))
result.append('\n') result.append('\n')
} }
result.append(urls.map("#IMPORT_URL <%s>\n".format(_)).mkString)
result.toString result.toString
} }
override def toString: String = {
getAclString(false)
}
def isValidCustomRules: Boolean = !hostnames.isEmpty
// Don't change: dummy fields for OrmLite interaction // Don't change: dummy fields for OrmLite interaction
// noinspection ScalaUnusedSymbol // noinspection ScalaUnusedSymbol
...@@ -125,6 +155,7 @@ class Acl { ...@@ -125,6 +155,7 @@ class Acl {
} }
object Acl { object Acl {
final val TAG = "Acl"
final val ALL = "all" final val ALL = "all"
final val BYPASS_LAN = "bypass-lan" final val BYPASS_LAN = "bypass-lan"
final val BYPASS_CHN = "bypass-china" final val BYPASS_CHN = "bypass-china"
...@@ -132,6 +163,10 @@ object Acl { ...@@ -132,6 +163,10 @@ object Acl {
final val GFWLIST = "gfwlist" final val GFWLIST = "gfwlist"
final val CHINALIST = "china-list" final val CHINALIST = "china-list"
final val CUSTOM_RULES = "custom-rules" final val CUSTOM_RULES = "custom-rules"
final val CUSTOM_RULES_FLATTENED = "custom-rules-flattened"
private val networkAclParser = "^IMPORT_URL\\s*<(.+)>\\s*$".r
private val urlOrdering: Ordering[URL] = Ordering.by(url => (url.getHost, url.getPort, url.getFile, url.getProtocol))
def getFile(id: String) = new File(app.getFilesDir, id + ".acl") def getFile(id: String) = new File(app.getFilesDir, id + ".acl")
def customRules: Acl = { def customRules: Acl = {
...@@ -139,9 +174,9 @@ object Acl { ...@@ -139,9 +174,9 @@ object Acl {
try acl.fromId(CUSTOM_RULES) catch { try acl.fromId(CUSTOM_RULES) catch {
case _: FileNotFoundException => case _: FileNotFoundException =>
} }
acl.bypass = true
acl.bypassHostnames.clear() // everything is bypassed
acl acl
} }
def save(id: String, acl: Acl, network: Boolean = false): Unit = { def save(id: String, acl: Acl): Unit = IOUtils.writeString(getFile(id), acl.toString)
IOUtils.writeString(getFile(id), acl.getAclString(network))
}
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment