frpc: add support for connecting server through http proxies, see #67

This commit is contained in:
fatedier
2016-08-15 00:55:22 +08:00
parent 47c1a3e52c
commit e262ac6abd
6 changed files with 72 additions and 6 deletions

View File

@@ -16,9 +16,12 @@ package conn
import (
"bufio"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
@@ -104,9 +107,9 @@ func NewConn(conn net.Conn) (c *Conn) {
return c
}
func ConnectServer(host string, port int64) (c *Conn, err error) {
func ConnectServer(addr string) (c *Conn, err error) {
c = &Conn{}
servertAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", host, port))
servertAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return
}
@@ -120,6 +123,49 @@ func ConnectServer(host string, port int64) (c *Conn, err error) {
return c, nil
}
func ConnectServerByHttpProxy(httpProxy string, serverAddr string) (c *Conn, err error) {
var proxyUrl *url.URL
if proxyUrl, err = url.Parse(httpProxy); err != nil {
return
}
var proxyAuth string
if proxyUrl.User != nil {
proxyAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(proxyUrl.User.String()))
}
if proxyUrl.Scheme != "http" {
err = fmt.Errorf("Proxy URL scheme must be http, not [%s]", proxyUrl.Scheme)
return
}
if c, err = ConnectServer(proxyUrl.Host); err != nil {
return
}
req, err := http.NewRequest("CONNECT", "https://"+serverAddr, nil)
if err != nil {
return
}
if proxyAuth != "" {
req.Header.Set("Proxy-Authorization", proxyAuth)
}
req.Header.Set("User-Agent", "Mozilla/5.0")
req.Write(c.TcpConn)
resp, err := http.ReadResponse(bufio.NewReader(c), req)
if err != nil {
return
}
resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("ConnectServer using proxy error, StatusCode [%d]", resp.StatusCode)
return
}
return
}
// if the tcpConn is different with c.TcpConn
// you should call c.Close() first
func (c *Conn) SetTcpConn(tcpConn net.Conn) {