chrome

package module
v0.0.0-...-ac0c594 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 30 Imported by: 0

README

chrome

Services implemented in Go.

Install

# go install github.com/b97tsk/chrome/cmd/chrome@latest

Usage

Create a config file (see below), then run:

chrome path/to/your/config/file

If config file is not specified, chrome.yaml is assumed.

If config file is -, chrome will try to load config from standard input.

Sample Config File

log:
  file: chrome.log # Write log messages to this file.
  level: INFO # Log level, alternatives are ERROR, WARN, DEBUG, TRACE and NONE.

dial:
  timeout: 10s # Default connect timeout.

alias#1: # Field names start with word `alias` are ignored.
  - &SS ss://method:password@example.com:12345
  - &Tor socks5://127.0.0.1:9150

# Create three TCP tunnels over different forward proxies.

tcptun#1: # Note that field names must be unique.
  on: 127.1.2.7:53 # Listen address.
  for: 1.1.1.1:53 # Forward target.
  over: Direct # Direct access, which is the default.

tcptun#2: # The first word is the service name, which must be valid.
  on: 127.1.2.7:5353
  for: 8.8.8.8:53
  over: *SS

tcptun#3:
  on: 127.1.2.7:443
  for: www.google.com:443
  over: *Tor

# Create three SOCKS5 servers over different forward proxies.

socks#1:
  on: 127.1.2.7:1080 # Listen address.
  over: Direct # Direct access, which is the default.

socks#2:
  on: 127.1.2.7:1081
  over: *SS

socks#3:
  on: 127.1.2.7:1082
  over: *Tor

# Create three Shadowsocks servers over different forward proxies.

shadowsocks#1:
  on: :10800 # Listening on all available IP addresses of the local system.
  method: aes-256-gcm
  password: 123456
  over: [] # Direct access, which is the default.

shadowsocks#2:
  on: :10801
  method: aes-256-gcm
  password: 123456
  over: [*SS, *Tor] # Chain proxies, one over another.

shadowsocks#3:
  on: :10802
  method: aes-256-gcm
  password: !!binary MTIzNDU2 # Encoded in Base64.
  over: [Direct, *SS, Direct] # `Direct`s are simply ignored.

Documentation

Overview

Package chrome is a library that can manage and start various services implemented in Go (currently, very TCP centric).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bytes

type Bytes int64

Bytes is a helper type for unmarshaling an int64 from YAML. When unmarshaling, Bytes accepts a binary prefix, for example, 1K = 1024.

func (*Bytes) UnmarshalYAML

func (b *Bytes) UnmarshalYAML(v *yaml.Node) error

type Context

type Context struct {
	// Context is for cancellation. It is canceled when the job cancels.
	context.Context
	// Manager is the Manager that starts the job.
	Manager *Manager
	// Event is for receiving events sent to the job.
	Event <-chan Event
}

A Context provides contextual values for a job.

type DialOptions

type DialOptions struct {
	// Timeout for each attempt to dial.
	Timeout time.Duration
	// Interval specifies the minimum interval between two consecutive attempts.
	// If one attempt fails shortly, next attempt has to wait.
	Interval time.Duration
	// MaxAttempts specifies the maximum number of dials.
	MaxAttempts int
}

DialOptions provides options for Dial.

type EnvString

type EnvString string

EnvString is a helper type for unmarshaling a string from YAML. When unmarshaling, it calls os.ExpandEnv on the original string and stores the result.

func (EnvString) String

func (s EnvString) String() string

func (*EnvString) UnmarshalYAML

func (s *EnvString) UnmarshalYAML(v *yaml.Node) error

type Event

type Event any

Event is the interface of events.

type Job

type Job struct {
	// Context is for cancellation. It is canceled when the job stops.
	context.Context
	// Cancel cancels the job and later cancels Context after Service.Run returns.
	Cancel context.CancelFunc
	// Event is for sending events to the job.
	Event chan<- Event
}

A Job provides mechanism to control the job started by a Service.

func (Job) SendEvent

func (job Job) SendEvent(ev Event)

SendEvent sends a event to the job.

func (Job) Stop

func (job Job) Stop()

Stop stops the job.

type LoadEvent

type LoadEvent struct {
	Options any
}

LoadEvent is for sending options to a job.

When a job receives this event, it should only parse the options but not start doing anything what it's supposed to do, not until the job receives a LoadedEvent.

If a job has acquired some system resources (for example, listening to a port) but no longer needs them, this is the good chance to release them, so other jobs can acquire them.

type LoadedEvent

type LoadedEvent struct{}

LoadedEvent is for telling a job to start doing what it's supposed to do.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

A Manager manages services and jobs started by services.

func (*Manager) AddService

func (m *Manager) AddService(service Service)

AddService registers a Service. Registering services are important for Load(File|FS) methods. Unregistered services cannot be started by Load(File|FS) methods.

func (*Manager) CloseConnections

func (m *Manager) CloseConnections()

CloseConnections closes all connections that Serve accepts.

Shutdown calls CloseConnections.

func (*Manager) Dial

func (m *Manager) Dial(
	ctx context.Context,
	network, address string,
	getopts func() (Proxy, DialOptions, bool),
	logger *log.Logger,
) (c net.Conn, err error)

Dial connects address repeatedly until success or ctx is canceled.

For each attempt, Dial calls getopts to obtain a Proxy and a DialOptions. Dial uses the Proxy to connect target address, and the DialOptions for custom behavior.

func (*Manager) Load

func (m *Manager) Load(r io.Reader) error

Load loads a YAML document from r.

func (*Manager) LoadFS

func (m *Manager) LoadFS(fsys fs.FS, name string) error

LoadFS loads a YAML document from a file in a file system.

func (*Manager) LoadFile

func (m *Manager) LoadFile(name string) error

LoadFile loads a YAML document from a file.

func (*Manager) LogLevel

func (m *Manager) LogLevel() log.Level

LogLevel gets the logging level.

func (*Manager) Logger

func (m *Manager) Logger(name string) *log.Logger

Logger gets a Logger with name quoted with square brackets as the prefix.

func (*Manager) Open

func (m *Manager) Open(name string) (fs.File, error)

Open implements fs.FS. Open is available for jobs started by Load(File|FS) methods when they are handling options.

func (*Manager) Relay

func (m *Manager) Relay(
	local net.Conn,
	getopts func() (RelayOptions, bool),
	getRemote func(context.Context) net.Conn,
	sendResponse func(io.Writer) bool,
	logger *log.Logger,
)

Relay (TCP only) sends packets from local to remote, and vice versa.

For each attempt, Relay calls getopts to obtain a RelayOptions for custom behavior, and calls getRemote to obtain a remote connection.

If sendResponse is not nil, it will be called once for sending response to local, after obtaining a remote connection.

func (*Manager) Serve

func (m *Manager) Serve(ln net.Listener, fn func(net.Conn))

Serve accepts incoming connections on the Listener ln and calls fn for each accepted connection in a goroutine. The connection is closed when fn returns.

func (*Manager) Service

func (m *Manager) Service(name string) Service

Service gets the Service that was registered by AddService. Service returns nil if there is no registered Service with this name. Service returns Dummy if name is not considered a real Service name.

func (*Manager) SetDialOptions

func (m *Manager) SetDialOptions(opts DialOptions)

SetDialOptions sets default options for Dial, which may be overrided when Dial.

func (*Manager) SetLogFile

func (m *Manager) SetLogFile(name string) error

SetLogFile sets the file that each logging message would write to.

func (*Manager) SetLogLevel

func (m *Manager) SetLogLevel(level log.Level)

SetLogLevel sets the logging level.

func (*Manager) SetLogOutput

func (m *Manager) SetLogOutput(w io.Writer)

SetLogOutput sets a io.Writer that each logging message would write to.

func (*Manager) SetRelayOptions

func (m *Manager) SetRelayOptions(opts RelayOptions)

SetRelayOptions sets default options for Relay, which may be overrided when Relay.

func (*Manager) Shutdown

func (m *Manager) Shutdown()

Shutdown shutdowns and cleanups the Manager.

func (*Manager) StartService

func (m *Manager) StartService(ctx context.Context, service Service) (Job, error)

StartService starts a Service. Jobs started by StartService are not managed but they should be stopped manually before you Shutdown the Manager since somehow they are connected to the Manager.

func (*Manager) StopJobs

func (m *Manager) StopJobs()

StopJobs stops managed jobs that were started by Load(File|FS) methods.

type Proxy

type Proxy struct {
	// contains filtered or unexported fields
}

Proxy is a helper type for unmarshaling a proxy from YAML. A Proxy is basically a proxy.Dialer.

func MakeProxy

func MakeProxy(fwd proxy.Dialer, urls ...string) (Proxy, error)

MakeProxy chains one or more proxies (parsed from urls) together, using fwd as a forwarder. The dial order would be: fwd -> proxies[0] -> proxies[1] -> ... -> proxies[n-1], where n is the number of proxies.

Note that proxies specified in YAML use reverse ordering to go with the idiom "one over another".

func MakeProxyUsing

func MakeProxyUsing(strategy string, proxies []Proxy) (Proxy, error)

MakeProxyUsing creates a load balancing Proxy from multiple proxies with specified strategy.

func ProxyFromDialer

func ProxyFromDialer(d proxy.Dialer) Proxy

ProxyFromDialer creates a Proxy from a Dialer. The Dialer returned shouldn't be used for comparison.

func (Proxy) Dialer

func (p Proxy) Dialer() proxy.Dialer

Dialer gets the proxy.Dialer.

func (Proxy) Equal

func (p Proxy) Equal(other Proxy) bool

Equal reports whether p and other are the same proxy.

func (Proxy) IsZero

func (p Proxy) IsZero() bool

IsZero reports whether p is proxy.Direct.

func (*Proxy) UnmarshalYAML

func (p *Proxy) UnmarshalYAML(v *yaml.Node) error

type RelayOptions

type RelayOptions struct {
	// Timeout for each attempt to relay.
	//
	// After the remote-side connection has been established, we send a request
	// to the remote and normally we can expect the remote sends back a response.
	//
	// However, if the connection was established via a proxy, we cannot be sure
	// that we have successfully connected to the remote. A proxy can certainly
	// delay the actual work and return a connection early for a good reason.
	//
	// Relay detects that if the remote does not send back a response within
	// a period of time, it kills the connection and resends the request to
	// a new one.
	Timeout time.Duration
	// Interval specifies the minimum interval between two consecutive attempts.
	// If one attempt fails shortly, next attempt has to wait.
	Interval time.Duration
	// ConnIdle is the idle timeout when Relay starts.
	// If both connections (local-side and remote-side) remains idle (no reads)
	// for the duration of ConnIdle, both are closed and Relay ends.
	ConnIdle time.Duration
	// UplinkIdle is the idle timeout when the remote-side connection (downlink)
	// closes. If the local-side connection (uplink) remains idle (no reads)
	// for the duration of UplinkIdle, it is closed and Relay ends.
	UplinkIdle time.Duration
	// DownlinkIdle is the idle timeout when the local-side connection (uplink)
	// closes. If the remote-side connection (downlink) remains idle (no reads)
	// for the duration of DownlinkIdle, it is closed and Relay ends.
	DownlinkIdle time.Duration
}

RelayOptions provides options for Relay.

type Service

type Service interface {
	// Name gets the name of the Service.
	// Successive calls must return the same value.
	Name() string
	// Options returns a new options for unmarshaling.
	// Options may return nil to indicate no options.
	// If non-nil, the returned value must be a pointer to a struct.
	// The returned value is sent to Context.Load later after unmarshaling.
	Options() any
	// Run starts a job.
	Run(Context)
}

A Service is something that does certain jobs.

var Dummy Service = new(struct{ Service })

Dummy is a dummy Service.

type StringList

type StringList []string

StringList is a helper type for unmarshaling a slice of string from YAML. When unmarshaling, it treats a string as a one-length slice of string.

func (*StringList) UnmarshalYAML

func (s *StringList) UnmarshalYAML(v *yaml.Node) error

Directories

Path Synopsis
cmd
internal
service

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL