diff options
| -rw-r--r-- | common/log/log.go | 16 | ||||
| -rw-r--r-- | common/options.go | 8 | ||||
| -rw-r--r-- | common/pt_extras/pt_extras.go | 6 | ||||
| -rw-r--r-- | common/socks5/auth_pt2.go | 14 | ||||
| -rw-r--r-- | common/socks5/rfc1929.go | 4 | ||||
| -rw-r--r-- | common/socks5/socks5.go | 24 | ||||
| -rw-r--r-- | common/termmon/termmon.go | 136 | ||||
| -rw-r--r-- | common/termmon/termmon_linux.go | 49 | ||||
| -rw-r--r-- | modes/pt_socks5/pt_socks5.go | 57 | ||||
| -rw-r--r-- | modes/stun_udp/stun_udp.go | 31 | ||||
| -rw-r--r-- | modes/transparent_tcp/transparent_tcp.go | 54 | ||||
| -rw-r--r-- | modes/transparent_udp/transparent_udp.go | 26 | ||||
| -rw-r--r-- | shapeshifter-dispatcher/shapeshifter-dispatcher.go | 89 | ||||
| -rw-r--r-- | state/dispatcher.log | 7 | ||||
| -rw-r--r-- | transports/transports.go | 32 | 
15 files changed, 151 insertions, 402 deletions
| diff --git a/common/log/log.go b/common/log/log.go index 1c30b48..bcf83ea 100644 --- a/common/log/log.go +++ b/common/log/log.go @@ -59,7 +59,7 @@ var enableLogging bool  var unsafeLogging bool  // Init initializes logging with the given path, and log safety options. -func Init(enable bool, logFilePath string, unsafe bool) error { +func Init(enable bool, logFilePath string) error {  	if enable {  		f, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)  		if err != nil { @@ -78,12 +78,6 @@ func Enabled() bool {  	return enableLogging  } -// Unsafe returns if unsafe logging is allowed (the caller MAY skip eliding -// addresses and other bits of sensitive information). -func Unsafe() bool { -	return unsafeLogging -} -  // Level returns the current log level.  func Level() int {  	return logLevel @@ -140,14 +134,6 @@ func Infof(format string, a ...interface{}) {  	}  } -// Debugf logs the given format string/arguments at the DEBUG log level. -func Debugf(format string, a ...interface{}) { -	if enableLogging && logLevel >= LevelDebug { -		msg := fmt.Sprintf(format, a...) -		log.Print("[DEBUG]: " + msg) -	} -} -  // ElideError transforms the string representation of the provided error  // based on the unsafeLogging setting.  Callers that wish to log errors  // returned from Go's net package should use ElideError to sanitize the diff --git a/common/options.go b/common/options.go index f0ededf..8382544 100644 --- a/common/options.go +++ b/common/options.go @@ -40,7 +40,7 @@ func ParseServerOptions(s string) (params map[string]map[string]interface{}, err  	return result, nil  } -func CoerceToString(futureString interface{}) (*string, error) { +func CoerceToString(futureString interface{}) (string, error) {  		var result string  		switch futureString.(type) { @@ -48,10 +48,10 @@ func CoerceToString(futureString interface{}) (*string, error) {  			var icerr error  			result, icerr = interconv.ParseString(futureString)  			if icerr != nil { -				return nil, icerr +				return "", icerr  			} -			return &result, nil +			return result, nil  		default: -			return nil, errors.New("unable to coerce empty interface to string") +			return "", errors.New("unable to coerce empty interface to string")  		}  }
\ No newline at end of file diff --git a/common/pt_extras/pt_extras.go b/common/pt_extras/pt_extras.go index a04859e..b04426f 100644 --- a/common/pt_extras/pt_extras.go +++ b/common/pt_extras/pt_extras.go @@ -169,12 +169,6 @@ func resolveAddrStr(addrStr string) (*net.TCPAddr, error) {  	return &net.TCPAddr{IP: ip, Port: int(port), Zone: ""}, nil  } -// Feature #15435 adds a new env var for determining if Tor keeps stdin -// open for use in termination detection. -func PtShouldExitOnStdinClose() bool { -	return os.Getenv("TOR_PT_EXIT_ON_STDIN_CLOSE") == "1" -} -  func ArgsToDialer(target string, name string, args map[string]interface{}, dialer proxy.Dialer) (Optimizer.Transport, error) {  	switch name {  	//case "obfs2": diff --git a/common/socks5/auth_pt2.go b/common/socks5/auth_pt2.go index ce3a50d..7e22a0f 100644 --- a/common/socks5/auth_pt2.go +++ b/common/socks5/auth_pt2.go @@ -35,24 +35,24 @@ import (  func (req *Request) authPT2() (err error) {  	// The client sends a PT 2.0 authentication request. -	//  uint32_t len -	//  uint8_t data[len] +	//  uint32_t u +	//  uint8_t data[u]  	// Read the authentication data. -	var len uint32 -	if len, err = req.readUint32(); err != nil { +	var u uint32 +	if u, err = req.readUint32(); err != nil {  		return  	} -	if len == 0 { +	if u == 0 {  		err = fmt.Errorf("PT 2.0 authentication data with 0 length")  		return  	}  	var data []byte -	if data, err = req.readBytes(int(len)); err != nil { +	if data, err = req.readBytes(int(u)); err != nil {  		return  	} -	var result string = string(data) +	var result = string(data)  	// Parse the authentication data according to the PT 2.0 specification  	if req.Args, err = pt.ParsePT2ClientParameters(result); err != nil { diff --git a/common/socks5/rfc1929.go b/common/socks5/rfc1929.go index f8176f1..d7849df 100644 --- a/common/socks5/rfc1929.go +++ b/common/socks5/rfc1929.go @@ -39,8 +39,8 @@ func (req *Request) authRFC1929() (err error) {  	sendErrResp := func() {  		// Swallow write/flush errors, the auth failure is the relevant error.  		resp := []byte{authRFC1929Ver, authRFC1929Fail} -		req.rw.Write(resp[:]) -		req.flushBuffers() +		_, _ = req.rw.Write(resp[:]) +		_ = req.flushBuffers()  	}  	// The client sends a Username/Password request. diff --git a/common/socks5/socks5.go b/common/socks5/socks5.go index 74e1175..002ba7b 100644 --- a/common/socks5/socks5.go +++ b/common/socks5/socks5.go @@ -111,6 +111,8 @@ func ErrorToReplyCode(err error) ReplyCode {  		return ReplyHostUnreachable  	case syscall.ECONNREFUSED, syscall.ECONNRESET:  		return ReplyConnectionRefused +	case syscall.EPERM: +		return ReplyConnectionNotAllowed  	default:  		return ReplyGeneralFailure  	} @@ -267,15 +269,15 @@ func (req *Request) readCommand() error {  	var err error  	if err = req.readByteVerify("version", version); err != nil { -		req.Reply(ReplyGeneralFailure) +		_ = req.Reply(ReplyGeneralFailure)  		return err  	}  	if err = req.readByteVerify("command", cmdConnect); err != nil { -		req.Reply(ReplyCommandNotSupported) +		_ = req.Reply(ReplyCommandNotSupported)  		return err  	}  	if err = req.readByteVerify("reserved", rsv); err != nil { -		req.Reply(ReplyGeneralFailure) +		_ = req.Reply(ReplyGeneralFailure)  		return err  	} @@ -283,49 +285,49 @@ func (req *Request) readCommand() error {  	var atyp byte  	var host string  	if atyp, err = req.readByte(); err != nil { -		req.Reply(ReplyGeneralFailure) +		_ = req.Reply(ReplyGeneralFailure)  		return err  	}  	switch atyp {  	case atypIPv4:  		var addr []byte  		if addr, err = req.readBytes(net.IPv4len); err != nil { -			req.Reply(ReplyGeneralFailure) +			_ = req.Reply(ReplyGeneralFailure)  			return err  		}  		host = net.IPv4(addr[0], addr[1], addr[2], addr[3]).String()  	case atypDomainName:  		var alen byte  		if alen, err = req.readByte(); err != nil { -			req.Reply(ReplyGeneralFailure) +			_ = req.Reply(ReplyGeneralFailure)  			return err  		}  		if alen == 0 { -			req.Reply(ReplyGeneralFailure) +			_ = req.Reply(ReplyGeneralFailure)  			return fmt.Errorf("domain name with 0 length")  		}  		var addr []byte  		if addr, err = req.readBytes(int(alen)); err != nil { -			req.Reply(ReplyGeneralFailure) +			_ = req.Reply(ReplyGeneralFailure)  			return err  		}  		host = string(addr)  	case atypIPv6:  		var rawAddr []byte  		if rawAddr, err = req.readBytes(net.IPv6len); err != nil { -			req.Reply(ReplyGeneralFailure) +			_ = req.Reply(ReplyGeneralFailure)  			return err  		}  		addr := make(net.IP, net.IPv6len)  		copy(addr[:], rawAddr[:])  		host = fmt.Sprintf("[%s]", addr.String())  	default: -		req.Reply(ReplyAddressNotSupported) +		_ = req.Reply(ReplyAddressNotSupported)  		return fmt.Errorf("unsupported address type 0x%02x", atyp)  	}  	var rawPort []byte  	if rawPort, err = req.readBytes(2); err != nil { -		req.Reply(ReplyGeneralFailure) +		_ = req.Reply(ReplyGeneralFailure)  		return err  	}  	port := int(rawPort[0])<<8 | int(rawPort[1]) diff --git a/common/termmon/termmon.go b/common/termmon/termmon.go deleted file mode 100644 index 716bef6..0000000 --- a/common/termmon/termmon.go +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2015, Yawning Angel <yawning at torproject dot org> - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - *  * Redistributions of source code must retain the above copyright notice, - *    this list of conditions and the following disclaimer. - * - *  * Redistributions in binary form must reproduce the above copyright notice, - *    this list of conditions and the following disclaimer in the documentation - *    and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -package termmon - -import ( -	"io" -	"io/ioutil" -	"os" -	"os/signal" -	"runtime" -	"syscall" -	"time" - -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/pt_extras" -) - -var TermMonitorOSInit func(*TermMonitor) error - -type TermMonitor struct { -	sigChan     chan os.Signal -	handlerChan chan int -	numHandlers int -} - -func (m *TermMonitor) OnHandlerStart() { -	m.handlerChan <- 1 -} - -func (m *TermMonitor) OnHandlerFinish() { -	m.handlerChan <- -1 -} - -func (m *TermMonitor) Wait(termOnNoHandlers bool) os.Signal { -	// Block until a signal has been received, or (optionally) the -	// number of pending handlers has hit 0.  In the case of the -	// latter, treat it as if a SIGTERM has been received. -	for { -		select { -		case n := <-m.handlerChan: -			m.numHandlers += n -		case sig := <-m.sigChan: -			return sig -		} -		if termOnNoHandlers && m.numHandlers == 0 { -			return syscall.SIGTERM -		} -	} -} - -func (m *TermMonitor) termOnStdinClose() { -	_, err := io.Copy(ioutil.Discard, os.Stdin) - -	// io.Copy() will return a nil on EOF, since reaching EOF is -	// expected behavior.  No matter what, if this unblocks, assume -	// that stdin is closed, and treat that as having received a -	// SIGTERM. -	log.Noticef("Stdin is closed or unreadable: %v", err) -	m.sigChan <- syscall.SIGTERM -} - -func (m *TermMonitor) termOnPPIDChange(ppid int) { -	// Under most if not all U*IX systems, the parent PID will change -	// to that of init once the parent dies.  There are several notable -	// exceptions (Slowlaris/Android), but the parent PID changes -	// under those platforms as well. -	// -	// Naturally we lose if the parent has died by the time when the -	// Getppid() call was issued in our parent, but, this is better -	// than nothing. -	const ppidPollInterval = 1 * time.Second -	for ppid == os.Getppid() { -		time.Sleep(ppidPollInterval) -	} - -	// Treat the parent PID changing as the same as having received -	// a SIGTERM. -	log.Noticef("Parent pid changed: %d (was %d)", os.Getppid(), ppid) -	m.sigChan <- syscall.SIGTERM -} - -func NewTermMonitor(exitOnStdinClose bool) (m *TermMonitor) { -	ppid := os.Getppid() -	m = new(TermMonitor) -	m.sigChan = make(chan os.Signal) -	m.handlerChan = make(chan int) -	signal.Notify(m.sigChan, syscall.SIGINT, syscall.SIGTERM) - -	// If tor supports feature #15435, we can use Stdin being closed as an -	// indication that tor has died, or wants the PT to shutdown for any -	// reason. -	if exitOnStdinClose || pt_extras.PtShouldExitOnStdinClose() { -		go m.termOnStdinClose() -	} else { -		// Instead of feature #15435, use various kludges and hacks: -		//  * Linux - Platform specific code that should always work. -		//  * Other U*IX - Somewhat generic code, that works unless the -		//    parent dies before the monitor is initialized. -		if TermMonitorOSInit != nil { -			// Errors here are non-fatal, since it might still be -			// possible to fall back to a generic implementation. -			if err := TermMonitorOSInit(m); err == nil { -				return -			} -		} -		if runtime.GOOS != "windows" { -			go m.termOnPPIDChange(ppid) -		} -	} -	return -} diff --git a/common/termmon/termmon_linux.go b/common/termmon/termmon_linux.go deleted file mode 100644 index 89d3e9f..0000000 --- a/common/termmon/termmon_linux.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2015, Yawning Angel <yawning at torproject dot org> - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - *  * Redistributions of source code must retain the above copyright notice, - *    this list of conditions and the following disclaimer. - * - *  * Redistributions in binary form must reproduce the above copyright notice, - *    this list of conditions and the following disclaimer in the documentation - *    and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -package termmon - -import ( -	"fmt" -	"syscall" -) - -func TermMonitorInitLinux(m *TermMonitor) error { -	// Use prctl() to have the kernel deliver a SIGTERM if the parent -	// process dies.  This beats anything else that can be done before -	// #15435 is implemented. -	_, _, errno := syscall.Syscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGTERM), 0) -	if errno != 0 { -		var err error = errno -		return fmt.Errorf("prctl(PR_SET_PDEATHSIG, SIGTERM) returned: %s", err) -	} -	return nil -} - -func init() { -	TermMonitorOSInit = TermMonitorInitLinux -} diff --git a/modes/pt_socks5/pt_socks5.go b/modes/pt_socks5/pt_socks5.go index c3a8c45..e2aa546 100644 --- a/modes/pt_socks5/pt_socks5.go +++ b/modes/pt_socks5/pt_socks5.go @@ -46,22 +46,21 @@ import (  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/socks5" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/termmon"  	"github.com/OperatorFoundation/shapeshifter-ipc"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs2"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs4"  ) -func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) (launched bool, listeners []net.Listener) { +func ClientSetup(socksAddr string, ptClientProxy *url.URL, names []string, options string) (launched bool, listeners []net.Listener) {  	// Launch each of the client listeners.  	for _, name := range names {  		ln, err := net.Listen("tcp", socksAddr)  		if err != nil { -			pt.CmethodError(name, err.Error()) +			_ = pt.CmethodError(name, err.Error())  			continue  		} -		go clientAcceptLoop(target, termMon, name, ln, ptClientProxy, options) +		go clientAcceptLoop(name, ln, ptClientProxy, options)  		pt.Cmethod(name, socks5.Version(), ln.Addr())  		log.Infof("%s - registered listener: %s", name, ln.Addr()) @@ -73,8 +72,8 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  	return  } -//FIXME figure out how to make this function match the other modes -func clientAcceptLoop(target string, termMon *termmon.TermMonitor, name string, ln net.Listener, proxyURI *url.URL, options string){ + +func clientAcceptLoop(name string, ln net.Listener, proxyURI *url.URL, options string) {  	for {  		conn, err := ln.Accept()  		if err != nil { @@ -85,15 +84,12 @@ func clientAcceptLoop(target string, termMon *termmon.TermMonitor, name string,  			}  			continue  		} -		go clientHandler(target, termMon, name, conn, proxyURI, options) +		go clientHandler(name, conn, proxyURI, options)  	}  } -func clientHandler(target string, termMon *termmon.TermMonitor, name string, conn net.Conn, proxyURI *url.URL, options string) { -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish() - -	var needOptions bool = options == "" +func clientHandler(name string, conn net.Conn, proxyURI *url.URL, options string) { +	var needOptions = options == ""  	// Read the client's SOCKS handshake.  	socksReq, err := socks5.Handshake(conn, needOptions) @@ -122,28 +118,27 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, con  	var dialer proxy.Dialer  	// Deal with arguments. -	transport, _ := pt_extras.ArgsToDialer(socksReq.Target, name, args,dialer) +	transport, _ := pt_extras.ArgsToDialer(socksReq.Target, name, args, dialer)  	// Obtain the proxy dialer if any, and create the outgoing TCP connection. -	dialFn := proxy.Direct.Dial  	if proxyURI != nil { -		dialer, err := proxy.FromURL(proxyURI, proxy.Direct) -		if err != nil { +		var proxyErr error +		dialer, proxyErr = proxy.FromURL(proxyURI, proxy.Direct) +		if proxyErr != nil {  			// This should basically never happen, since config protocol  			// verifies this.  			log.Errorf("%s(%s) - failed to obtain proxy dialer: %s", name, addrStr, log.ElideError(err)) -			socksReq.Reply(socks5.ReplyGeneralFailure) +			_ = socksReq.Reply(socks5.ReplyGeneralFailure)  			return  		} -		dialFn = dialer.Dial  	} -	fmt.Println("Got dialer", dialFn, proxyURI, proxy.Direct) +	fmt.Println("Got dialer", dialer, proxyURI, proxy.Direct) -	remote, _ := transport.Dial() -	if err != nil { +	remote, err2 := transport.Dial() +	if err2 != nil {  		log.Errorf("%s(%s) - outgoing connection failed: %s", name, addrStr, log.ElideError(err)) -		socksReq.Reply(socks5.ErrorToReplyCode(err)) +		_ = socksReq.Reply(socks5.ErrorToReplyCode(err))  		return  	}  	err = socksReq.Reply(socks5.ReplySucceeded) @@ -161,7 +156,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, con  	return  } -func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, options string) (launched bool, listeners []net.Listener) { +func ServerSetup(ptServerInfo pt.ServerInfo, options string) (launched bool, listeners []net.Listener) {  	for _, bindaddr := range ptServerInfo.Bindaddrs {  		name := bindaddr.MethodName @@ -199,7 +194,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  				return  			}  		case "replicant": -			config, ok :=args.Get("config") +			config, ok := args.Get("config")  			fmt.Println(config)  			if !ok {  				return false, nil @@ -207,7 +202,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  			transport := replicant.New(replicant.Config{})  			listen = transport.Listen  		case "Dust": -			idPath, ok :=args.Get("idPath") +			idPath, ok := args.Get("idPath")  			if !ok {  				return false, nil  			} @@ -244,13 +239,11 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  			return  		} - -  		f := listen  		transportLn := f(bindaddr.Addr.String()) -		go serverAcceptLoop(termMon, name, transportLn, &ptServerInfo) +		go serverAcceptLoop(name, transportLn, &ptServerInfo)  		// if args := f.Args(); args != nil {  		// 	pt.SmethodArgs(name, ln.Addr(), *args) @@ -268,7 +261,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  	return  } -func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener, info *pt.ServerInfo){ +func serverAcceptLoop(name string, ln net.Listener, info *pt.ServerInfo) {  	for {  		conn, err := ln.Accept()  		if err != nil { @@ -277,13 +270,11 @@ func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener  			}  			continue  		} -		go serverHandler(termMon, name, conn, info) +		go serverHandler(name, conn, info)  	}  } -func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, info *pt.ServerInfo) { -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish() +func serverHandler(name string, remote net.Conn, info *pt.ServerInfo) {  	addrStr := log.ElideAddr(remote.RemoteAddr().String())  	log.Infof("%s(%s) - new connection", name, addrStr) diff --git a/modes/stun_udp/stun_udp.go b/modes/stun_udp/stun_udp.go index 4abe433..3d72b69 100644 --- a/modes/stun_udp/stun_udp.go +++ b/modes/stun_udp/stun_udp.go @@ -47,7 +47,6 @@ import (  	"github.com/willscott/goturn"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/termmon"  	"github.com/OperatorFoundation/shapeshifter-ipc"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs2"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs4" @@ -64,7 +63,7 @@ func NewConnState() ConnState {  type ConnTracker map[string]ConnState -func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) bool { +func ClientSetup(socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) bool {  	// Launch each of the client listeners.  	for _, name := range names {  		udpAddr, err := net.ResolveUDPAddr("udp", socksAddr) @@ -79,7 +78,7 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  			continue  		} -		go clientHandler(target, termMon, name, options, ln, ptClientProxy) +		go clientHandler(target, name, options, ln, ptClientProxy)  		log.Infof("%s - registered listener: %s", name, ln)  	} @@ -87,12 +86,9 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  	return true  } -func clientHandler(target string, termMon *termmon.TermMonitor, name string, options string, conn *net.UDPConn, proxyURI *url.URL) { +func clientHandler(target string, name string, options string, conn *net.UDPConn, proxyURI *url.URL) { -	termMon.OnHandlerStart()  	//defers are never called due to infinite loop -	//defer termMon.OnHandlerFinish() -	//defer  conn.Close()  	fmt.Println("@@@ handling...") @@ -133,7 +129,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  			fmt.Println("Opening connection to ", target) -			openConnection(&tracker, addr.String(), target, termMon, name, options, proxyURI) +			openConnection(&tracker, addr.String(), target, name, options, proxyURI)  			// Drop the packet.  			fmt.Println("recv: Open") @@ -141,7 +137,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  	}  } -func openConnection(tracker *ConnTracker, addr string, target string, termMon *termmon.TermMonitor, name string, options string, proxyURI *url.URL) { +func openConnection(tracker *ConnTracker, addr string, target string, name string, options string, proxyURI *url.URL) {  	fmt.Println("Making dialer...")  	newConn := NewConnState() @@ -193,7 +189,7 @@ func dialConn(tracker *ConnTracker, addr string, target string, name string, opt  	(*tracker)[addr] = ConnState{remote, false}  } -func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, options string, stateDir string) (launched bool, listeners []net.Listener) { +func ServerSetup(ptServerInfo pt.ServerInfo, options string, stateDir string) (launched bool, listeners []net.Listener) {  	fmt.Println("ServerSetup")  	// Launch each of the server listeners. @@ -268,7 +264,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  		transportLn := listen(bindaddr.Addr.String()) -		go serverAcceptLoop(termMon, name, transportLn, &ptServerInfo) +		go serverAcceptLoop(name, transportLn, &ptServerInfo)  		log.Infof("%s - registered listener: %s", name, log.ElideAddr(bindaddr.Addr.String())) @@ -345,7 +341,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  //	return int(port), err  //} -func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener, info *pt.ServerInfo){ +func serverAcceptLoop(name string, ln net.Listener, info *pt.ServerInfo) {  	for {  		conn, err := ln.Accept()  		fmt.Println("accepted") @@ -357,15 +353,13 @@ func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener  			}  			continue  		} -		go serverHandler(termMon, name, conn, info) +		go serverHandler(name, conn, info)  	}  } -func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, info *pt.ServerInfo) { +func serverHandler(name string, remote net.Conn, info *pt.ServerInfo) {  	var header *common.Message -	termMon.OnHandlerStart() -  	addrStr := log.ElideAddr(remote.RemoteAddr().String())  	fmt.Println("### handling", name)  	log.Infof("%s(%s) - new connection", name, addrStr) @@ -373,21 +367,19 @@ func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, i  	serverAddr, err := net.ResolveUDPAddr("udp", info.OrAddr.String())  	if err != nil {  		_ = remote.Close() -		termMon.OnHandlerFinish() +  		golog.Fatal(err)  	}  	localAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")  	if err != nil {  		_ = remote.Close() -		termMon.OnHandlerFinish()  		golog.Fatal(err)  	}  	dest, err := net.DialUDP("udp", localAddr, serverAddr)  	if err != nil {  		_ = remote.Close() -		termMon.OnHandlerFinish()  		golog.Fatal(err)  	} @@ -429,5 +421,4 @@ func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, i  	}  	_ = remote.Close() -	termMon.OnHandlerFinish()  } diff --git a/modes/transparent_tcp/transparent_tcp.go b/modes/transparent_tcp/transparent_tcp.go index 0bdfe75..c1482bb 100644 --- a/modes/transparent_tcp/transparent_tcp.go +++ b/modes/transparent_tcp/transparent_tcp.go @@ -43,14 +43,12 @@ import (  	"sync"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/termmon"  	"github.com/OperatorFoundation/shapeshifter-ipc" -	//"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs2"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/obfs4"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/shadow"  ) -func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) (launched bool, listeners []net.Listener) { +func ClientSetup(socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) (launched bool, listeners []net.Listener) {  	// Launch each of the client listeners.  	for _, name := range names {  		ln, err := net.Listen("tcp", socksAddr) @@ -59,7 +57,7 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  			continue  		} -		go clientAcceptLoop(target, termMon, name, options, ln, ptClientProxy) +		go clientAcceptLoop(target, name, options, ln, ptClientProxy)  		log.Infof("%s - registered listener: %s", name, ln.Addr()) @@ -70,7 +68,7 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  	return  } -func clientAcceptLoop(target string, termMon *termmon.TermMonitor, name string, options string, ln net.Listener, proxyURI *url.URL) { +func clientAcceptLoop(target string, name string, options string, ln net.Listener, proxyURI *url.URL) {  	for {  		conn, err := ln.Accept()  		if err != nil { @@ -81,14 +79,11 @@ func clientAcceptLoop(target string, termMon *termmon.TermMonitor, name string,  			log.Warnf("Failed to accept connection: %s", err.Error())  			continue  		} -		go clientHandler(target, termMon, name, options, conn, proxyURI) +		go clientHandler(target, name, options, conn, proxyURI)  	}  } -func clientHandler(target string, termMon *termmon.TermMonitor, name string, options string, conn net.Conn, proxyURI *url.URL) { -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish() - +func clientHandler(target string, name string, options string, conn net.Conn, proxyURI *url.URL) {  	var dialer proxy.Dialer  	dialer = proxy.Direct  	if proxyURI != nil { @@ -103,7 +98,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  		}  	} -//this is where the refactoring begins +	//this is where the refactoring begins  	args, argsErr := options2.ParseOptions(options)  	if argsErr != nil {  		log.Errorf("Error parsing transport options: %s", options) @@ -124,7 +119,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  	}  } -func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, statedir string, options string) (launched bool, listeners []net.Listener) { +func ServerSetup(ptServerInfo pt.ServerInfo, statedir string, options string) (launched bool, listeners []net.Listener) {  	// Launch each of the server listeners.  	for _, bindaddr := range ptServerInfo.Bindaddrs {  		name := bindaddr.MethodName @@ -177,7 +172,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  				log.Errorf("could not coerce Dust Url to string")  				return false, nil  			} -			transport := Dust.NewDustServer(*idPath) +			transport := Dust.NewDustServer(idPath)  			listen = transport.Listen  		case "meeklite":  			args, aok := args["meeklite"] @@ -190,22 +185,22 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  				return false, nil  			} -  			Url, err := options2.CoerceToString(untypedUrl)  			if err != nil {  				log.Errorf("could not coerce meeklite Url to string")  			} -			untypedFront, ok := args["Front"] +			untypedFront, ok := args["front"]  			if !ok {  				return false, nil  			} -			Front, err := options2.CoerceToString(untypedFront) -			if err != nil { -				log.Errorf("could not coerce meeklite Front to string") +			front, err2 := options2.CoerceToString(untypedFront) +			if err2 != nil { +				log.Errorf("could not coerce meeklite front to string")  			} -			transport := meeklite.NewMeekTransportWithFront(*Url, *Front) + +			transport := meeklite.NewMeekTransportWithFront(Url, front)  			listen = transport.Listen  		case "shadow":  			args, aok := args["shadow"] @@ -220,7 +215,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  			Password, err := options2.CoerceToString(untypedPassword)  			if err != nil { -				log.Errorf("could not coerce meeklite Url to string") +				log.Errorf("could not coerce shadow password to string")  			}  			untypedCertString, ok := args["Url"] @@ -228,13 +223,12 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  				return false, nil  			} - -			certString, err := options2.CoerceToString(untypedCertString) -			if err != nil { +			certString, err2 := options2.CoerceToString(untypedCertString) +			if err2 != nil {  				log.Errorf("could not coerce meeklite Url to string")  			} -			transport := shadow.NewShadowServer(*Password, *certString) +			transport := shadow.NewShadowServer(Password, certString)  			listen = transport.Listen  		default:  			log.Errorf("Unknown transport: %s", name) @@ -245,7 +239,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  		transportLn := f(bindaddr.Addr.String()) -		go serverAcceptLoop(termMon, name, transportLn, &ptServerInfo) +		go serverAcceptLoop(name, transportLn, &ptServerInfo)  		log.Infof("%s - registered listener: %s", name, log.ElideAddr(bindaddr.Addr.String())) @@ -281,7 +275,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, state  //	return result, nil  //} -func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener, info *pt.ServerInfo) { +func serverAcceptLoop(name string, ln net.Listener, info *pt.ServerInfo) {  	for {  		conn, err := ln.Accept()  		if err != nil { @@ -292,14 +286,11 @@ func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener  			log.Warnf("Failed to accept connection: %s", err.Error())  			continue  		} -		go serverHandler(termMon, name, conn, info) +		go serverHandler(name, conn, info)  	}  } -func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, info *pt.ServerInfo) { -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish() - +func serverHandler(name string, remote net.Conn, info *pt.ServerInfo) {  	// Connect to the orport.  	orConn, err := pt.DialOr(info, remote.RemoteAddr().String(), name)  	if err != nil { @@ -343,4 +334,3 @@ func copyLoop(a net.Conn, b net.Conn) error {  	return nil  } - diff --git a/modes/transparent_udp/transparent_udp.go b/modes/transparent_udp/transparent_udp.go index 64bc711..506637e 100644 --- a/modes/transparent_udp/transparent_udp.go +++ b/modes/transparent_udp/transparent_udp.go @@ -36,7 +36,6 @@ import (  	options2 "github.com/OperatorFoundation/shapeshifter-dispatcher/common"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/pt_extras" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/termmon"  	"github.com/OperatorFoundation/shapeshifter-ipc"  	"github.com/OperatorFoundation/shapeshifter-transports/transports/Dust"  	replicant "github.com/OperatorFoundation/shapeshifter-transports/transports/Replicant" @@ -65,7 +64,7 @@ func NewConnState() ConnState {  type ConnTracker map[string]ConnState -func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) bool { +func ClientSetup(socksAddr string, target string, ptClientProxy *url.URL, names []string, options string) bool {  	// Launch each of the client listeners.  	for _, name := range names {  		udpAddr, err := net.ResolveUDPAddr("udp", socksAddr) @@ -80,7 +79,7 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  			continue  		} -		go clientHandler(target, termMon, name, options, ln, ptClientProxy) +		go clientHandler(target, name, options, ln, ptClientProxy)  		log.Infof("%s - registered listener", name)  	} @@ -88,12 +87,10 @@ func ClientSetup(termMon *termmon.TermMonitor, socksAddr string, target string,  	return true  } -func clientHandler(target string, termMon *termmon.TermMonitor, name string, options string, conn *net.UDPConn, proxyURI *url.URL) { +func clientHandler(target string, name string, options string, conn *net.UDPConn, proxyURI *url.URL) {  	var length16 uint16  	defer conn.Close() -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish()  	fmt.Println("@@@ handling...") @@ -153,7 +150,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  			fmt.Println("Opening connection to ", target) -			openConnection(&tracker, addr.String(), target, termMon, name, options, proxyURI) +			openConnection(&tracker, addr.String(), target, name, options, proxyURI)  			// Drop the packet.  			fmt.Println("recv: Open") @@ -161,7 +158,7 @@ func clientHandler(target string, termMon *termmon.TermMonitor, name string, opt  	}  } -func openConnection(tracker *ConnTracker, addr string, target string, termMon *termmon.TermMonitor, name string, options string, proxyURI *url.URL) { +func openConnection(tracker *ConnTracker, addr string, target string, name string, options string, proxyURI *url.URL) {  	fmt.Println("Making dialer...")  	newConn := NewConnState() @@ -211,7 +208,7 @@ func dialConn(tracker *ConnTracker, addr string, target string, name string, opt  	(*tracker)[addr] = ConnState{remote, false}  } -func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, options string) (launched bool, listeners []net.Listener) { +func ServerSetup(ptServerInfo pt.ServerInfo, options string) (launched bool, listeners []net.Listener) {  	fmt.Println("ServerSetup")  	// Launch each of the server listeners. @@ -304,7 +301,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  		transportLn := f(bindaddr.Addr.String()) -		go serverAcceptLoop(termMon, name, transportLn, &ptServerInfo) +		go serverAcceptLoop(name, transportLn, &ptServerInfo)  		log.Infof("%s - registered listener: %s", name, log.ElideAddr(bindaddr.Addr.String())) @@ -356,7 +353,7 @@ func ServerSetup(termMon *termmon.TermMonitor, ptServerInfo pt.ServerInfo, optio  //	return int(port), err  //} -func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener, info *pt.ServerInfo) { +func serverAcceptLoop(name string, ln net.Listener, info *pt.ServerInfo) {  	for {  		conn, err := ln.Accept()  		fmt.Println("accepted") @@ -368,16 +365,13 @@ func serverAcceptLoop(termMon *termmon.TermMonitor, name string, ln net.Listener  			}  			continue  		} -		go serverHandler(termMon, name, conn, info) +		go serverHandler(name, conn, info)  	}  } -func serverHandler(termMon *termmon.TermMonitor, name string, remote net.Conn, info *pt.ServerInfo) { +func serverHandler(name string, remote net.Conn, info *pt.ServerInfo) {  	var length16 uint16 -	termMon.OnHandlerStart() -	defer termMon.OnHandlerFinish() -  	addrStr := log.ElideAddr(remote.RemoteAddr().String())  	fmt.Println("### handling", name)  	log.Infof("%s(%s) - new connection", name, addrStr) diff --git a/shapeshifter-dispatcher/shapeshifter-dispatcher.go b/shapeshifter-dispatcher/shapeshifter-dispatcher.go index a4412c9..59263e2 100644 --- a/shapeshifter-dispatcher/shapeshifter-dispatcher.go +++ b/shapeshifter-dispatcher/shapeshifter-dispatcher.go @@ -33,18 +33,16 @@ import (  	"errors"  	"flag"  	"fmt" +	"io"  	"io/ioutil"  	golog "log" -	"net"  	"net/url"  	"os"  	"path"  	"strings" -	"syscall"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/log"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/pt_extras" -	"github.com/OperatorFoundation/shapeshifter-dispatcher/common/termmon"  	"github.com/OperatorFoundation/shapeshifter-ipc"  	"github.com/OperatorFoundation/shapeshifter-dispatcher/modes/pt_socks5" @@ -63,7 +61,6 @@ const (  )  var stateDir string -var termMon *termmon.TermMonitor  func getVersion() string {  	return fmt.Sprintf("dispatcher-%s", dispatcherVersion) @@ -74,10 +71,10 @@ func main() {  	_, execName := path.Split(os.Args[0])  	flag.Usage = func() { -		fmt.Fprintf(os.Stderr, "shapeshifter-dispatcher is a PT v2.0 proxy supporting multiple transports and proxy modes\n\n") -		fmt.Fprintf(os.Stderr, "Usage:\n\t%s --client --state [statedir] --ptversion 2 --transports [transport1,transport2,...]\n\n", os.Args[0]) -		fmt.Fprintf(os.Stderr, "Example:\n\t%s --client --state state --ptversion 2 --transports obfs2\n\n", os.Args[0]) -		fmt.Fprintf(os.Stderr, "Flags:\n\n") +		_, _ = fmt.Fprintf(os.Stderr, "shapeshifter-dispatcher is a PT v2.0 proxy supporting multiple transports and proxy modes\n\n") +		_, _ = fmt.Fprintf(os.Stderr, "Usage:\n\t%s --client --state [statedir] --ptversion 2 --transports [transport1,transport2,...]\n\n", os.Args[0]) +		_, _ = fmt.Fprintf(os.Stderr, "Example:\n\t%s --client --state state --ptversion 2 --transports obfs2\n\n", os.Args[0]) +		_, _ = fmt.Fprintf(os.Stderr, "Flags:\n\n")  		flag.PrintDefaults()  	} @@ -108,7 +105,6 @@ func main() {  	showVer := flag.Bool("version", false, "Print version and exit")  	logLevelStr := flag.String("logLevel", "ERROR", "Log level (ERROR/WARN/INFO/DEBUG)")  	enableLogging := flag.Bool("enableLogging", false, "Log to TOR_PT_STATE_LOCATION/"+dispatcherLogFile) -	unsafeLogging := flag.Bool("unsafeLogging", false, "Disable the address scrubber")  	// Additional command line flags added to shapeshifter-dispatcher  	clientMode := flag.Bool("client", false, "Enable client mode") @@ -118,21 +114,17 @@ func main() {  	target := flag.String("target", "", "Specify transport server destination address")  	flag.Parse() -	// Initialize the termination state monitor as soon as possible. -	termMon = termmon.NewTermMonitor(*exitOnStdinClose) -  	if *showVer {  		fmt.Printf("%s\n", getVersion())  		os.Exit(0)  	} +  	if err := log.SetLogLevel(*logLevelStr); err != nil {  		fmt.Println("failed to set log level")  		golog.Fatalf("[ERROR]: %s - failed to set log level: %s", execName, err)  	}  	// Determine if this is a client or server, initialize the common state. -	var clientListeners []net.Listener -	var serverListeners []net.Listener  	launched := false  	isClient, err := checkIsClient(*clientMode, *serverMode)  	if err != nil { @@ -143,7 +135,7 @@ func main() {  		flag.Usage()  		golog.Fatalf("[ERROR]: %s - No state directory: Use --state or TOR_PT_STATE_LOCATION environment variable", execName)  	} -	if err = log.Init(*enableLogging, path.Join(stateDir, dispatcherLogFile), *unsafeLogging); err != nil { +	if err = log.Init(*enableLogging, path.Join(stateDir, dispatcherLogFile)); err != nil {  		golog.Fatalf("[ERROR]: %s - failed to initialize logging", execName)  	}  	if *options != "" && *optionsFile != "" { @@ -163,6 +155,11 @@ func main() {  			}  		}  	} +	//in socks5 mode, target is not needed +	if !*udp && !*transparent && *target != "" { +		log.Errorf("--target option cannot be used in SOCKS5 mode") +		return +	}  	log.Noticef("%s - launched", getVersion()) @@ -178,7 +175,7 @@ func main() {  				} else {  					ptClientProxy, names := getClientNames(ptversion, transportsList, proxy) -					launched = transparent_udp.ClientSetup(termMon, *socksAddr, *target, ptClientProxy, names, *options) +					launched = transparent_udp.ClientSetup(*socksAddr, *target, ptClientProxy, names, *options)  				}  			} else {  				log.Infof("%s - initializing server transport listeners", execName) @@ -187,8 +184,8 @@ func main() {  				} else {  					// launched = transparent_udp.ServerSetup(termMon, *bindAddr, *target) -					ptServerInfo := getServerInfo(ptversion, bindAddr, options, transportsList, orport, extorport, authcookie) -					launched, serverListeners = transparent_udp.ServerSetup(termMon, ptServerInfo, *options) +					ptServerInfo := getServerInfo(bindAddr, options, transportsList, orport, extorport, authcookie) +					launched, _ = transparent_udp.ServerSetup(ptServerInfo, *options)  				}  			}  		} else { @@ -200,15 +197,15 @@ func main() {  				} else {  					ptClientProxy, names := getClientNames(ptversion, transportsList, proxy) -					launched, clientListeners = transparent_tcp.ClientSetup(termMon, *socksAddr, *target, ptClientProxy, names, *options) +					launched, _ = transparent_tcp.ClientSetup(*socksAddr, *target, ptClientProxy, names, *options)  				}  			} else {  				log.Infof("%s - initializing server transport listeners", execName)  				if *bindAddr == "" {  					log.Errorf("%s - transparent mode requires a bindaddr", execName)  				} else { -					ptServerInfo := getServerInfo(ptversion, bindAddr, options, transportsList, orport, extorport, authcookie) -					launched, serverListeners = transparent_tcp.ServerSetup(termMon, ptServerInfo, *statePath, *options) +					ptServerInfo := getServerInfo(bindAddr, options, transportsList, orport, extorport, authcookie) +					launched, _ = transparent_tcp.ServerSetup(ptServerInfo, *statePath, *options)  				}  			}  		} @@ -222,15 +219,15 @@ func main() {  				} else {  					ptClientProxy, names := getClientNames(ptversion, transportsList, proxy) -					launched = stun_udp.ClientSetup(termMon, *socksAddr, *target, ptClientProxy, names, *options) +					launched = stun_udp.ClientSetup(*socksAddr, *target, ptClientProxy, names, *options)  				}  			} else {  				log.Infof("%s - initializing server transport listeners", execName)  				if *bindAddr == "" {  					log.Errorf("%s - STUN mode requires a bindaddr", execName)  				} else { -					ptServerInfo := getServerInfo(ptversion, bindAddr, options, transportsList, orport, extorport, authcookie) -					launched, serverListeners = stun_udp.ServerSetup(termMon, ptServerInfo, *options, stateDir) +					ptServerInfo := getServerInfo(bindAddr, options, transportsList, orport, extorport, authcookie) +					launched, _ = stun_udp.ServerSetup(ptServerInfo, *options, stateDir)  				}  			}  		} else { @@ -240,11 +237,11 @@ func main() {  				log.Infof("%s - initializing client transport listeners", execName)  				ptClientProxy, names := getClientNames(ptversion, transportsList, proxy) -				launched, clientListeners = pt_socks5.ClientSetup(termMon, *socksAddr, *target, ptClientProxy, names, *options) +				launched, _ = pt_socks5.ClientSetup(*socksAddr, ptClientProxy, names, *options)  			} else {  				log.Infof("%s - initializing server transport listeners", execName) -				ptServerInfo := getServerInfo(ptversion, bindAddr, options, transportsList, orport, extorport, authcookie) -				launched, serverListeners = pt_socks5.ServerSetup(termMon, ptServerInfo, *options) +				ptServerInfo := getServerInfo(bindAddr, options, transportsList, orport, extorport, authcookie) +				launched, _ = pt_socks5.ServerSetup(ptServerInfo, *options)  			}  		}  	} @@ -256,34 +253,17 @@ func main() {  	}  	log.Infof("%s - accepting connections", execName) -	defer func() { -		log.Noticef("%s - terminated", execName) -	}() - -	// At this point, the pt config protocol is finished, and incoming -	// connections will be processed.  Wait till the parent dies -	// (immediate exit), a SIGTERM is received (immediate exit), -	// or a SIGINT is received. -	if sig := termMon.Wait(false); sig == syscall.SIGTERM { -		return -	} -	// Ok, it was the first SIGINT, close all listeners, and wait till, -	// the parent dies, all the current connections are closed, or either -	// a SIGINT/SIGTERM is received, and exit. -	for _, ln := range clientListeners { -		_ = ln.Close() -	} - -	for _, ln := range serverListeners { -		_ = ln.Close() +	if *exitOnStdinClose || PtShouldExitOnStdinClose() { +		_, _ = io.Copy(ioutil.Discard, os.Stdin) +		os.Exit(-1) +	} else { +		select{}  	} +} -	termMon.Wait(true) -	// FIXME - block because termMon.Wait is not blocking -	//for { -	// -	//} +func PtShouldExitOnStdinClose() bool { +	return os.Getenv("TOR_PT_EXIT_ON_STDIN_CLOSE") == "1"  }  func checkIsClient(client bool, server bool) (bool, error) { @@ -309,9 +289,8 @@ func getClientNames(ptversion *string, transportsList *string, proxy *string) (c  	var ptClientInfo pt.ClientInfo  	var err error -	// FIXME - instead of this, goptlib should be modified to accept command line flag override of EITHER ptversion or transports (or both)  	if ptversion == nil || transportsList == nil { -		log.Infof("Falling back to environment variables for ptversion/transports %q %q", *ptversion, *transportsList) +		log.Infof("Falling back to environment variables for ptversion/transports")  		ptClientInfo, err = pt.ClientSetup(transports.Transports())  		if err != nil {  			// FIXME - print a more useful error, specifying --ptversion and --transports flags @@ -335,7 +314,7 @@ func getClientNames(ptversion *string, transportsList *string, proxy *string) (c  	return ptClientProxy, ptClientInfo.MethodNames  } -func getServerInfo(ptversion *string, bindaddrList *string, options *string, transportList *string, orport *string, extorport *string, authcookie *string) pt.ServerInfo { +func getServerInfo(bindaddrList *string, options *string, transportList *string, orport *string, extorport *string, authcookie *string) pt.ServerInfo {  	var ptServerInfo pt.ServerInfo  	var err error  	var bindaddrs []pt.Bindaddr diff --git a/state/dispatcher.log b/state/dispatcher.log index abba35d..3a53736 100644 --- a/state/dispatcher.log +++ b/state/dispatcher.log @@ -339,3 +339,10 @@  2019/10/21 15:13:16 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - initializing client transport listeners  2019/10/21 15:13:16 [INFO]: Optimizer - registered listener: 127.0.0.1:1444  2019/10/21 15:13:16 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - accepting connections +2019/10/21 15:25:27 [ERROR]: Fatal listener error: accept tcp 127.0.0.1:1444: use of closed network connection +2019/10/21 17:28:43 [NOTICE]: dispatcher-0.0.7-dev - launched +2019/10/21 17:28:43 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - initializing transparent proxy +2019/10/21 17:28:43 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - initializing TCP transparent proxy +2019/10/21 17:28:43 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - initializing client transport listeners +2019/10/21 17:28:43 [INFO]: Optimizer - registered listener: 127.0.0.1:1444 +2019/10/21 17:28:43 [INFO]: ___go_build_github_com_OperatorFoundation_shapeshifter_dispatcher_shapeshifter_dispatcher - accepting connections diff --git a/transports/transports.go b/transports/transports.go index 021b176..5f519d2 100644 --- a/transports/transports.go +++ b/transports/transports.go @@ -285,8 +285,8 @@ func ParseReplicantConfig(args map[string]interface{}) (*replicant.Config, error  	}  	replicantConfig := replicant.Config{ -		toneburstConfig, -		polishConfig, +		Toneburst: toneburstConfig, +		Polish:    polishConfig,  	}  	return &replicantConfig, nil @@ -328,8 +328,8 @@ func parseToneburstConfig(args map[string]interface{}) (*toneburst.Config, error  			}  			toneburstConfig := toneburst.Config{ -				selector, -				whalesongConfig, +				Selector:  selector, +				Whalesong: whalesongConfig,  			}  			return &toneburstConfig, nil @@ -378,8 +378,8 @@ func parsePolishConfig(args map[string]interface{}) (*polish.Config, error) {  			}  			polishConfig := polish.Config{ -				selector, -				silverConfig, +				Selector: selector, +				Silver:   silverConfig,  			}  			return &polishConfig, nil @@ -449,8 +449,8 @@ func parseWhalesongConfig(args map[string]interface{}) (*toneburst.WhalesongConf  	}  	whalesongConfig := toneburst.WhalesongConfig{ -		addSequences, -		removeSequences, +		AddSequences:    addSequences, +		RemoveSequences: removeSequences,  	}  	return &whalesongConfig, nil @@ -512,9 +512,9 @@ func parseSilverConfig(args map[string]interface{}) (*polish.SilverPolishConfig,  	}  	silverConfig := polish.SilverPolishConfig{ -		clientOrServer, -		clientConfig, -		serverConfig, +		ClientOrServer: clientOrServer, +		ClientConfig:   clientConfig, +		ServerConfig:   serverConfig,  	}  	return &silverConfig, nil @@ -560,8 +560,8 @@ func parseClientConfig(args map[string]interface{}) (*polish.SilverPolishClientC  	}  	silverPolishClientConfig := polish.SilverPolishClientConfig{ -		serverPublicKey, -		chunkSize, +		ServerPublicKey: serverPublicKey, +		ChunkSize:       chunkSize,  	}  	return &silverPolishClientConfig, nil @@ -629,9 +629,9 @@ func parseServerConfig(args map[string]interface{}) (*polish.SilverPolishServerC  	}  	silverPolishServerConfig := polish.SilverPolishServerConfig{ -		serverPublicKey, -		serverPrivateKey, -		chunkSize, +		ServerPublicKey:  serverPublicKey, +		ServerPrivateKey: serverPrivateKey, +		ChunkSize:        chunkSize,  	}  	return &silverPolishServerConfig, nil | 
