| 1 |
/* |
| 2 |
* Copyright (c) 2015, Yawning Angel <yawning at schwanenlied dot me> |
| 3 |
* All rights reserved. |
| 4 |
* |
| 5 |
* Redistribution and use in source and binary forms, with or without |
| 6 |
* modification, are permitted provided that the following conditions are met: |
| 7 |
* |
| 8 |
* * Redistributions of source code must retain the above copyright notice, |
| 9 |
* this list of conditions and the following disclaimer. |
| 10 |
* |
| 11 |
* * Redistributions in binary form must reproduce the above copyright notice, |
| 12 |
* this list of conditions and the following disclaimer in the documentation |
| 13 |
* and/or other materials provided with the distribution. |
| 14 |
* |
| 15 |
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 16 |
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 17 |
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 18 |
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 19 |
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 20 |
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 21 |
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 22 |
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 23 |
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 24 |
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 25 |
* POSSIBILITY OF SUCH DAMAGE. |
| 26 |
*/ |
| 27 |
|
| 28 |
package meeklite |
| 29 |
|
| 30 |
import ( |
| 31 |
"bytes" |
| 32 |
"crypto/rand" |
| 33 |
"crypto/sha256" |
| 34 |
"encoding/hex" |
| 35 |
"errors" |
| 36 |
"fmt" |
| 37 |
"io" |
| 38 |
"io/ioutil" |
| 39 |
"net" |
| 40 |
"net/http" |
| 41 |
gourl "net/url" |
| 42 |
"os" |
| 43 |
"runtime" |
| 44 |
"sync" |
| 45 |
"time" |
| 46 |
|
| 47 |
"git.torproject.org/pluggable-transports/goptlib.git" |
| 48 |
"gitlab.com/yawning/obfs4.git/transports/base" |
| 49 |
) |
| 50 |
|
| 51 |
const ( |
| 52 |
urlArg = "url" |
| 53 |
frontArg = "front" |
| 54 |
|
| 55 |
maxChanBacklog = 16 |
| 56 |
|
| 57 |
// Constants shamelessly stolen from meek-client.go... |
| 58 |
maxPayloadLength = 0x10000 |
| 59 |
initPollInterval = 100 * time.Millisecond |
| 60 |
maxPollInterval = 5 * time.Second |
| 61 |
pollIntervalMultiplier = 1.5 |
| 62 |
maxRetries = 10 |
| 63 |
retryDelay = 30 * time.Second |
| 64 |
) |
| 65 |
|
| 66 |
var ( |
| 67 |
// ErrNotSupported is the error returned for a unsupported operation. |
| 68 |
ErrNotSupported = errors.New("meek_lite: operation not supported") |
| 69 |
|
| 70 |
loopbackAddr = net.IPv4(127, 0, 0, 1) |
| 71 |
) |
| 72 |
|
| 73 |
type meekClientArgs struct { |
| 74 |
url *gourl.URL |
| 75 |
front string |
| 76 |
} |
| 77 |
|
| 78 |
func (ca *meekClientArgs) Network() string { |
| 79 |
return transportName |
| 80 |
} |
| 81 |
|
| 82 |
func (ca *meekClientArgs) String() string { |
| 83 |
return transportName + ":" + ca.front + ":" + ca.url.String() |
| 84 |
} |
| 85 |
|
| 86 |
func newClientArgs(args *pt.Args) (ca *meekClientArgs, err error) { |
| 87 |
ca = &meekClientArgs{} |
| 88 |
|
| 89 |
// Parse the URL argument. |
| 90 |
str, ok := args.Get(urlArg) |
| 91 |
if !ok { |
| 92 |
return nil, fmt.Errorf("missing argument '%s'", urlArg) |
| 93 |
} |
| 94 |
ca.url, err = gourl.Parse(str) |
| 95 |
if err != nil { |
| 96 |
return nil, fmt.Errorf("malformed url: '%s'", str) |
| 97 |
} |
| 98 |
switch ca.url.Scheme { |
| 99 |
case "http", "https": |
| 100 |
default: |
| 101 |
return nil, fmt.Errorf("invalid scheme: '%s'", ca.url.Scheme) |
| 102 |
} |
| 103 |
|
| 104 |
// Parse the (optional) front argument. |
| 105 |
ca.front, _ = args.Get(frontArg) |
| 106 |
|
| 107 |
return ca, nil |
| 108 |
} |
| 109 |
|
| 110 |
type meekConn struct { |
| 111 |
args *meekClientArgs |
| 112 |
sessionID string |
| 113 |
transport *http.Transport |
| 114 |
|
| 115 |
closeOnce sync.Once |
| 116 |
workerWrChan chan []byte |
| 117 |
workerRdChan chan []byte |
| 118 |
workerCloseChan chan struct{} |
| 119 |
rdBuf *bytes.Buffer |
| 120 |
} |
| 121 |
|
| 122 |
func (c *meekConn) Read(p []byte) (n int, err error) { |
| 123 |
// If there is data left over from the previous read, |
| 124 |
// service the request using the buffered data. |
| 125 |
if c.rdBuf != nil { |
| 126 |
if c.rdBuf.Len() == 0 { |
| 127 |
panic("empty read buffer") |
| 128 |
} |
| 129 |
n, err = c.rdBuf.Read(p) |
| 130 |
if c.rdBuf.Len() == 0 { |
| 131 |
c.rdBuf = nil |
| 132 |
} |
| 133 |
return |
| 134 |
} |
| 135 |
|
| 136 |
// Wait for the worker to enqueue more incoming data. |
| 137 |
b, ok := <-c.workerRdChan |
| 138 |
if !ok { |
| 139 |
// Close() was called and the worker's shutting down. |
| 140 |
return 0, io.ErrClosedPipe |
| 141 |
} |
| 142 |
|
| 143 |
// Ew, an extra copy, but who am I kidding, it's meek. |
| 144 |
buf := bytes.NewBuffer(b) |
| 145 |
n, err = buf.Read(p) |
| 146 |
if buf.Len() > 0 { |
| 147 |
// If there's data pending, stash the buffer so the next |
| 148 |
// Read() call will use it to fulfuill the Read(). |
| 149 |
c.rdBuf = buf |
| 150 |
} |
| 151 |
return |
| 152 |
} |
| 153 |
|
| 154 |
func (c *meekConn) Write(b []byte) (n int, err error) { |
| 155 |
// Check to see if the connection is actually open. |
| 156 |
select { |
| 157 |
case <-c.workerCloseChan: |
| 158 |
return 0, io.ErrClosedPipe |
| 159 |
default: |
| 160 |
} |
| 161 |
|
| 162 |
if len(b) == 0 { |
| 163 |
return 0, nil |
| 164 |
} |
| 165 |
|
| 166 |
// Copy the data to be written to a new slice, since |
| 167 |
// we return immediately after queuing and the peer can |
| 168 |
// happily reuse `b` before data has been sent. |
| 169 |
b2 := append([]byte{}, b...) |
| 170 |
if ok := c.enqueueWrite(b2); !ok { |
| 171 |
// Technically we did enqueue data, but the worker's |
| 172 |
// got closed out from under us. |
| 173 |
return 0, io.ErrClosedPipe |
| 174 |
} |
| 175 |
runtime.Gosched() |
| 176 |
return len(b), nil |
| 177 |
} |
| 178 |
|
| 179 |
func (c *meekConn) Close() error { |
| 180 |
err := os.ErrClosed |
| 181 |
|
| 182 |
c.closeOnce.Do(func() { |
| 183 |
// Tear down the worker, if it is still running. |
| 184 |
close(c.workerCloseChan) |
| 185 |
err = nil |
| 186 |
}) |
| 187 |
|
| 188 |
return err |
| 189 |
} |
| 190 |
|
| 191 |
func (c *meekConn) LocalAddr() net.Addr { |
| 192 |
return &net.IPAddr{IP: loopbackAddr} |
| 193 |
} |
| 194 |
|
| 195 |
func (c *meekConn) RemoteAddr() net.Addr { |
| 196 |
return c.args |
| 197 |
} |
| 198 |
|
| 199 |
func (c *meekConn) SetDeadline(t time.Time) error { |
| 200 |
return ErrNotSupported |
| 201 |
} |
| 202 |
|
| 203 |
func (c *meekConn) SetReadDeadline(t time.Time) error { |
| 204 |
return ErrNotSupported |
| 205 |
} |
| 206 |
|
| 207 |
func (c *meekConn) SetWriteDeadline(t time.Time) error { |
| 208 |
return ErrNotSupported |
| 209 |
} |
| 210 |
|
| 211 |
func (c *meekConn) enqueueWrite(b []byte) (ok bool) { |
| 212 |
defer func() { |
| 213 |
if err := recover(); err != nil { |
| 214 |
ok = false |
| 215 |
} |
| 216 |
}() |
| 217 |
c.workerWrChan <- b |
| 218 |
return true |
| 219 |
} |
| 220 |
|
| 221 |
func (c *meekConn) roundTrip(sndBuf []byte) (recvBuf []byte, err error) { |
| 222 |
var req *http.Request |
| 223 |
var resp *http.Response |
| 224 |
|
| 225 |
for retries := 0; retries < maxRetries; retries++ { |
| 226 |
url := *c.args.url |
| 227 |
host := url.Host |
| 228 |
if c.args.front != "" { |
| 229 |
url.Host = c.args.front |
| 230 |
} |
| 231 |
var body io.Reader |
| 232 |
if len(sndBuf) > 0 { |
| 233 |
body = bytes.NewReader(sndBuf) |
| 234 |
} |
| 235 |
req, err = http.NewRequest("POST", url.String(), body) |
| 236 |
if err != nil { |
| 237 |
return nil, err |
| 238 |
} |
| 239 |
if c.args.front != "" { |
| 240 |
req.Host = host |
| 241 |
} |
| 242 |
req.Header.Set("X-Session-Id", c.sessionID) |
| 243 |
req.Header.Set("User-Agent", "") |
| 244 |
|
| 245 |
resp, err = c.transport.RoundTrip(req) |
| 246 |
if err != nil { |
| 247 |
return nil, err |
| 248 |
} |
| 249 |
|
| 250 |
if resp.StatusCode == http.StatusOK { |
| 251 |
recvBuf, err = ioutil.ReadAll(io.LimitReader(resp.Body, maxPayloadLength)) |
| 252 |
resp.Body.Close() |
| 253 |
return |
| 254 |
} |
| 255 |
|
| 256 |
resp.Body.Close() |
| 257 |
err = fmt.Errorf("status code was %d, not %d", resp.StatusCode, http.StatusOK) |
| 258 |
time.Sleep(retryDelay) |
| 259 |
} |
| 260 |
return |
| 261 |
} |
| 262 |
|
| 263 |
func (c *meekConn) ioWorker() { |
| 264 |
interval := initPollInterval |
| 265 |
var sndBuf, leftBuf []byte |
| 266 |
|
| 267 |
loop: |
| 268 |
for { |
| 269 |
sndBuf = nil |
| 270 |
select { |
| 271 |
case <-time.After(interval): |
| 272 |
// If the poll interval has elapsed, issue a request. |
| 273 |
case sndBuf = <-c.workerWrChan: |
| 274 |
// If there is data pending a send, issue a request. |
| 275 |
case <-c.workerCloseChan: |
| 276 |
break loop |
| 277 |
} |
| 278 |
|
| 279 |
// Combine short writes as long as data is available to be |
| 280 |
// sent immediately and it will not put us over the max |
| 281 |
// payload limit. Any excess data is stored and dispatched |
| 282 |
// as the next request). |
| 283 |
sndBuf = append(leftBuf, sndBuf...) |
| 284 |
wrSz := len(sndBuf) |
| 285 |
for len(c.workerWrChan) > 0 && wrSz < maxPayloadLength { |
| 286 |
b := <-c.workerWrChan |
| 287 |
sndBuf = append(sndBuf, b...) |
| 288 |
wrSz = len(sndBuf) |
| 289 |
} |
| 290 |
if wrSz > maxPayloadLength { |
| 291 |
wrSz = maxPayloadLength |
| 292 |
} |
| 293 |
|
| 294 |
// Issue a request. |
| 295 |
rdBuf, err := c.roundTrip(sndBuf[:wrSz]) |
| 296 |
if err != nil { |
| 297 |
// Welp, something went horrifically wrong. |
| 298 |
break loop |
| 299 |
} |
| 300 |
|
| 301 |
// Stash the remaining payload if any. |
| 302 |
leftBuf = sndBuf[wrSz:] // Store the remaining data |
| 303 |
if len(leftBuf) == 0 { |
| 304 |
leftBuf = nil |
| 305 |
} |
| 306 |
|
| 307 |
// Determine the next poll interval. |
| 308 |
if len(rdBuf) > 0 { |
| 309 |
// Received data, enqueue the read. |
| 310 |
c.workerRdChan <- rdBuf |
| 311 |
|
| 312 |
// And poll immediately. |
| 313 |
interval = 0 |
| 314 |
} else if wrSz > 0 { |
| 315 |
// Sent data, poll immediately. |
| 316 |
interval = 0 |
| 317 |
} else if interval == 0 { |
| 318 |
// Neither sent nor received data after a poll, re-initialize the delay. |
| 319 |
interval = initPollInterval |
| 320 |
} else { |
| 321 |
// Apply a multiplicative backoff. |
| 322 |
interval = time.Duration(float64(interval) * pollIntervalMultiplier) |
| 323 |
if interval > maxPollInterval { |
| 324 |
interval = maxPollInterval |
| 325 |
} |
| 326 |
} |
| 327 |
|
| 328 |
runtime.Gosched() |
| 329 |
} |
| 330 |
|
| 331 |
// Unblock callers waiting in Read() for data that will never arrive, |
| 332 |
// and callers waiting in Write() for data that will never get sent. |
| 333 |
close(c.workerRdChan) |
| 334 |
close(c.workerWrChan) |
| 335 |
|
| 336 |
// Close the connection (extra calls to Close() are harmless). |
| 337 |
_ = c.Close() |
| 338 |
} |
| 339 |
|
| 340 |
func newMeekConn(network, addr string, dialFn base.DialFunc, ca *meekClientArgs) (net.Conn, error) { |
| 341 |
id, err := newSessionID() |
| 342 |
if err != nil { |
| 343 |
return nil, err |
| 344 |
} |
| 345 |
|
| 346 |
conn := &meekConn{ |
| 347 |
args: ca, |
| 348 |
sessionID: id, |
| 349 |
transport: &http.Transport{Dial: dialFn}, |
| 350 |
workerWrChan: make(chan []byte, maxChanBacklog), |
| 351 |
workerRdChan: make(chan []byte, maxChanBacklog), |
| 352 |
workerCloseChan: make(chan struct{}), |
| 353 |
} |
| 354 |
|
| 355 |
// Start the I/O worker. |
| 356 |
go conn.ioWorker() |
| 357 |
|
| 358 |
return conn, nil |
| 359 |
} |
| 360 |
|
| 361 |
func newSessionID() (string, error) { |
| 362 |
var b [64]byte |
| 363 |
if _, err := rand.Read(b[:]); err != nil { |
| 364 |
return "", err |
| 365 |
} |
| 366 |
h := sha256.Sum256(b[:]) |
| 367 |
return hex.EncodeToString(h[:16]), nil |
| 368 |
} |
| 369 |
|
| 370 |
var ( |
| 371 |
_ net.Conn = (*meekConn)(nil) |
| 372 |
_ net.Addr = (*meekClientArgs)(nil) |
| 373 |
) |