-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
208 lines (160 loc) · 4.12 KB
/
main.go
File metadata and controls
208 lines (160 loc) · 4.12 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"sync/atomic"
"time"
"github.com/jinzhu/gorm"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
db, err := NewPostgreSQL()
if err != nil {
log.Fatalln("can not connect to postgres:", err)
}
defer db.Close()
ips := make(chan string, 200)
sem := make(chan bool, 200)
go cleaner(ips)
go getProxyUrl(ips, db)
server := NewServer(port, ips, sem)
log.Println("server start on port:", port)
log.Fatal(server.ListenAndServe())
}
func cleaner(ips chan string) {
ticker := time.NewTicker(time.Second * 10)
defer ticker.Stop()
for range ticker.C {
<-ips
log.Println("cleaner TICK")
}
}
func handleTunneling(w http.ResponseWriter, r *http.Request, ips chan string, sem chan bool) {
defer func() {
<-sem
}()
var counter uint64
dest_conn, err := dialCoordinatorViaCONNECT(r.Host, ips, &counter)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
client_conn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
go transfer(dest_conn, client_conn)
go transfer(client_conn, dest_conn)
}
func transfer(destination io.WriteCloser, source io.ReadCloser) {
defer destination.Close()
defer source.Close()
if _, err := io.Copy(destination, source); err != nil {
log.Println(err)
}
}
func dialCoordinatorViaCONNECT(addr string, ips chan string, counter *uint64) (net.Conn, error) {
if *counter > 5 {
err := fmt.Sprintf("error with max counter retry for: %s", addr)
log.Printf(err)
return nil, fmt.Errorf("error with max counter retry for: %s", addr)
}
atomic.AddUint64(counter, 1)
proxyAddr := <-ips
log.Printf("dialing proxy %q to remote: %s", proxyAddr, addr)
c, err := net.DialTimeout("tcp", proxyAddr, time.Second*10)
if err != nil {
log.Printf("Try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
if err = c.SetReadDeadline(time.Now().Add(time.Second * 15)); err != nil {
c.Close()
log.Printf("Try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
_, err = fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", addr, addr)
if err != nil {
c.Close()
log.Printf("Try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
br := bufio.NewReader(c)
res, err := http.ReadResponse(br, nil)
if err != nil {
c.Close()
log.Printf("Try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
if res.StatusCode != http.StatusOK {
c.Close()
log.Printf("Try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
if br.Buffered() > 0 {
c.Close()
log.Printf("unexpected %d bytes of buffered data from CONNECT proxy %q", br.Buffered(), proxyAddr)
log.Printf("try again for %s ...", addr)
return dialCoordinatorViaCONNECT(addr, ips, counter)
}
return c, nil
}
func handleHTTP(w http.ResponseWriter, req *http.Request, ips chan string, sem chan bool) {
defer func() {
<-sem
}()
execHandleHTTP(w, req, ips)
}
func execHandleHTTP(w http.ResponseWriter, req *http.Request, ips chan string) {
proxyUrl, err := url.Parse(fmt.Sprintf("http://%s", <-ips))
if err != nil {
log.Println(err)
return
}
myClient := &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
resp, err := myClient.RoundTrip(req)
if err != nil {
execHandleHTTP(w, req, ips)
}
defer resp.Body.Close()
copyHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
log.Println(err)
}
}
func copyHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
func getProxyUrl(ips chan string, db *gorm.DB) {
for {
proxies := []*Proxy{}
db.Table("proxies").
Select("content").
Order("score desc").
Limit(200).
Find(&proxies)
for _, proxy := range proxies {
ips <- proxy.Content
}
}
}