Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: build tun2socks from source within Android Studio #487

Merged
merged 5 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ dependencies {
implementation 'com.google.firebase:firebase-crashlytics-ndk:18.2.6'
implementation 'com.google.firebase:firebase-config:21.0.1'
// For go-tun2socks
implementation project(":tun2socks")
implementation project(path: ':tun2socks', configuration: 'aarBinary')
}

// For Firebase Analytics
Expand Down
2 changes: 0 additions & 2 deletions Android/tun2socks/README.md

This file was deleted.

79 changes: 77 additions & 2 deletions Android/tun2socks/build.gradle
Original file line number Diff line number Diff line change
@@ -1,2 +1,77 @@
configurations.maybeCreate("default")
artifacts.add("default", file('tun2socks.aar'))
// We use Android library plugin to get the Android SDK path.
plugins {
id('com.android.library')
}

android {
compileSdkVersion 33
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
defaultConfig {
minSdkVersion 16
}
}

configurations {
aarBinary {
canBeConsumed = true
canBeResolved = false
}
}

def goBuildDir = file("${buildDir}/go")
def outputAAR = file("${buildDir}/tun2socks.aar")

def srcDir = "${rootDir}/tun2socks/intra"
def srcPackages = [srcDir,
"${srcDir}/android",
"${srcDir}/doh",
"${srcDir}/split",
"${srcDir}/protect"]

// Make sure that the go build directory exists.
task ensureBuildDir() {
doLast {
goBuildDir.mkdirs()
}
}

// Install `gomobile` and `gobind` to the build directory, so that the user
// does not need to install them on their system or call `gomobile init`.
task ensureGoMobile(type: Exec, dependsOn: ensureBuildDir) {
// Define outputs so this task will only be executed when they don't exist
outputs.file("${goBuildDir}/gomobile")
outputs.file("${goBuildDir}/gobind")

environment 'GOBIN', goBuildDir.getPath()

commandLine('go', 'install',
'golang.org/x/mobile/cmd/gomobile@latest',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you use @latest, you will ignore the go.mod, and you won't get consistent versioning.

Use go build instead, so it's aware of the module: https://github.com/Jigsaw-Code/outline-sdk/tree/main/x/mobileproxy#build-the-go-mobile-binaries-with-go-build

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing @latest from the package name would do the work as well. If the @ symbol is omitted, go install will also read the go.mod file.

Here is the source code that handles package names containing @ in go install: https://github.com/golang/go/blob/ad9e6edfddf7c68b7a549ab7b491919f0980889d/src/cmd/go/internal/work/build.go#L690-L693

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code is not very clear if it will install in module mode and use the pinned dependencies.
But the documentation seems to imply it will be installed in module-aware mode. So I guess it's fine to just remove the version suffix.

I still think go build is superior, because you don't need to know the rules of where Go installs things. You can explicitly specify the output location with the -o flag. This is especially helpful for people not used to Go, since otherwise what happens to the binary is just magic. But it's up to you.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replaced it with go build since go install won't install reproducible binaries, either.

'golang.org/x/mobile/cmd/gobind@latest')
}

// Invoke `gomobile bind` to build from `srcPackages` to `outputAAR`.
// `gomobile` needs the `ANDROID_HOME` environment variable to be set, and the
// parent directory of `gobind` must be in the `PATH` as well.
task gobind(type: Exec, dependsOn: ensureGoMobile) {
// Define inputs and outputs so Gradle will enable incremental builds
inputs.dir(srcDir)
outputs.file(outputAAR)

workingDir goBuildDir
environment 'ANDROID_HOME', android.sdkDirectory
environment 'PATH', goBuildDir.getPath() +
System.getProperty('path.separator') +
System.getenv('PATH')

commandLine("${goBuildDir}/gomobile", 'bind',
fortuna marked this conversation as resolved.
Show resolved Hide resolved
'-target=android', '-androidapi=16',
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
'-o', outputAAR,
*srcPackages)
}

// AAR file that can be consumed by other projects. For example:
// implementation project(path: ':tun2socks', configuration: 'aarBinary')
artifacts {
aarBinary(outputAAR) {
builtBy(gobind)
}
}
27 changes: 27 additions & 0 deletions Android/tun2socks/intra/android/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tun2socks

import (
"runtime/debug"

"github.com/eycorsican/go-tun2socks/common/log"
)

func init() {
// Conserve memory by increasing garbage collection frequency.
debug.SetGCPercent(10)
log.SetLevel(log.WARN)
}
38 changes: 38 additions & 0 deletions Android/tun2socks/intra/android/tun.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tun2socks

import (
"errors"
"os"

"golang.org/x/sys/unix"
)

func makeTunFile(fd int) (*os.File, error) {
if fd < 0 {
return nil, errors.New("must provide a valid TUN file descriptor")
}
// Make a copy of `fd` so that os.File's finalizer doesn't close `fd`.
newfd, err := unix.Dup(fd)
if err != nil {
return nil, err
}
file := os.NewFile(uintptr(newfd), "")
if file == nil {
return nil, errors.New("failed to open TUN file descriptor")
}
return file, nil
}
110 changes: 110 additions & 0 deletions Android/tun2socks/intra/android/tun2socks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tun2socks

import (
"errors"
"io"
"io/fs"
"log"
"os"
"strings"

"github.com/Jigsaw-Code/Intra/Android/tun2socks/intra"
"github.com/Jigsaw-Code/Intra/Android/tun2socks/intra/doh"
"github.com/Jigsaw-Code/Intra/Android/tun2socks/intra/protect"
"github.com/Jigsaw-Code/outline-sdk/network"
)

// ConnectIntraTunnel reads packets from a TUN device and applies the Intra routing
// rules. Currently, this only consists of redirecting DNS packets to a specified
// server; all other data flows directly to its destination.
//
// `fd` is the TUN device. The IntraTunnel acquires an additional reference to it, which
//
// is released by IntraTunnel.Disconnect(), so the caller must close `fd` _and_ call
// Disconnect() in order to close the TUN device.
//
// `fakedns` is the DNS server that the system believes it is using, in "host:port" style.
//
// The port is normally 53.
//
// `udpdns` and `tcpdns` are the location of the actual DNS server being used. For DNS
//
// tunneling in Intra, these are typically high-numbered ports on localhost.
//
// `dohdns` is the initial DoH transport. It must not be `nil`.
// `protector` is a wrapper for Android's VpnService.protect() method.
// `eventListener` will be provided with a summary of each TCP and UDP socket when it is closed.
//
// Throws an exception if the TUN file descriptor cannot be opened, or if the tunnel fails to
// connect.
func ConnectIntraTunnel(
fd int, fakedns string, dohdns doh.Transport, protector protect.Protector, eventListener intra.Listener,
) (*intra.Tunnel, error) {
tun, err := makeTunFile(fd)
if err != nil {
return nil, err
}
t, err := intra.NewTunnel(fakedns, dohdns, tun, protector, eventListener)
if err != nil {
return nil, err
}
go copyUntilEOF(t, tun)
go copyUntilEOF(tun, t)
return t, nil
}

// NewDoHTransport returns a DNSTransport that connects to the specified DoH server.
// `url` is the URL of a DoH server (no template, POST-only). If it is nonempty, it
//
// overrides `udpdns` and `tcpdns`.
//
// `ips` is an optional comma-separated list of IP addresses for the server. (This
//
// wrapper is required because gomobile can't make bindings for []string.)
//
// `protector` is the socket protector to use for all external network activity.
// `auth` will provide a client certificate if required by the TLS server.
// `eventListener` will be notified after each DNS query succeeds or fails.
func NewDoHTransport(
url string, ips string, protector protect.Protector, auth doh.ClientAuth, eventListener intra.Listener,
) (doh.Transport, error) {
split := []string{}
if len(ips) > 0 {
split = strings.Split(ips, ",")
}
dialer := protect.MakeDialer(protector)
return doh.NewTransport(url, split, dialer, auth, eventListener)
}

func copyUntilEOF(dst, src io.ReadWriteCloser) {
log.Printf("[debug] start relaying traffic [%s] -> [%s]", src, dst)
defer log.Printf("[debug] stop relaying traffic [%s] -> [%s]", src, dst)

const commonMTU = 1500
buf := make([]byte, commonMTU)
defer dst.Close()
for {
_, err := io.CopyBuffer(dst, src, buf)
if err == nil || isErrClosed(err) {
return
}
}
}

func isErrClosed(err error) bool {
return errors.Is(err, os.ErrClosed) || errors.Is(err, fs.ErrClosed) || errors.Is(err, network.ErrClosed)
}
38 changes: 38 additions & 0 deletions Android/tun2socks/intra/doh/atomic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package doh

import (
"sync/atomic"
)

// Atomic is atomic.Value, specialized for doh.Transport.
type Atomic struct {
v atomic.Value
}

// Store a DNSTransport. d must not be nil.
func (a *Atomic) Store(t Transport) {
a.v.Store(t)
}

// Load the DNSTransport, or nil if it has not been stored.
func (a *Atomic) Load() Transport {
v := a.v.Load()
if v == nil {
return nil
}
return v.(Transport)
}
Loading