Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
darren committed Feb 1, 2019
0 parents commit 2fd013e
Show file tree
Hide file tree
Showing 5 changed files with 221 additions and 0 deletions.
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2019 Darren Hoo

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 changes: 27 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## pacroxy


pacproxy is a proxy that parses pac file and start a simple http proxy which will forward http requests to proxies in pac


## Install

Ensure that `Go` enviroment has been properly setup.

```bash
go get -u -v github.com/darren/pacroxy
```


## Usage

```
pacroxy -p wpad.dat -l 127.0.0.1:9999
curl -x 127.0.0.1:9999 https://example.com
```

## Note

This is a simple tool still in development, use at your own risk.


3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/darren/pacroxy

require github.com/darren/gpac v0.0.0-20190201203621-687614ea7470
6 changes: 6 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
github.com/darren/gpac v0.0.0-20190201203621-687614ea7470 h1:liq6Kzh6QchRPvsAKmIG/QPrHc0bSntrXFM2eBWkRxo=
github.com/darren/gpac v0.0.0-20190201203621-687614ea7470/go.mod h1:fK76ZiaaM0f4rW2A3sTomlo/wlY9jRV07KJ66DbOAXs=
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d h1:1VUlQbCfkoSGv7qP7Y+ro3ap1P1pPZxgdGVqiTVy5C4=
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY=
gopkg.in/sourcemap.v1 v1.0.5 h1:inv58fC9f9J3TK2Y2R1NPntXEn3/wjWHkonhIUODNTI=
gopkg.in/sourcemap.v1 v1.0.5/go.mod h1:2RlvNNSMglmRrcvhfuzp4hQHwOtjxlbjX7UPY/GXb78=
178 changes: 178 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package main

import (
"context"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"

"github.com/darren/gpac"
)

var scripts = `
function FindProxyForURL(url, host) {
if (host == "www.baidu.com") return "DIRECT";
if (isPlainHostName(host)) return "DIRECT";
else return "PROXY 10.0.1.254:8080; PROXY 127.0.0.1:8080; DIRECT";
}
`

var pacfile = flag.String("p", "wpad.dat", "pac file to load")
var addr = flag.String("l", "127.0.0.1:8080", "Listening address")

// Server the proxy server
type Server struct {
http.Server
pac *gpac.Parser
}

func (s *Server) handle(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
s.handleTunneling(w, r)
} else {
s.handleHTTP(w, r)
}
}

type peekedConn struct {
net.Conn
r io.Reader
}

// concat combine conn and peeked buffer
func combine(peeked io.Reader, conn net.Conn) *peekedConn {
r := io.MultiReader(peeked, conn)
return &peekedConn{conn, r}
}

func (p *peekedConn) Read(data []byte) (int, error) {
return p.r.Read(data)
}

func (s *Server) handleTunneling(w http.ResponseWriter, r *http.Request) {
host, _, _ := net.SplitHostPort(r.Host)
url := fmt.Sprintf("https://%s/", host)

proxies, err := s.pac.FindProxy(url)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}

ctx := context.Background()

var dst net.Conn
var proxy *gpac.Proxy

for _, proxy = range proxies {
dialer := proxy.Dialer()
dst, err = dialer(ctx, "tcp", r.Host)
if err != nil {
log.Println("Dial failed:", err)
continue
} else {
break
}
}

if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}

if proxy == nil {
http.Error(w, "No Proxy Available", http.StatusServiceUnavailable)
return
}

if proxy.IsDirect() {
w.WriteHeader(http.StatusOK)
}

hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "Hijacking not supported", http.StatusInternalServerError)
return
}
src, buf, err := hijacker.Hijack()

if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}

src = combine(buf, src)

go transfer(dst, src)
go transfer(src, dst)

log.Printf("[%s] %s %v [%v]", r.RemoteAddr, r.Method, url, proxy)
}

func transfer(destination io.WriteCloser, source io.ReadCloser) {
defer destination.Close()
defer source.Close()
io.Copy(destination, source)
}

func (s *Server) handleHTTP(w http.ResponseWriter, req *http.Request) {
proxies, err := s.pac.FindProxy(req.URL.String())
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}

req.RequestURI = ""

for _, proxy := range proxies {
resp, err := proxy.Do(req)
if err != nil {
continue
}

defer resp.Body.Close()
cloneHeader(w.Header(), resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)

log.Printf("[%s] %s %v [%v]", req.RemoteAddr, req.Method, req.URL, proxy)

if err == nil {
return
}
}

log.Printf("[%s] %s %v FAILED", req.RemoteAddr, req.Method, req.URL)
http.Error(w, "No Proxy Available", http.StatusServiceUnavailable)
}

func cloneHeader(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}

func main() {
flag.Parse()

log.Printf("Loading pac from %s", *pacfile)
pac, err := gpac.From(*pacfile)
if err != nil {
log.Fatal(err)
}

log.Printf("Start proxy on %s", *addr)
server := Server{
Server: http.Server{
Addr: *addr,
},
pac: pac,
}

server.Handler = http.HandlerFunc(server.handle)
log.Fatal(server.ListenAndServe())
}

0 comments on commit 2fd013e

Please sign in to comment.