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

feat(example): add Outline CLI app for Linux #15

Merged
merged 24 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
19 changes: 19 additions & 0 deletions x/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,22 @@ func newPacketDialerFromPart(innerDialer transport.PacketDialer, oneDialerConfig
return nil, fmt.Errorf("config scheme '%v' is not supported", url.Scheme)
}
}

// NewShadowsocksPacketListenerFromPart creates a new [transport.PacketListener] according to the given config,
// the config must contain only one "ss://" segment.
func NewShadowsocksPacketListenerFromPart(ssConfig string) (transport.PacketListener, error) {
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
ssConfig = strings.TrimSpace(ssConfig)
if ssConfig == "" {
return nil, errors.New("empty config part")
}

url, err := url.Parse(ssConfig)
if err != nil {
return nil, fmt.Errorf("failed to parse config part: %w", err)
}

if url.Scheme != "ss" {
return nil, errors.New("config scheme must be 'ss' for a PacketListener")
}
return newShadowsocksPacketListenerFromURL(url)
fortuna marked this conversation as resolved.
Show resolved Hide resolved
}
9 changes: 9 additions & 0 deletions x/config/shadowsocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@ func newShadowsocksPacketDialerFromURL(innerDialer transport.PacketDialer, confi
return dialer, nil
}

func newShadowsocksPacketListenerFromURL(configURL *url.URL) (transport.PacketListener, error) {
config, err := parseShadowsocksURL(configURL)
if err != nil {
return nil, err
}
ep := &transport.UDPEndpoint{Address: config.serverAddress}
return shadowsocks.NewPacketListener(ep, config.cryptoKey)
}

type shadowsocksConfig struct {
serverAddress string
cryptoKey *shadowsocks.EncryptionKey
Expand Down
30 changes: 30 additions & 0 deletions x/examples/outline-cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# OutlineVPN CLI
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved

The CLI interface of OutlineVPN client for Linux.
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved

## Usage

#### Standard

```
./outline-cli -transport "ss://<outline-server-access-key>"
```

#### Advanced (with Golang)

```
go run github.com/Jigsaw-Code/outline-sdk/x/examples/outline-cli@latest -transport "ss://<outline-server-access-key>"
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
```

### Arguments

- `-transport` : the Outline server access key from the service provider, it should start with "ss://"

## Build (for Developers)

We recommend to setup a [go workspace](https://go.dev/blog/get-familiar-with-workspaces) to build the code. Then use the following command to build the CLI (only support Linux):
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved

```
cd outline-sdk/x/examples/
go build -o outline-cli -ldflags="-extldflags=-static" ./outline-cli
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
```
68 changes: 68 additions & 0 deletions x/examples/outline-cli/dns_posix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// 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
//
// https://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.

//go:build linux

package main

import (
"fmt"
"log"
"os"
)

const (
resolvConfFile = "/etc/resolv.conf"
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
resolvConfHeadFile = "/etc/resolv.conf.head"
resolvConfBackupFile = "/etc/resolv.outlinecli.backup"
resolvConfHeadBackupFile = "/etc/resolv.head.outlinecli.backup"
)

func setSystemDNSServer(serverHost string) error {
setting := []byte(`# Outline CLI DNS Setting
# The original file has been renamed as resolv[.head].outlinecli.backup
nameserver ` + serverHost + "\n")

if err := backupAndWriteFile(resolvConfFile, resolvConfBackupFile, setting); err != nil {
return err
}
return backupAndWriteFile(resolvConfHeadFile, resolvConfHeadBackupFile, setting)
}

func restoreSystemDNSServer() {
restoreFileIfExists(resolvConfBackupFile, resolvConfFile)
restoreFileIfExists(resolvConfHeadBackupFile, resolvConfHeadFile)
}

func backupAndWriteFile(original, backup string, data []byte) error {
if err := os.Rename(original, backup); err != nil {
return fmt.Errorf("failed to backup DNS config file '%s' to '%s': %w", original, backup, err)
}
if err := os.WriteFile(original, data, 0644); err != nil {
return fmt.Errorf("failed to write DNS config file '%s': %w", original, err)
}
return nil
}

func restoreFileIfExists(backup, original string) {
if _, err := os.Stat(backup); err != nil {
log.Printf("[warn] no DNS config backup file '%s' presents: %v\n", backup, err)
return
}
if err := os.Rename(backup, original); err != nil {
log.Printf("[error] failed to restore DNS config from backup '%s' to '%s': %v\n", backup, original, err)
return
}
log.Printf("[info] DNS config restored from '%s' to '%s'\n", backup, original)
}
52 changes: 52 additions & 0 deletions x/examples/outline-cli/ipv6_posix.go
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// 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
//
// https://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.

//go:build linux

package main

import (
"fmt"
"log"
"os"
)

const disableIPv6ProcFile = "/proc/sys/net/ipv6/conf/all/disable_ipv6"

// enableIPv6 enables or disables the IPv6 support for the Linux system.
// It returns the previous setting value so the caller can restore it.
// Non-nil error means we cannot find the IPv6 setting.
func enableIPv6(enabled bool) (bool, error) {
disabledStr, err := os.ReadFile(disableIPv6ProcFile)
if err != nil {
return false, fmt.Errorf("failed to read IPv6 config: %w", err)
}
if disabledStr[0] != '0' && disabledStr[0] != '1' {
return false, fmt.Errorf("invalid IPv6 config value: %v", disabledStr)
}

prevEnabled := disabledStr[0] == '0'

if enabled {
disabledStr[0] = '0'
} else {
disabledStr[0] = '1'
}
if err := os.WriteFile(disableIPv6ProcFile, disabledStr, 0644); err != nil {
return prevEnabled, fmt.Errorf("failed to write IPv6 config: %w", err)
}

log.Printf("[info] global IPv6 enabled: %v\n", enabled)
return prevEnabled, nil
}
110 changes: 110 additions & 0 deletions x/examples/outline-cli/main.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
//
// https://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.

//go:build linux

package main

import (
"flag"
"fmt"
"io"
"log"
"os"
"os/signal"
"sync"

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

const OUTLINE_TUN_NAME = "outline233"
const OUTLINE_TUN_IP = "10.233.233.1"
const OUTLINE_TUN_MTU = 1500 // todo: we can read this from netlink
const OUTLINE_GW_SUBNET = "10.233.233.2/32"
const OUTLINE_GW_IP = "10.233.233.2"
const OUTLINE_ROUTING_PRIORITY = 23333
const OUTLINE_ROUTING_TABLE = 233
const OUTLINE_DNS_SERVER = "9.9.9.9"

// ./app -transport "ss://..."
func main() {
fmt.Println("OutlineVPN CLI (experimental)")

transportFlag := flag.String("transport", "", "Transport config")
flag.Parse()

// this WaitGroup must Wait() after tun is closed
trafficCopyWg := &sync.WaitGroup{}
defer trafficCopyWg.Wait()

tun, err := NewTunDevice(OUTLINE_TUN_NAME, OUTLINE_TUN_IP)
if err != nil {
log.Printf("[error] failed to create tun device: %v\n", err)
return
}
defer tun.Close()

// disable IPv6 before resolving Shadowsocks server IP
prevIPv6, err := enableIPv6(false)
if err != nil {
log.Printf("[error] failed to disable IPv6: %v\n", err)
return
}
defer enableIPv6(prevIPv6)

ss, err := NewOutlineDevice(*transportFlag)
if err != nil {
log.Printf("[error] failed to create Outline device: %v", err)
return
}
defer ss.Close()

ss.Refresh()

// Copy the traffic from tun device to OutlineDevice bidirectionally
trafficCopyWg.Add(2)
go func() {
defer trafficCopyWg.Done()
written, err := io.Copy(ss, tun)
log.Printf("[info] tun -> OutlineDevice stopped: %v %v\n", written, err)
}()
go func() {
defer trafficCopyWg.Done()
written, err := io.Copy(tun, ss)
log.Printf("[info] OutlineDevice -> tun stopped: %v %v\n", written, err)
}()

if err := setSystemDNSServer(OUTLINE_DNS_SERVER); err != nil {
log.Printf("[error] failed to configure system DNS: %v", err)
return
}
defer restoreSystemDNSServer()

if err := startRouting(ss.GetServerIP().String(),
OUTLINE_TUN_NAME,
jyyi1 marked this conversation as resolved.
Show resolved Hide resolved
OUTLINE_GW_SUBNET,
OUTLINE_TUN_IP,
OUTLINE_GW_IP,
OUTLINE_ROUTING_TABLE,
OUTLINE_ROUTING_PRIORITY); err != nil {
log.Printf("[error] failed to configure routing: %v", err)
return
}
defer stopRouting(OUTLINE_ROUTING_TABLE)

sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, unix.SIGTERM, unix.SIGHUP)
s := <-sigc
log.Printf("\nreceived %v, terminating...\n", s)
}
Loading
Loading