diff --git a/client/client.go b/client/client.go index 101acd8..07e04ed 100644 --- a/client/client.go +++ b/client/client.go @@ -7,7 +7,7 @@ import ( "github.com/genshen/wssocks/wss" "github.com/genshen/wssocks/wss/ticker" "github.com/gorilla/websocket" - "log" + log "github.com/sirupsen/logrus" "net/http" "net/url" "time" @@ -61,7 +61,9 @@ func (c *client) PreRun() error { func (c *client) Run() error { // start websocket connection (to remote server). - log.Println("connecting to ", c.remoteUrl.String()) + log.WithFields(log.Fields{ + "remote": c.remoteUrl.String(), + }).Info("connecting to wssocks server.") dialer := websocket.DefaultDialer wsHeader := make(http.Header) // header in websocket request(default is nil) @@ -78,28 +80,32 @@ func (c *client) Run() error { if err != nil { log.Fatal("establishing connection error:", err) } - log.Println("connected to ", c.remoteUrl.String()) + log.WithFields(log.Fields{ + "remote": c.remoteUrl.String(), + }).Info("connected to wssocks server.") // todo chan for wsc and tcp accept defer wsc.WSClose() // negotiate version if version, err := wss.ExchangeVersion(wsc.WsConn); err != nil { - log.Println("server version {version code:", version.VersionCode, - ", version number:", version.Version, - ", update address:", version.UpdateAddr, "}") + log.WithFields(log.Fields{ + "version code": version.VersionCode, + "version number:": version.Version, + "update address": version.UpdateAddr, + }).Info("server version") return err } // start websocket message listen. go func() { if err := wsc.ListenIncomeMsg(); err != nil { - log.Println("error websocket read:", err) + log.Error("error websocket read:", err) } }() // send heart beats. go func() { if err := wsc.HeartBeat(); err != nil { - log.Println("heartbeat ending", err) + log.Info("heartbeat ending", err) } }() diff --git a/client/client_plugin.go b/client/client_plugin.go index b9da565..ac4d7c4 100644 --- a/client/client_plugin.go +++ b/client/client_plugin.go @@ -2,7 +2,7 @@ package client import ( "github.com/gorilla/websocket" - "log" + log "github.com/sirupsen/logrus" "net/http" "net/url" ) diff --git a/go.mod b/go.mod index 830fa38..7be9f6d 100644 --- a/go.mod +++ b/go.mod @@ -6,4 +6,5 @@ require ( github.com/genshen/cmds v0.0.0-20190410131841-986519260a65 github.com/gorilla/websocket v1.4.0 github.com/segmentio/ksuid v1.0.2 + github.com/sirupsen/logrus v1.4.2 ) diff --git a/go.sum b/go.sum index 5a4f9d1..899fa08 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,17 @@ +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/genshen/cmds v0.0.0-20190410131841-986519260a65 h1:RYKhlk6k5qpQBZVaSi+azOINxxJRujYMGHVAdMstw+o= github.com/genshen/cmds v0.0.0-20190410131841-986519260a65/go.mod h1:Uo2P6VGNS7t++sjm8vO2AqK/AB2v/favOgOZB984Z3o= github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gosuri/uilive v0.0.3 h1:kvo6aB3pez9Wbudij8srWo4iY6SFTTxTKOkb+uRCE8I= +github.com/gosuri/uilive v0.0.3/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/segmentio/ksuid v1.0.2 h1:9yBfKyw4ECGTdALaF09Snw3sLJmYIX6AbPJrAy6MrDc= github.com/segmentio/ksuid v1.0.2/go.mod h1:BXuJDr2byAiHuQaQtSKoXh1J0YmUDurywOXgB2w+OSU= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/main.go b/main.go index be33f1b..df1347e 100644 --- a/main.go +++ b/main.go @@ -5,9 +5,13 @@ import ( _ "github.com/genshen/wssocks/client" _ "github.com/genshen/wssocks/server" _ "github.com/genshen/wssocks/version" - "log" + log "github.com/sirupsen/logrus" ) +func init() { + log.SetLevel(log.TraceLevel) +} + func main() { cmds.SetProgramName("wssocks") if err := cmds.Parse(); err != nil { diff --git a/server/server.go b/server/server.go index 5f3e5dd..e83baaa 100644 --- a/server/server.go +++ b/server/server.go @@ -4,7 +4,7 @@ import ( "flag" "github.com/genshen/cmds" "github.com/genshen/wssocks/wss" - "log" + log "github.com/sirupsen/logrus" "net/http" "time" ) @@ -46,7 +46,9 @@ func (s *server) Run() error { // new time ticker to flush data into websocket (to client). http.HandleFunc("/", wss.ServeWs) - log.Println("listening on ", s.address) + log.WithFields(log.Fields{ + "listen address": s.address, + }).Info("listening on income message.") log.Fatal(http.ListenAndServe(s.address, nil)) return nil } diff --git a/wss/proxy_client.go b/wss/proxy_client.go index 8821ee0..9c915ac 100644 --- a/wss/proxy_client.go +++ b/wss/proxy_client.go @@ -2,11 +2,12 @@ package wss import ( "encoding/base64" + "github.com/genshen/wssocks/wss/term_view" "github.com/genshen/wssocks/wss/ticker" "github.com/gorilla/websocket" "github.com/segmentio/ksuid" + log "github.com/sirupsen/logrus" "io" - "log" "net" ) @@ -21,7 +22,7 @@ type ProxyClient struct { func (p *ProxyClient) DispatchData(data *ProxyData) error { // decode base64 if decodeBytes, err := base64.StdEncoding.DecodeString(data.DataBase64); err != nil { // todo ignore error - log.Println("base64 decode error,", err) + log.Error("base64 decode error,", err) return err // skip error } else { // just write data back @@ -44,17 +45,16 @@ func (p *ProxyClient) Close() { // handel socket dial results processing // copy income connection data to proxy serve via websocket -func (p *ProxyClient) Serve(wsc *WebSocketClient, tick *ticker.Ticker, addr string) error { - log.Println("dialing to", addr) - defer log.Println("closing", addr) +func (p *ProxyClient) Serve(plog *term_view.ProgressLog, wsc *WebSocketClient, tick *ticker.Ticker, addr string) error { + plog.Update(term_view.Status{IsNew: true, Address: addr}) + defer plog.Update(term_view.Status{IsNew: false, Address: addr}) defer wsc.Close(p.Id) addrSend := WebSocketMessage{Type: WsTpEst, Id: p.Id.String(), Data: ProxyEstMessage{Addr: addr}} if err := wsc.WriteWSJSON(&addrSend); err != nil { - log.Println("json error:",err) + log.Error("json error:", err) return err } - log.Println("connected to", addr) if tick != nil { var buffer Base64WSBufferWriter @@ -64,12 +64,12 @@ func (p *ProxyClient) Serve(wsc *WebSocketClient, tick *ticker.Ticker, addr stri tick.Append(ticker.TickId(p.Id), func() { // fixme return error _, err := buffer.Flush(websocket.TextMessage, p.Id, &(wsc.ConcurrentWebSocket)) if err != nil { - log.Println("write:", err) // todo use of closed network connection + log.Error("write error:", err) // todo use of closed network connection } }) // todo p.id if _, err := io.Copy(&buffer, p.Conn); err != nil { // copy data to buffer - log.Println("io copy error,", err) + log.Error("io copy error,", err) return nil } } else { @@ -81,7 +81,7 @@ func (p *ProxyClient) Serve(wsc *WebSocketClient, tick *ticker.Ticker, addr stri // log.Println("read error:", err) } else if n > 0 { if err := wsc.WriteProxyMessage(p.Id, buffer[:n]); err != nil { - log.Println("write:", err) + log.Error("write error:", err) break } } diff --git a/wss/proxy_server.go b/wss/proxy_server.go index 5fe8b6c..4db93c6 100644 --- a/wss/proxy_server.go +++ b/wss/proxy_server.go @@ -7,8 +7,8 @@ import ( "github.com/genshen/wssocks/wss/ticker" "github.com/gorilla/websocket" "github.com/segmentio/ksuid" + log "github.com/sirupsen/logrus" "io" - "log" "net" "sync" "time" @@ -131,11 +131,11 @@ func (s *ServerWS) dispatchMessage(data []byte) error { return err } else { go func() { - log.Println("info", "proxy to:", proxyEstMsg.Addr) + log.WithField("address", proxyEstMsg.Addr).Info("proxy connecting to remote") if err := s.establish(id, proxyEstMsg.Addr); err != nil { - log.Println(err) // todo error handle better way + log.Error(err) // todo error handle better way } - log.Println("info", "disconnected to:", proxyEstMsg.Addr) + log.WithField("address", proxyEstMsg.Addr).Info("disconnected to remote") s.tellClosed(id) // tell client to close connection. }() } @@ -149,7 +149,7 @@ func (s *ServerWS) dispatchMessage(data []byte) error { //go func() { // write income data from websocket to TCP connection if decodeBytes, err := base64.StdEncoding.DecodeString(requestMsg.DataBase64); err != nil { - log.Println("base64 decode error,", err) + log.Error("base64 decode error,", err) return err } else { if _, err := connector.Conn.Write(decodeBytes); err != nil { @@ -186,7 +186,7 @@ func (s *ServerWS) establish(id ksuid.KSUID, addr string) error { proxyServerTicker.Append(ticker.TickId(id), func() { // fixme return error if _, err := sendBuffer.Flush(websocket.TextMessage, id, &(s.ConcurrentWebSocket)); err != nil { - log.Println("Error: error sending data via webSocket:", err) + log.Error("error sending data via webSocket:", err) return } }) diff --git a/wss/term_view/log.go b/wss/term_view/log.go new file mode 100644 index 0000000..9900441 --- /dev/null +++ b/wss/term_view/log.go @@ -0,0 +1,102 @@ +package term_view + +import ( + "fmt" + "github.com/sirupsen/logrus" + "log" + "sync" +) + +type Status struct { + Address string + IsNew bool +} +type ProgressLog struct { + ConnSize uint // size of current connections + Address map[string]uint // current requests as well as its count + log *logrus.Logger + Writer *Writer // terminal writer todo defer Flush + mtx *sync.Mutex +} + +func NewPLog() *ProgressLog { + plog := ProgressLog{ + ConnSize: 0, + Address: map[string]uint{}, + mtx: &sync.Mutex{}, + } + plog.Writer = NewWriter() + plog.log = logrus.New() + plog.log.SetOutput(plog.Writer) // use terminal writer + plog.log.SetFormatter(&logrus.TextFormatter{ForceColors: true}) // use colorful log + plog.log.SetLevel(logrus.TraceLevel) + return &plog +} + +func (p *ProgressLog) Update(status Status) { + p.mtx.Lock() + defer p.mtx.Unlock() + if status.IsNew { + p.ConnSize++ + if size, ok := p.Address[status.Address]; ok { + p.Address[status.Address] = size + 1 + } else { + p.Address[status.Address] = 1 + } + } else { + p.ConnSize-- + if size, ok := p.Address[status.Address]; ok && size > 0 { + if size-1 == 0 { + delete(p.Address, status.Address); + } else { + p.Address[status.Address] = size - 1 + } + } else { + log.Fatal("bad connection size") + } + } + // update log + p.setLogBuffer() // call Writer.Write() to set log data into buffer + p.Writer.Flush(nil) // flush buffer +} + +// update progress log. +func (p *ProgressLog) setLogBuffer() { + _, terminalRows := getTermSize() + // log size is ok for terminal (at least one row) + p.log.WithField("size", p.ConnSize).Trace("size of proxy connection(s).") + terminalRows-- + recordsWritten := 0 + if terminalRows >= 2 { // at least 2 lines left: one for show more records and one for new line(\n). + // have rows left + for k, v := range p.Address { + if terminalRows <= 2 { + // hide left records + p.Writer.Write([]byte(fmt.Sprintf("more: %d record(s) hiden.\n", len(p.Address)-recordsWritten))) + break + } else { + p.log.WithFields(logrus.Fields{ + "address": k, + "size": v, + }).Info("connection size to remote proxy server.") + terminalRows-- + recordsWritten++ + } + } + } +} + +// write buffer data directly to stdout. +func (p *ProgressLog) Write(buf [] byte) (int, error) { + p.mtx.Lock() + defer p.mtx.Unlock() + + p.setLogBuffer() // call Writer.Write() to set log data into buffer + err := p.Writer.Flush(func() error { // flush buffer + if _, err := p.Writer.OutDev.Write(buf); err != nil { // just write buff to stdout, and keep progress log. + return err + } + return nil + }) + return len(buf), err +} diff --git a/wss/term_view/terminal_size.go b/wss/term_view/terminal_size.go new file mode 100644 index 0000000..0c9f370 --- /dev/null +++ b/wss/term_view/terminal_size.go @@ -0,0 +1,41 @@ +// this file is copied from https://github.com/gosuri/uilive + +// +build !windows + +package term_view + +import ( + "os" + "runtime" + "syscall" + "unsafe" +) + +type windowSize struct { + rows uint16 + cols uint16 + xPixels uint16 + yPixels uint16 +} + +var out *os.File +var err error +var sz windowSize + +func getTermSize() (int, int) { + if runtime.GOOS == "openbsd" { + out, err = os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + return 0, 0 + } + + } else { + out, err = os.OpenFile("/dev/tty", os.O_WRONLY, 0) + if err != nil { + return 0, 0 + } + } + _, _, _ = syscall.Syscall(syscall.SYS_IOCTL, + out.Fd(), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&sz))) + return int(sz.cols), int(sz.rows) +} diff --git a/wss/term_view/terminal_size_windows.go b/wss/term_view/terminal_size_windows.go new file mode 100644 index 0000000..3a07701 --- /dev/null +++ b/wss/term_view/terminal_size_windows.go @@ -0,0 +1,66 @@ +// this file is copied from https://github.com/gosuri/uilive + +// +build windows + +package term_view + +import ( + "math" + "syscall" + "unsafe" +) + + +type consoleFontInfo struct { + font uint32 + fontSize coord +} + +const ( + SmCxMin = 28 + SmCyMin = 29 +) + +var ( + tmpConsoleFontInfo consoleFontInfo + moduleUser32 = syscall.NewLazyDLL("user32.dll") + procGetCurrentConsoleFont = kernel32.NewProc("GetCurrentConsoleFont") + getSystemMetrics = moduleUser32.NewProc("GetSystemMetrics") +) + +func getCurrentConsoleFont(h syscall.Handle, info *consoleFontInfo) (err error) { + r0, _, e1 := syscall.Syscall( + procGetCurrentConsoleFont.Addr(), 3, uintptr(h), 0, uintptr(unsafe.Pointer(info)), + ) + if int(r0) == 0 { + if e1 != 0 { + err = error(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func getTermSize() (int, int) { + out, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0) + if err != nil { + return 0, 0 + } + + x, _, err := getSystemMetrics.Call(SmCxMin) + y, _, err := getSystemMetrics.Call(SmCyMin) + + if x == 0 || y == 0 { + if err != nil { + panic(err) + } + } + + err = getCurrentConsoleFont(out, &tmpConsoleFontInfo) + if err != nil { + panic(err) + } + + return int(math.Ceil(float64(x) / float64(tmpConsoleFontInfo.fontSize.x))), int(math.Ceil(float64(y) / float64(tmpConsoleFontInfo.fontSize.y))) +} diff --git a/wss/term_view/writer.go b/wss/term_view/writer.go new file mode 100644 index 0000000..6361377 --- /dev/null +++ b/wss/term_view/writer.go @@ -0,0 +1,77 @@ +// most code in this sub-package is copy or modified from https://github.com/gosuri/uilive + +package term_view + +import ( + "bytes" + "io" + "os" + "sync" +) + +// Writer will updates the terminal when flush is called. +type Writer struct { + OutDev io.Writer + buf bytes.Buffer + mtx *sync.Mutex + lineCount int // lines have wrote to terminal. +} + +// NewWriter returns a new Writer with default values +func NewWriter() *Writer { + return &Writer{ + OutDev: os.Stdout, + mtx: &sync.Mutex{}, + lineCount: 0, + } +} + +// Write write contents to the writer's io writer. +func (w *Writer) NormalWrite(buf []byte) (n int, err error) { + w.mtx.Lock() + w.clearLines() // clean progress lines first + defer w.mtx.Unlock() + return w.OutDev.Write(buf) +} + +func (w *Writer) Write(buf []byte) (n int, err error) { + w.mtx.Lock() + defer w.mtx.Unlock() + return w.buf.Write(buf) +} + +// Flush writes to the out and resets the buffer. +func (w *Writer) Flush(onLinesCleared func() error) error { + w.mtx.Lock() + defer w.mtx.Unlock() + + if len(w.buf.Bytes()) == 0 { + return nil + } + w.clearLines() + if onLinesCleared != nil { + if err := onLinesCleared(); err != nil { // callback if lines is cleared. + return err + } + } + + lines := 0 + var currentLine bytes.Buffer + for _, b := range w.buf.Bytes() { + if b == '\n' { + lines++ + currentLine.Reset() + } else { + currentLine.Write([]byte{b}) + // todo windows overflow + //if overFlowHandled && currentLine.Len() > termWidth { + // lines++ + // currentLine.Reset() + //} + } + } + w.lineCount = lines + _, err := w.OutDev.Write(w.buf.Bytes()) + w.buf.Reset() + return err +} diff --git a/wss/term_view/writer_unix.go b/wss/term_view/writer_unix.go new file mode 100644 index 0000000..12d79df --- /dev/null +++ b/wss/term_view/writer_unix.go @@ -0,0 +1,18 @@ +// +build !windows + +package term_view + +import ( + "fmt" + "strings" +) + +// ESC is the ASCII code for escape character +const ESC = 27 + +// clear the line and move the cursor up +var clear = fmt.Sprintf("%c[%dA%c[2K", ESC, 1, ESC) + +func (w *Writer) clearLines() { + _, _ = fmt.Fprint(w.OutDev, strings.Repeat(clear, w.lineCount)) +} diff --git a/wss/term_view/writer_windows.go b/wss/term_view/writer_windows.go new file mode 100644 index 0000000..347ed43 --- /dev/null +++ b/wss/term_view/writer_windows.go @@ -0,0 +1,75 @@ +// file is copied from: https://github.com/gosuri/uilive/blob/master/writer_windows.go + +// +build windows + +package term_view + +import ( + "fmt" + "strings" + "syscall" + "unsafe" +) + +var kernel32 = syscall.NewLazyDLL("kernel32.dll") + +var ( + procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") + procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") + procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") +) + +// clear the line and move the cursor up +var clear = fmt.Sprintf("%c[%dA%c[2K\r", ESC, 0, ESC) + +type short int16 +type dword uint32 +type word uint16 + +type coord struct { + x short + y short +} + +type smallRect struct { + left short + top short + right short + bottom short +} + +type consoleScreenBufferInfo struct { + size coord + cursorPosition coord + attributes word + window smallRect + maximumWindowSize coord +} + +func (w *Writer) clearLines() { + f, ok := w.Out.(FdWriter) + if ok && !isatty.IsTerminal(f.Fd()) { + ok = false + } + if !ok { + _, _ = fmt.Fprint(w.Out, strings.Repeat(clear, w.lineCount)) + return + } + fd := f.Fd() + var csbi consoleScreenBufferInfo + _, _, _ = procGetConsoleScreenBufferInfo.Call(fd, uintptr(unsafe.Pointer(&csbi))) + + for i := 0; i < w.lineCount; i++ { + // move the cursor up + csbi.cursorPosition.y-- + _, _, _ = procSetConsoleCursorPosition.Call(fd, uintptr(*(*int32)(unsafe.Pointer(&csbi.cursorPosition)))) + // clear the line + cursor := coord{ + x: csbi.window.left, + y: csbi.window.top + csbi.cursorPosition.y, + } + var count, w dword + count = dword(csbi.size.x) + _, _, _ = procFillConsoleOutputCharacter.Call(fd, uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&w))) + } +} diff --git a/wss/websocket.go b/wss/websocket.go index e4048a6..b29c88c 100644 --- a/wss/websocket.go +++ b/wss/websocket.go @@ -2,7 +2,7 @@ package wss import ( "github.com/gorilla/websocket" - "log" + log "github.com/sirupsen/logrus" "net/http" ) @@ -13,16 +13,16 @@ var upgrader = websocket.Upgrader{} // use default options func ServeWs(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { - log.Println(err) + log.Error(err) return } if _, ok := err.(websocket.HandshakeError); ok { http.Error(w, "Not a websocket handshake", 400) - log.Println("Error: Not a websocket handshake", 400) + log.Error("Not a websocket handshake", 400) return } else if err != nil { http.Error(w, "Cannot setup WebSocket connection:", 400) - log.Println("Error: Cannot setup WebSocket connection:", err) + log.Error("Cannot setup WebSocket connection:", err) return } defer ws.Close() @@ -35,17 +35,17 @@ func ServeWs(w http.ResponseWriter, r *http.Request) { sws := NewServerWS(ws) // read messages from webSocket for { - log.Println("conn size: ", sws.GetConnectorSize()) + log.WithField("size", sws.GetConnectorSize()).Trace("connection size changed.") _, p, err := ws.ReadMessage() // if WebSocket is closed by some reason, then this func will return, // and 'done' channel will be set, the outer func will reach to the end. // then ssh session will be closed in defer. if err != nil { - log.Println("Error: error reading webSocket message:", err) + log.Error("error reading webSocket message:", err) break } if err = sws.dispatchMessage(p); err != nil { - log.Println("Error: error proxy:", err) + log.Error("error proxy:", err) // break skip error } } diff --git a/wss/wssocks.go b/wss/wssocks.go index 8c6263f..7341d32 100644 --- a/wss/wssocks.go +++ b/wss/wssocks.go @@ -1,8 +1,9 @@ package wss import ( + "github.com/genshen/wssocks/wss/term_view" "github.com/genshen/wssocks/wss/ticker" - "log" + log "github.com/sirupsen/logrus" "net" ) @@ -12,17 +13,22 @@ func ListenAndServe(wsc *WebSocketClient, tick *ticker.Ticker, address string) e if err != nil { return err } + log.WithField("local address", address).Info("listening on local address for incoming proxy request.") + + plog := term_view.NewPLog() + log.SetOutput(plog) // change log stdout to plog + var client Client for { - log.Println("size of connector:", wsc.ConnSize()) c, err := s.Accept() if err != nil { return nil } + go func() { err := client.Reply(c, func(conn *net.TCPConn, addr string) error { proxy := wsc.NewProxy(conn) - proxy.Serve(wsc, tick, addr) + proxy.Serve(plog, wsc, tick, addr) wsc.TellClose(proxy.Id) return nil // todo error })