File: proxy.go

package info (click to toggle)
golang-github-coreos-pkg 3-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 320 kB
  • sloc: sh: 30; makefile: 3
file content (48 lines) | stat: -rw-r--r-- 1,073 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package netutil

import (
	"io"
	"log"
	"net"
	"sync"
	"time"
)

// ProxyTCP proxies between two TCP connections.
// Because TLS connections don't have CloseRead() and CloseWrite() methods, our
// temporary solution is to use timeouts.
func ProxyTCP(conn1, conn2 net.Conn, tlsWriteDeadline, tlsReadDeadline time.Duration) {
	var wg sync.WaitGroup
	wg.Add(2)

	go copyBytes(conn1, conn2, &wg, tlsWriteDeadline, tlsReadDeadline)
	go copyBytes(conn2, conn1, &wg, tlsWriteDeadline, tlsReadDeadline)

	wg.Wait()
	conn1.Close()
	conn2.Close()
}

func copyBytes(dst, src net.Conn, wg *sync.WaitGroup, writeDeadline, readDeadline time.Duration) {
	defer wg.Done()
	_, err := io.Copy(dst, src)
	if err != nil {
		log.Printf("proxy i/o error: %v", err)
	}

	if cr, ok := src.(*net.TCPConn); ok {
		cr.CloseRead()
	} else {
		// For TLS connections.
		wto := time.Now().Add(writeDeadline)
		src.SetWriteDeadline(wto)
	}

	if cw, ok := dst.(*net.TCPConn); ok {
		cw.CloseWrite()
	} else {
		// For TLS connections.
		rto := time.Now().Add(readDeadline)
		dst.SetReadDeadline(rto)
	}
}