Ejemplo n.º 1
0
func main() {
	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*baidu.com$"))).
		HandleConnect(goproxy.AlwaysReject)
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
		HandleConnect(goproxy.AlwaysMitm)
	// enable curl -p for all hosts on port 80
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := net.Dial("tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)
				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})
	proxy.Verbose = true
	log.Fatal(http.ListenAndServe(":8080", proxy))
}
Ejemplo n.º 2
0
func main() {

	var templateFilePath string
	if len(os.Args) == 1 {
		templateFilePath = "./template.html"
	} else if len(os.Args) == 2 {
		templateFilePath = os.Args[1]
	} else {
		panic("Unknown number of arguments. Please enter a template file")
	}

	content, err := ioutil.ReadFile(templateFilePath)
	if err != nil {
		panic(err)
	}

	var htmlStr string = string(content)

	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).HandleConnect(goproxy.AlwaysMitm)
	proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		return req, goproxy.NewResponse(req, goproxy.ContentTypeHtml, http.StatusForbidden, htmlStr)
	})

	log.Fatalln(http.ListenAndServe(":8401", proxy))
}
Ejemplo n.º 3
0
func main() {
	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
		HandleConnect(goproxy.AlwaysMitm)
	proxy.Verbose = true
	log.Fatal(http.ListenAndServe(":8080", proxy))
}
Ejemplo n.º 4
0
func main() {
	// read the config file
	var configfile string
	flag.StringVar(&configfile, "config", "./config.json", "JSON config file")
	flag.Parse()

	file, err := ioutil.ReadFile(configfile)
	if err != nil {
		log.Fatal(err)
	}

	f := ConfigData{}
	err = json.Unmarshal(file, &f)
	if err != nil {
		log.Fatal(err)
	}

	SUBMIT_URL = f.SubmitURL

	var host_blacklist = readFileToRegexpList(f.DomainBlacklistFile)
	var full_blacklist = readFileToRegexpList(f.FullBlacklistFile)
	var path_suffix_blacklist = []string{}

	content, err := ioutil.ReadFile(f.SuffixBlacklistFile)
	if err == nil {
		for _, line := range strings.Split(string(content), "\n") {
			if line != "" {
				path_suffix_blacklist = append(path_suffix_blacklist, line)
			}
		}
	}

	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = false
	proxy.OnResponse(
		StatusIs(200),
		TextButNotCode(),
		goproxy.Not(UrlSuffixMatches(path_suffix_blacklist...)),
		goproxy.Not(goproxy.ReqHostMatches(host_blacklist...)),
		goproxy.Not(UrlMatchesAny(full_blacklist...)),
	).DoFunc(SaveCopyToHarken)
	log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", f.Port), proxy))
}
Ejemplo n.º 5
0
func main() {
	verbose := flag.Bool("v", true, "should every proxy request be logged to stdout")
	http_addr := flag.String("httpaddr", ":3129", "proxy http listen address")
	https_addr := flag.String("httpsaddr", ":3128", "proxy https listen address")
	flag.Parse()

	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = *verbose
	if proxy.Verbose {
		log.Printf("Server starting up! - configured to listen on http interface %s and https interface %s", *http_addr, *https_addr)
	}

	proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.Host == "" {
			fmt.Fprintln(w, "Cannot handle requests without Host header, e.g., HTTP 1.0")
			return
		}
		req.URL.Scheme = "http"
		req.URL.Host = req.Host
		proxy.ServeHTTP(w, req)
	})
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
		HandleConnect(goproxy.AlwaysMitm)
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := connectDial(proxy, "tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)
				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})

	go func() {
		log.Fatalln(http.ListenAndServe(*http_addr, proxy))
	}()

	// listen to the TLS ClientHello but make it a CONNECT request instead
	ln, err := net.Listen("tcp", *https_addr)
	if err != nil {
		log.Fatalf("Error listening for https connections - %v", err)
	}
	for {
		c, err := ln.Accept()
		if err != nil {
			log.Printf("Error accepting new connection - %v", err)
			continue
		}
		go func(c net.Conn) {
			tlsConn, err := vhost.TLS(c)
			if err != nil {
				log.Printf("Error accepting new connection - %v", err)
			}
			if tlsConn.Host() == "" {
				log.Printf("Cannot support non-SNI enabled clients")
				return
			}
			connectReq := &http.Request{
				Method: "CONNECT",
				URL: &url.URL{
					Opaque: tlsConn.Host(),
					Host:   net.JoinHostPort(tlsConn.Host(), "443"),
				},
				Host:   tlsConn.Host(),
				Header: make(http.Header),
			}
			resp := dumbResponseWriter{tlsConn}
			proxy.ServeHTTP(resp, connectReq)
		}(c)
	}
}
Ejemplo n.º 6
0
func main() {
	verbose := flag.Bool("v", false, "proxy log info to stdout")
	addr := flag.String("l", ":9010", "proxy listen addr")
	debug = flag.Bool("d", false, "open the debug mode")
	//fmt.Printf("v1 type :%s\n", reflect.TypeOf(debug))
	flag.Usage = func() {
		p("================By b0lu===============")
		p("usage:  " + string(os.Args[0]) + " -v -l :9010 -d")
		p("-d	open then debug mode")
		p("-v	open proxy log info to stdout")
		p("-l	set the proxy listen addr and port. default: -l :9010")
		p("\nPS: proxy will log requests info into qproxylog file")
	}
	flag.Parse()

	defer func() {
		if err := recover(); err != nil {
			p(err)
		}
	}()

	p("================By b0lu===============")
	p("Load config.ini to init allowHostsRule and staticResourcesRules")
	cfg, err := goconfig.LoadConfigFile("config.ini")
	if err != nil {
		log.Println("读取配置文件失败[config.ini]")
		return
	}
	allowHostsRule, err := cfg.GetValue(goconfig.DEFAULT_SECTION, "allowHostsRule")
	check(err)
	p("allowHostsRule==>", allowHostsRule)
	allowRules := make([]*regexp.Regexp, 0)

	for _, hostRule := range strings.Split(allowHostsRule, ",") {
		allowRules = append(allowRules, regexp.MustCompile(hostRule))

	}
	p(allowRules)

	staticResources, err := cfg.GetValue(goconfig.DEFAULT_SECTION, "staticResources")
	check(err)
	p("staticResources==>", staticResources)
	staticResourcesRules := regexp.MustCompile(staticResources)
	p(staticResourcesRules)

	httpHandler, err := NewHttpHandle()
	check(err)
	proxy := goproxy.NewProxyHttpServer()

	proxy.Verbose = *verbose
	/*
		if err := os.MkdirAll("proxydump", 0755); err != nil {
			log.Fatal("Cant create dir", err)
		}
	*/
	proxy.OnRequest(goproxy.ReqHostMatches(allowRules...)).
		DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			if !staticResourcesRules.MatchString(req.URL.Path) {
				httpHandler.PutRequest(req)
			}
			return req, nil
		})
	p("----------------------Proxy Start------------------------")
	http.ListenAndServe(*addr, proxy)

}
Ejemplo n.º 7
0
// getNewHoverfly returns a configured ProxyHttpServer and DBClient, also starts admin interface on configured port
func getNewHoverfly(cfg *Configuration) (*goproxy.ProxyHttpServer, DBClient) {

	// getting boltDB
	db := getDB(cfg.databaseName)

	cache := Cache{
		db:             db,
		requestsBucket: []byte(requestsBucketName),
	}

	// getting connections
	d := DBClient{
		cache: cache,
		http:  &http.Client{},
		cfg:   cfg,
	}

	// creating proxy
	proxy := goproxy.NewProxyHttpServer()

	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(d.cfg.destination))).
		HandleConnect(goproxy.AlwaysMitm)

	// enable curl -p for all hosts on port 80
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(d.cfg.destination))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := net.Dial("tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)

				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})

	// processing connections
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(cfg.destination))).DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			return d.processRequest(r)
		})

	go d.startAdminInterface()

	proxy.Verbose = d.cfg.verbose
	// proxy starting message
	log.WithFields(log.Fields{
		"Destination": d.cfg.destination,
		"ProxyPort":   d.cfg.proxyPort,
		"Mode":        d.cfg.GetMode(),
	}).Info("Proxy prepared...")

	return proxy, d
}
Ejemplo n.º 8
0
func main() {
	proxy := goproxy.NewProxyHttpServer()
	proxy.Verbose = true
	proxy.NonproxyHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		w.Header().Set("Content-Type", "multipart/form-data")
		w.Header().Set("Content-Disposition:", "attachment;filename=\""+"shiningbt.mobileconfig\"")
		// req.URL, _ = url.Parse("/shiningbt.mobileconfig")
		w.Write([]byte(mobileconfigContent))
		// http.FileServer(http.Dir(".")).ServeHTTP(w, req)
	})

	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*[universe.walkrgame.com|api.walkrhub.com|api.walkrconnect.com].*$"))).HandleConnect(goproxy.AlwaysMitm)
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*[universe.walkrgame.com|api.walkrhub.com|api.walkrconnect.com].*$"))).DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		req.Header.Add("Cache-Control", "no-cache,no-store")
		req.Header.Add("Pragma", "no-cache")
		req.Header.Del("If-None-Match")
		return req, nil
	})
	proxy.OnResponse(goproxy.UrlMatches(regexp.MustCompile("^.*v1/pilots?.*$"))).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
		if body, err := ioutil.ReadAll(resp.Body); err == nil {
			var record PilotListResponse
			if err := json.Unmarshal([]byte(body), &record); err == nil {
				for index, _ := range record.Pilots {
					record.Pilots[index].Energy = 60000
				}
				dx, _ := json.Marshal(record)
				resp.Body = ioutil.NopCloser(bytes.NewBuffer(dx))
			} else {
				fmt.Println("Unmarshal Err", err)

			}
		} else {
			fmt.Println("Read body Err", err)
		}

		return resp

	})
	proxy.OnResponse(goproxy.UrlMatches(regexp.MustCompile("^.*v1/pilots/(.*)/check$"))).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
		record := &ConvertedEnergyResponse{Success: true, CheckedEnergy: 60000}
		dx, _ := json.Marshal(record)
		resp.Body = ioutil.NopCloser(bytes.NewBuffer(dx))
		return resp

	})

	// https://universe.walkrgame.com/api/v1/fleets/443091/check_reward
	if EpicHack == true {
		proxy.OnResponse(goproxy.UrlMatches(regexp.MustCompile("^.*v1/fleets/(.*)/check_reward$"))).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
			if body, err := ioutil.ReadAll(resp.Body); err == nil {
				var record CheckEpicRewardResponse
				if err := json.Unmarshal([]byte(body), &record); err == nil {
					record.Data.IsChecked = false
					record.Data.IsFirstTime = false
					// 能量块
					record.Data.Reward.Type = "cubes"
					record.Data.Reward.Value = "60000"
					record.Data.Contribution.Value = 1
					// DFR
					// record.Data.Reward.Type = "replicator"
					// record.Data.Reward.Value = fmt.Sprintf("map-%v", rand.New(rand.NewSource(time.Now().UnixNano())).Intn(100)+210000)
					dx, _ := json.Marshal(record)
					resp.Body = ioutil.NopCloser(bytes.NewBuffer(dx))
				} else {
					fmt.Println("Unmarshal Err", err)

				}
			} else {
				fmt.Println("Read body Err", err)
			}

			return resp

		})
	}

	// 这里应该加一个验证,用来启动或者停止
	authed := false
	currentUUID := strings.Split(uuid.NewUUID().String(), "-")[4]
	md5h := md5.New()
	md5h.Write([]byte(PackageFor + "-" + currentUUID))
	md5str := hex.EncodeToString(md5h.Sum([]byte("")))

	client := &http.Client{}
	v := url.Values{}
	v.Add("u", PackageFor)
	v.Add("id", currentUUID)
	v.Add("md", md5str)
	v.Add("v", Version)

	host := fmt.Sprintf("http://%v:9896/verify?%v", RemoteAddr, v.Encode())
	if req, err := http.NewRequest("GET", host, nil); err != nil {
		fmt.Println(fmt.Sprintf("启动失败: %v", err))
	} else {
		if resp, err := client.Do(req); err != nil {
			fmt.Println(fmt.Sprintf("启动失败: %v", err))
		} else {
			body, err := ioutil.ReadAll(resp.Body)
			if err != nil || string(body) != "1" {
				fmt.Println(fmt.Sprintf("启动失败: %v", string(body)))
			} else {
				authed = true
			}
		}
	}
	if authed == true {
		localIp := "127.0.0.1"
		if conn, err := net.Dial("udp", fmt.Sprintf("%v:9896", RemoteAddr)); err == nil {
			defer conn.Close()
			localIp = strings.Split(conn.LocalAddr().String(), ":")[0]
		} else {

			fmt.Println(err)
		}
		port := 9897

		fmt.Println("你的IP地址是: ", localIp)
		fmt.Println("!!!!!! 第一次使用工具的时候, 请按照[条目0]安装一个描述文件 !!!!!!")
		fmt.Println("0. 在玩儿Walkr的iPad/iPhone上使用Safari打开 [http://" + localIp + ":" + fmt.Sprintf("%v", port) + "], 会提示下载一个描述文件, 一路安装即可")
		fmt.Println("=========================== 无辜的分割线 ===========================")
		fmt.Println("1. 安装之后在Wifi的代理设置为[手动], 服务器地址为 [" + localIp + "], 端口为 [" + fmt.Sprintf("%v", port) + "]")
		fmt.Println("2. 打开游戏进入舰桥, 如果能显示能量并且可以领取, 就说明成功")
		fmt.Println("!!!!!! 不用的时候一定关掉[软件]以及[设备上的代理], 否则可能上不了网 !!!!!!")

		log.Fatal(http.ListenAndServe(":"+fmt.Sprintf("%v", port), proxy))
	} else {
		time.Sleep(5 * time.Second)
	}

}
Ejemplo n.º 9
0
Archivo: main.go Proyecto: rakoo/MMAS
func main() {
	proxy := goproxy.NewProxyHttpServer()

	db, err := sql.Open("sqlite3", "memory")
	if err != nil {
		log.Fatal(err)
	}

	if err = db.Ping(); err != nil {
		log.Fatal(err)
	}

	_, err = db.Exec(`CREATE TABLE IF NOT EXISTS chunks (
		content BLOB,
		hash BLOB UNIQUE ON CONFLICT REPLACE,
		count INTEGER
	);`)
	if err != nil {
		log.Fatal(err)
	}

	bh := &bodyHandler{
		db: db,
	}

	matchPath := regexp.MustCompile("reddit.com")
	proxy.OnResponse(
		goproxy.ContentTypeIs("text/html"),
		goproxy.ReqHostMatches(matchPath),
	).DoFunc(bh.handle)
	proxy.OnResponse(
		goproxy.ReqHostMatches(matchPath),
	).DoFunc(func(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
		r.Header.Set("X-Sdch-Encoding", "0")
		return r
	})
	proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)

	err = os.Mkdir(DICT_PATH, 0755)
	if err != nil && !os.IsExist(err) {
		log.Fatal(err)
	}

	err = os.Mkdir(DICT_HDR_PATH, 0755)
	if err != nil && !os.IsExist(err) {
		log.Fatal(err)
	}

	dir, err := os.Open(DICT_PATH)
	if err != nil {
		log.Fatal(err)
	}
	fis, err := dir.Readdir(-1)
	if err != nil {
		log.Fatal(err)
	}

	if len(fis) > 0 {
		current := fis[0]
		for _, fi := range fis[1:] {
			if fi.ModTime().After(current.ModTime()) {
				err := os.Remove(path.Join(DICT_PATH, fi.Name()))
				if err != nil {
					log.Fatal(err)
				}
				err = os.Remove(path.Join(DICT_HDR_PATH, fi.Name()))
				if err != nil {
					log.Fatal(err)
				}
				current = fi
			}
		}
		bh.SetDictName(path.Join(DICT_PATH, current.Name()))
		bh.SetDictHdrName(path.Join(DICT_HDR_PATH, current.Name()))
	}

	proxy.OnRequest().DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		if !strings.HasPrefix(r.URL.Path, "/_dictionary") {
			return r, nil
		}

		dictQuery := strings.Replace(r.URL.Path, "/_dictionary/", "", 1)
		parts := strings.Split(dictQuery, "/")
		if len(parts) != 2 {
			log.Println("Wrong query:", dictQuery)
			resp := goproxy.NewResponse(r, "text/plain", http.StatusNotFound, http.StatusText(http.StatusNotFound))
			return nil, resp
		}

		dictName := parts[1]

		if dictName != path.Base(bh.DictName()) {
			log.Println(err)
			resp := goproxy.NewResponse(r, "text/plain", http.StatusNotFound, http.StatusText(http.StatusNotFound))
			return nil, resp
		}

		dict, modTime, err := bh.makeSdchDict()
		if err != nil {
			log.Println(err)
			resp := goproxy.NewResponse(r, "text/plain", http.StatusNotFound, http.StatusText(http.StatusNotFound))
			return nil, resp
		}

		size, err1 := dict.Seek(0, os.SEEK_END)
		_, err2 := dict.Seek(0, os.SEEK_SET)
		if err1 != nil || err2 != nil {
			log.Println(err, err2)
			resp := goproxy.NewResponse(r, "text/plain", http.StatusNotFound, http.StatusText(http.StatusNotFound))
			return nil, resp
		}

		resp := &http.Response{}
		resp.Request = r
		resp.TransferEncoding = r.TransferEncoding
		resp.Header = make(http.Header)
		resp.Header.Add("Content-Type", "application/x-sdch-dictionary")
		resp.Header.Add("Content-Length", strconv.Itoa(int(size)))
		resp.Header.Add("X-Sdch-Encode", "0")
		resp.Header.Add("Date", time.Now().Format(time.RFC1123))
		resp.Header.Add("Expires", time.Now().Add(1*time.Hour).Format(time.RFC1123))
		resp.Header.Add("Last-Modified", modTime.Format(time.RFC1123))

		resp.StatusCode = 200
		resp.ContentLength = size
		resp.Body = ioutil.NopCloser(dict)

		log.Println("Sending back dict")
		return nil, resp
	})

	log.Println("Let's go !")
	log.Fatal(http.ListenAndServe(":8080", proxy))
}
Ejemplo n.º 10
0
func main() {
	// getting proxy configuration
	verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
	record := flag.Bool("record", false, "should proxy record")
	destination := flag.String("destination", ".", "destination URI to catch")
	flag.Parse()

	// getting settings
	initSettings()

	// overriding default settings
	AppConfig.recordState = *record

	// overriding destination
	AppConfig.destination = *destination

	// getting default database
	port := os.Getenv("ProxyPort")
	if port == "" {
		port = DefaultPort
	} else {
		port = fmt.Sprintf(":%s", port)
	}

	// Output to stderr instead of stdout, could also be a file.
	log.SetOutput(os.Stderr)
	log.SetFormatter(&log.TextFormatter{})

	redisPool := getRedisPool()
	defer redisPool.Close()

	cache := Cache{pool: redisPool,
		prefix: AppConfig.cachePrefix}

	// getting connections
	d := DBClient{
		cache: cache,
		http:  &http.Client{},
	}

	// creating proxy
	proxy := goproxy.NewProxyHttpServer()

	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
		HandleConnect(goproxy.AlwaysMitm)

	// enable curl -p for all hosts on port 80
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := net.Dial("tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)

				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})

	// just helper handler to know where request hits proxy or no
	proxy.OnRequest().DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			log.WithFields(log.Fields{
				"destination": r.URL.Host,
			}).Info("Got request")

			return r, nil
		})

	// hijacking plain connections
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(*destination))).DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {

			log.Info("connection found......")
			log.Info(fmt.Sprintf("Url path:  %s", r.URL.Path))

			return d.processRequest(r)
		})

	go d.startAdminInterface()

	proxy.Verbose = *verbose

	// proxy starting message
	log.WithFields(log.Fields{
		"RedisAddress": AppConfig.redisAddress,
		"Destination":  *destination,
		"ProxyPort":    port,
	}).Info("Proxy is starting...")

	log.Warn(http.ListenAndServe(port, proxy))
}
Ejemplo n.º 11
0
// GetNewHoverfly returns a configured ProxyHttpServer and DBClient
func GetNewHoverfly(cfg *Configuration, cache Cache) (*goproxy.ProxyHttpServer, DBClient) {

	counter := NewModeCounter()

	// getting connections
	d := DBClient{
		Cache:   cache,
		HTTP:    &http.Client{},
		Cfg:     cfg,
		Counter: counter,
		Hooks:   make(ActionTypeHooks),
	}

	// creating proxy
	proxy := goproxy.NewProxyHttpServer()

	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(d.Cfg.Destination))).
		HandleConnect(goproxy.AlwaysMitm)

	// enable curl -p for all hosts on port 80
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(d.Cfg.Destination))).
		HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
			defer func() {
				if e := recover(); e != nil {
					ctx.Logf("error connecting to remote: %v", e)
					client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
				}
				client.Close()
			}()
			clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
			remote, err := net.Dial("tcp", req.URL.Host)
			orPanic(err)
			remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
			for {
				req, err := http.ReadRequest(clientBuf.Reader)
				orPanic(err)
				orPanic(req.Write(remoteBuf))
				orPanic(remoteBuf.Flush())
				resp, err := http.ReadResponse(remoteBuf.Reader, req)

				orPanic(err)
				orPanic(resp.Write(clientBuf.Writer))
				orPanic(clientBuf.Flush())
			}
		})

	// processing connections
	proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile(cfg.Destination))).DoFunc(
		func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			return d.processRequest(r)
		})

	// intercepts response
	proxy.OnResponse(goproxy.ReqHostMatches(regexp.MustCompile(cfg.Destination))).DoFunc(
		func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
			d.Counter.Count(d.Cfg.GetMode())
			return resp
		})

	proxy.Verbose = d.Cfg.Verbose
	// proxy starting message
	log.WithFields(log.Fields{
		"Destination": d.Cfg.Destination,
		"ProxyPort":   d.Cfg.ProxyPort,
		"Mode":        d.Cfg.GetMode(),
	}).Info("Proxy prepared...")

	return proxy, d
}