upstreamproxy.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2015, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package upstreamproxy
  20. import (
  21. "fmt"
  22. "golang.org/x/net/proxy"
  23. "net"
  24. "net/url"
  25. )
  26. type DialFunc func(string, string) (net.Conn, error)
  27. type Error struct {
  28. error
  29. }
  30. func proxyError(err error) error {
  31. // Avoid multiple upstream.Error wrapping
  32. if _, ok := err.(*Error); ok {
  33. return err
  34. }
  35. return &Error{error: fmt.Errorf("upstreamproxy error: %s", err)}
  36. }
  37. type UpstreamProxyConfig struct {
  38. ForwardDialFunc DialFunc
  39. ProxyURIString string
  40. }
  41. // UpstreamProxyConfig implements proxy.Dialer interface
  42. // so we can pass it to proxy.FromURL
  43. func (u *UpstreamProxyConfig) Dial(network, addr string) (net.Conn, error) {
  44. return u.ForwardDialFunc(network, addr)
  45. }
  46. func NewProxyDialFunc(config *UpstreamProxyConfig) DialFunc {
  47. if config.ProxyURIString == "" {
  48. return config.ForwardDialFunc
  49. }
  50. proxyURI, err := url.Parse(config.ProxyURIString)
  51. if err != nil {
  52. return func(network, addr string) (net.Conn, error) {
  53. return nil, proxyError(fmt.Errorf("proxyURI url.Parse: %v", err))
  54. }
  55. }
  56. dialer, err := proxy.FromURL(proxyURI, config)
  57. if err != nil {
  58. return func(network, addr string) (net.Conn, error) {
  59. return nil, proxyError(fmt.Errorf("proxy.FromURL: %v", err))
  60. }
  61. }
  62. return dialer.Dial
  63. }