upstreamproxy.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "net"
  23. "net/http"
  24. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  25. "golang.org/x/net/proxy"
  26. )
  27. type DialFunc func(string, string) (net.Conn, error)
  28. type Error struct {
  29. error
  30. }
  31. func proxyError(err error) error {
  32. // Avoid multiple upstream.Error wrapping
  33. if _, ok := err.(*Error); ok {
  34. return err
  35. }
  36. return &Error{error: fmt.Errorf("upstreamproxy error: %s", err)}
  37. }
  38. type UpstreamProxyConfig struct {
  39. ForwardDialFunc DialFunc
  40. ProxyURIString string
  41. CustomHeaders http.Header
  42. }
  43. // Dial implements the proxy.Dialer interface, allowing a UpstreamProxyConfig
  44. // to be passed to proxy.FromURL.
  45. func (u *UpstreamProxyConfig) Dial(network, addr string) (net.Conn, error) {
  46. return u.ForwardDialFunc(network, addr)
  47. }
  48. func NewProxyDialFunc(config *UpstreamProxyConfig) DialFunc {
  49. if config.ProxyURIString == "" {
  50. return config.ForwardDialFunc
  51. }
  52. proxyURI, err := common.SafeParseURL(config.ProxyURIString)
  53. if err != nil {
  54. return func(network, addr string) (net.Conn, error) {
  55. return nil, proxyError(fmt.Errorf("NewProxyDialFunc: SafeParseURL failed: %v", err))
  56. }
  57. }
  58. dialer, err := proxy.FromURL(proxyURI, config)
  59. if err != nil {
  60. return func(network, addr string) (net.Conn, error) {
  61. return nil, proxyError(fmt.Errorf("NewProxyDialFunc: proxy.FromURL: %v", err))
  62. }
  63. }
  64. return dialer.Dial
  65. }