├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── auth.go ├── dialer.go └── test ├── grpc_e2e_test.go ├── testdata ├── ca.pem ├── server1.key └── server1.pem └── testproto ├── Makefile ├── impl.go ├── test.pb.go └── test.proto /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Go template 3 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 4 | *.o 5 | *.a 6 | *.so 7 | 8 | # Folders 9 | _obj 10 | _test 11 | 12 | # Architecture specific extensions/prefixes 13 | *.[568vq] 14 | [568vq].out 15 | 16 | *.cgo1.go 17 | *.cgo2.c 18 | _cgo_defun.c 19 | _cgo_gotypes.go 20 | _cgo_export.* 21 | 22 | _testmain.go 23 | 24 | *.exe 25 | *.test 26 | *.prof 27 | ### Windows template 28 | # Windows image file caches 29 | Thumbs.db 30 | ehthumbs.db 31 | 32 | # Folder config file 33 | Desktop.ini 34 | 35 | # Recycle Bin used on file shares 36 | $RECYCLE.BIN/ 37 | 38 | # Windows Installer files 39 | *.cab 40 | *.msi 41 | *.msm 42 | *.msp 43 | 44 | # Windows shortcuts 45 | *.lnk 46 | ### Kate template 47 | # Swap Files # 48 | .*.kate-swp 49 | .swp.* 50 | ### SublimeText template 51 | # cache files for sublime text 52 | *.tmlanguage.cache 53 | *.tmPreferences.cache 54 | *.stTheme.cache 55 | 56 | # workspace files are user-specific 57 | *.sublime-workspace 58 | 59 | # project files should be checked into the repository, unless a significant 60 | # proportion of contributors will probably not be using SublimeText 61 | # *.sublime-project 62 | 63 | # sftp configuration file 64 | sftp-config.json 65 | ### Linux template 66 | *~ 67 | 68 | # temporary files which can be created if a process still has a handle open of a deleted file 69 | .fuse_hidden* 70 | 71 | # KDE directory preferences 72 | .directory 73 | 74 | # Linux trash folder which might appear on any partition or disk 75 | .Trash-* 76 | ### JetBrains template 77 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 78 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 79 | 80 | # User-specific stuff: 81 | .idea 82 | .idea/tasks.xml 83 | .idea/dictionaries 84 | .idea/vcs.xml 85 | .idea/jsLibraryMappings.xml 86 | 87 | # Sensitive or high-churn files: 88 | .idea/dataSources.ids 89 | .idea/dataSources.xml 90 | .idea/dataSources.local.xml 91 | .idea/sqlDataSources.xml 92 | .idea/dynamic.xml 93 | .idea/uiDesigner.xml 94 | 95 | # Gradle: 96 | .idea/gradle.xml 97 | .idea/libraries 98 | 99 | # Mongo Explorer plugin: 100 | .idea/mongoSettings.xml 101 | 102 | ## File-based project format: 103 | *.iws 104 | 105 | ## Plugin-specific files: 106 | 107 | # IntelliJ 108 | /out/ 109 | 110 | # mpeltonen/sbt-idea plugin 111 | .idea_modules/ 112 | 113 | # JIRA plugin 114 | atlassian-ide-plugin.xml 115 | 116 | # Crashlytics plugin (for Android Studio and IntelliJ) 117 | com_crashlytics_export_strings.xml 118 | crashlytics.properties 119 | crashlytics-build.properties 120 | fabric.properties 121 | ### Xcode template 122 | # Xcode 123 | # 124 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 125 | 126 | ## Build generated 127 | build/ 128 | DerivedData/ 129 | 130 | ## Various settings 131 | *.pbxuser 132 | !default.pbxuser 133 | *.mode1v3 134 | !default.mode1v3 135 | *.mode2v3 136 | !default.mode2v3 137 | *.perspectivev3 138 | !default.perspectivev3 139 | xcuserdata/ 140 | 141 | ## Other 142 | *.moved-aside 143 | *.xccheckout 144 | *.xcscmblueprint 145 | ### Eclipse template 146 | 147 | .metadata 148 | bin/ 149 | tmp/ 150 | *.tmp 151 | *.bak 152 | *.swp 153 | *~.nib 154 | local.properties 155 | .settings/ 156 | .loadpath 157 | .recommenders 158 | 159 | # Eclipse Core 160 | .project 161 | 162 | # External tool builders 163 | .externalToolBuilders/ 164 | 165 | # Locally stored "Eclipse launch configurations" 166 | *.launch 167 | 168 | # PyDev specific (Python IDE for Eclipse) 169 | *.pydevproject 170 | 171 | # CDT-specific (C/C++ Development Tooling) 172 | .cproject 173 | 174 | # JDT-specific (Eclipse Java Development Tools) 175 | .classpath 176 | 177 | # Java annotation processor (APT) 178 | .factorypath 179 | 180 | # PDT-specific (PHP Development Tools) 181 | .buildpath 182 | 183 | # sbteclipse plugin 184 | .target 185 | 186 | # Tern plugin 187 | .tern-project 188 | 189 | # TeXlipse plugin 190 | .texlipse 191 | 192 | # STS (Spring Tool Suite) 193 | .springBeans 194 | 195 | # Code Recommenders 196 | .recommenders/ 197 | 198 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | 4 | go: 5 | - 1.7 6 | 7 | install: 8 | - go get google.golang.org/grpc 9 | - go get golang.org/x/net/context 10 | - go get github.com/stretchr/testify 11 | - go get github.com/elazarl/goproxy 12 | 13 | script: 14 | - go test -race -v ./... 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HTTP CONNECT tunneling Go Dialer 2 | 3 | [![Travis Build](https://travis-ci.org/mwitkow/go-http-dialer.svg)](https://travis-ci.org/mwitkow/go-http-dialer) 4 | [![Go Report Card](https://goreportcard.com/badge/github.com/mwitkow/go-http-dialer)](http://goreportcard.com/report/mwitkow/go-http-dialer) 5 | [![GoDoc](http://img.shields.io/badge/GoDoc-Reference-blue.svg)](https://godoc.org/github.com/mwitkow/go-http-dialer) 6 | [![Apache 2.0 License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) 7 | 8 | A `net.Dialer` drop-in that establishes the TCP connection over an [HTTP CONNECT Tunnel](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling). 9 | 10 | ## Why?! 11 | 12 | Some enterprises have fairly restrictive networking environments. They typically operate [HTTP forward proxies](https://en.wikipedia.org/wiki/Proxy_server) that require user authentication. These proxies usually allow HTTPS (TCP to `:443`) to pass through the proxy using the [`CONNECT`](https://tools.ietf.org/html/rfc2616#section-9.9) method. The `CONNECT` method is basically a HTTP-negotiated "end-to-end" TCP stream... which is exactly what [`net.Conn`](https://golang.org/pkg/net/#Conn) is :) 13 | 14 | ## But, really, why? 15 | 16 | Because if you want to call [gRPC](http://www.grpc.io/) services which are exposed publicly over `:443` TLS over an HTTP proxy, you can't. 17 | 18 | Also, this allows you to call any TCP service over HTTP `CONNECT`... if your proxy allows you to `¯\(ツ)/¯` 19 | 20 | ## Supported features 21 | 22 | - [x] unencrypted connection to proxy (e.g. `http://proxy.example.com:3128` 23 | - [x] TLS connection to proxy (customizeable) (e.g. `https://proxy.example.com`) 24 | - [x] customizeable for `Proxy-Authenticate`, with challenge-response semantics 25 | - [x] out of the box support for `Basic` auth 26 | - [ ] appropriate `RemoteAddr` remapping 27 | 28 | 29 | ## Usage with gRPC 30 | 31 | 32 | 33 | ## License 34 | 35 | `go-http-dialer` is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details. 36 | -------------------------------------------------------------------------------- /auth.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 | // See LICENSE for licensing terms. 3 | 4 | package http_dialer 5 | 6 | import "encoding/base64" 7 | 8 | const ( 9 | hdrProxyAuthResp = "Proxy-Authorization" 10 | hdrProxyAuthReq = "Proxy-Authenticate" 11 | ) 12 | 13 | // ProxyAuthorization allows for plugging in arbitrary implementations of the "Proxy-Authorization" handler. 14 | type ProxyAuthorization interface { 15 | // Type represents what kind of Authorization, e.g. "Bearer", "Token", "Digest". 16 | Type() string 17 | 18 | // Initial allows you to specify an a-priori "Proxy-Authenticate" response header, attached to first request, 19 | // so you don't need to wait for an additional challenge. If empty string is returned, "Proxy-Authenticate" 20 | // header is added. 21 | InitialResponse() string 22 | 23 | // ChallengeResponse returns the content of the "Proxy-Authenticate" response header, that has been chose as 24 | // response to "Proxy-Authorization" request header challenge. 25 | ChallengeResponse(challenge string) string 26 | } 27 | 28 | type basicAuth struct { 29 | username string 30 | password string 31 | } 32 | 33 | // AuthBasic returns a ProxyAuthorization that implements "Basic" protocol while ignoring realm challanges. 34 | func AuthBasic(username string, password string) ProxyAuthorization { 35 | return &basicAuth{username: username, password: password} 36 | } 37 | 38 | func (b *basicAuth) Type() string { 39 | return "Basic" 40 | } 41 | 42 | func (b *basicAuth) InitialResponse() string { 43 | return b.authString() 44 | } 45 | 46 | func (b *basicAuth) ChallengeResponse(challenge string) string { 47 | // challenge can be realm="proxy.com" 48 | // TODO(mwitkow): Implement realm lookup in AuthBasicWithRealm. 49 | return b.authString() 50 | } 51 | 52 | func (b *basicAuth) authString() string { 53 | resp := b.username + ":" + b.password 54 | return base64.StdEncoding.EncodeToString([]byte(resp)) 55 | } 56 | -------------------------------------------------------------------------------- /dialer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 | // See LICENSE for licensing terms. 3 | 4 | // Package http_dialer provides HTTP(S) CONNECT tunneling net.Dialer. It allows you to 5 | // establish arbitrary TCP connections (as long as your proxy allows them) through a HTTP(S) CONNECT point. 6 | package http_dialer 7 | 8 | import ( 9 | "bufio" 10 | "crypto/tls" 11 | "fmt" 12 | "net" 13 | "net/http" 14 | "net/url" 15 | "strings" 16 | "time" 17 | ) 18 | 19 | type opt func(*HttpTunnel) 20 | 21 | // New constructs an HttpTunnel to be used a net.Dial command. 22 | // The first parameter is a proxy URL, for example https://foo.example.com:9090 will use foo.example.com as proxy on 23 | // port 9090 using TLS for connectivity. 24 | // Optional customization parameters are available, e.g.: WithTls, WithDialer, WithConnectionTimeout 25 | func New(proxyUrl *url.URL, opts ...opt) *HttpTunnel { 26 | t := &HttpTunnel{ 27 | parentDialer: &net.Dialer{}, 28 | } 29 | t.parseProxyUrl(proxyUrl) 30 | for _, opt := range opts { 31 | opt(t) 32 | } 33 | return t 34 | } 35 | 36 | // WithTls sets the tls.Config to be used (e.g. CA certs) when connecting to an HTTP proxy over TLS. 37 | func WithTls(tlsConfig *tls.Config) opt { 38 | return func(t *HttpTunnel) { 39 | t.tlsConfig = tlsConfig 40 | } 41 | } 42 | 43 | // WithDialer allows the customization of the underlying net.Dialer used for establishing TCP connections to the proxy. 44 | func WithDialer(dialer *net.Dialer) opt { 45 | return func(t *HttpTunnel) { 46 | t.parentDialer = dialer 47 | } 48 | } 49 | 50 | // WithConnectionTimeout customizes the underlying net.Dialer.Timeout. 51 | func WithConnectionTimeout(timeout time.Duration) opt { 52 | return func(t *HttpTunnel) { 53 | t.parentDialer.Timeout = timeout 54 | } 55 | } 56 | 57 | // WithProxyAuth allows you to add ProxyAuthorization to calls. 58 | func WithProxyAuth(auth ProxyAuthorization) opt { 59 | return func(t *HttpTunnel) { 60 | t.auth = auth 61 | } 62 | } 63 | 64 | // HttpTunnel represents a configured HTTP Connect Tunnel dialer. 65 | type HttpTunnel struct { 66 | parentDialer *net.Dialer 67 | isTls bool 68 | proxyAddr string 69 | tlsConfig *tls.Config 70 | auth ProxyAuthorization 71 | } 72 | 73 | func (t *HttpTunnel) parseProxyUrl(proxyUrl *url.URL) { 74 | t.proxyAddr = proxyUrl.Host 75 | if strings.ToLower(proxyUrl.Scheme) == "https" { 76 | if !strings.Contains(t.proxyAddr, ":") { 77 | t.proxyAddr = t.proxyAddr + ":443" 78 | } 79 | t.isTls = true 80 | } else { 81 | if !strings.Contains(t.proxyAddr, ":") { 82 | t.proxyAddr = t.proxyAddr + ":8080" 83 | } 84 | t.isTls = false 85 | } 86 | } 87 | 88 | func (t *HttpTunnel) dialProxy() (net.Conn, error) { 89 | if !t.isTls { 90 | return t.parentDialer.Dial("tcp", t.proxyAddr) 91 | } 92 | return tls.DialWithDialer(t.parentDialer, "tcp", t.proxyAddr, t.tlsConfig) 93 | } 94 | 95 | // Dial is an implementation of net.Dialer, and returns a TCP connection handle to the host that HTTP CONNECT reached. 96 | func (t *HttpTunnel) Dial(network string, address string) (net.Conn, error) { 97 | if network != "tcp" { 98 | return nil, fmt.Errorf("network type '%v' unsupported (only 'tcp')", network) 99 | } 100 | conn, err := t.dialProxy() 101 | if err != nil { 102 | return nil, fmt.Errorf("http_tunnel: failed dialing to proxy: %v", err) 103 | } 104 | req := &http.Request{ 105 | Method: "CONNECT", 106 | URL: &url.URL{Opaque: address}, 107 | Host: address, // This is weird 108 | Header: make(http.Header), 109 | } 110 | if t.auth != nil && t.auth.InitialResponse() != "" { 111 | req.Header.Set(hdrProxyAuthResp, t.auth.Type() + " " + t.auth.InitialResponse()) 112 | } 113 | resp, err := t.doRoundtrip(conn, req) 114 | if err != nil { 115 | conn.Close() 116 | return nil, err 117 | } 118 | // Retry request with auth, if available. 119 | if resp.StatusCode == http.StatusProxyAuthRequired && t.auth != nil { 120 | responseHdr, err := t.performAuthChallengeResponse(resp) 121 | if err != nil { 122 | conn.Close() 123 | return nil, err 124 | } 125 | req.Header.Set(hdrProxyAuthResp, t.auth.Type() + " " + responseHdr) 126 | resp, err = t.doRoundtrip(conn, req) 127 | if err != nil { 128 | conn.Close() 129 | return nil, err 130 | } 131 | } 132 | 133 | if resp.StatusCode != 200 { 134 | conn.Close() 135 | return nil, fmt.Errorf("http_tunnel: failed proxying %d: %s", resp.StatusCode, resp.Status) 136 | } 137 | return conn, nil 138 | } 139 | 140 | func (t *HttpTunnel) doRoundtrip(conn net.Conn, req *http.Request) (*http.Response, error) { 141 | if err := req.Write(conn); err != nil { 142 | return nil, fmt.Errorf("http_tunnel: failed writing request: %v", err) 143 | } 144 | // Doesn't matter, discard this bufio. 145 | br := bufio.NewReader(conn) 146 | return http.ReadResponse(br, req) 147 | 148 | } 149 | 150 | func (t *HttpTunnel) performAuthChallengeResponse(resp *http.Response) (string, error) { 151 | respAuthHdr := resp.Header.Get(hdrProxyAuthReq) 152 | if !strings.Contains(respAuthHdr, t.auth.Type() + " ") { 153 | return "", fmt.Errorf("http_tunnel: expected '%v' Proxy authentication, got: '%v'", t.auth.Type(), respAuthHdr) 154 | } 155 | splits := strings.SplitN(respAuthHdr, " ", 2) 156 | challenge := splits[1] 157 | return t.auth.ChallengeResponse(challenge), nil 158 | } -------------------------------------------------------------------------------- /test/grpc_e2e_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 | // See LICENSE for licensing terms. 3 | 4 | package end2end_test 5 | 6 | import ( 7 | "crypto/tls" 8 | "crypto/x509" 9 | "fmt" 10 | "io/ioutil" 11 | "net" 12 | "net/http" 13 | "net/url" 14 | "testing" 15 | "time" 16 | 17 | "encoding/base64" 18 | 19 | "github.com/elazarl/goproxy" 20 | "github.com/mwitkow/go-http-dialer" 21 | "github.com/mwitkow/go-http-dialer/test/testproto" 22 | "github.com/stretchr/testify/require" 23 | "github.com/stretchr/testify/suite" 24 | "golang.org/x/net/context" 25 | "google.golang.org/grpc" 26 | "google.golang.org/grpc/credentials" 27 | ) 28 | 29 | type testAuthHandler func(resp http.ResponseWriter, req *http.Request) bool 30 | 31 | func TestDialerIntegrationTestSuite(t *testing.T) { 32 | suite.Run(t, &DialerIntegrationTestSuite{}) 33 | } 34 | 35 | var ( 36 | expectedUser = "john" 37 | expectedPassword = "bonjovi" 38 | withBasicProxyAuth = http_dialer.WithProxyAuth(http_dialer.AuthBasic(expectedUser, expectedPassword)) 39 | ) 40 | 41 | // expectBasicProxyAuth implements a basic auth check. 42 | func expectBasicProxyAuth(handler http.HandlerFunc) http.HandlerFunc { 43 | return func(resp http.ResponseWriter, req *http.Request) { 44 | expected := base64.StdEncoding.EncodeToString([]byte(expectedUser + ":" + expectedPassword)) 45 | if req.Header.Get("Proxy-Authorization") != "Basic "+expected { 46 | resp.Header().Set("Proxy-Authenticate", `Basic realm="foobar"`) 47 | resp.WriteHeader(http.StatusProxyAuthRequired) 48 | return 49 | } 50 | handler(resp, req) 51 | } 52 | } 53 | 54 | type DialerIntegrationTestSuite struct { 55 | suite.Suite 56 | 57 | grpcListener net.Listener 58 | tlsGrpcListener net.Listener 59 | 60 | grpcServer *grpc.Server 61 | authHandler testAuthHandler 62 | httpProxy *goproxy.ProxyHttpServer 63 | httpProxyListener net.Listener 64 | tlsProxyListener net.Listener 65 | 66 | ctx context.Context 67 | } 68 | 69 | func (s *DialerIntegrationTestSuite) SetupSuite() { 70 | var err error 71 | 72 | // non TLS server 73 | s.grpcListener, err = net.Listen("tcp", "127.0.0.1:0") 74 | require.NoError(s.T(), err, "must be able to allocate a port for grpcListener") 75 | noTlsServer := grpc.NewServer() 76 | mwitkow_testproto.RegisterTestServiceServer(noTlsServer, &mwitkow_testproto.TestService{}) 77 | s.T().Logf("starting grpc.Server at: %v", s.grpcListener.Addr().String()) 78 | go func() { 79 | noTlsServer.Serve(s.grpcListener) 80 | }() 81 | 82 | // TLS server 83 | s.tlsGrpcListener, err = net.Listen("tcp", "127.0.0.1:0") 84 | require.NoError(s.T(), err, "must be able to allocate a port for grpcListener") 85 | tlsServer := grpc.NewServer(grpc.Creds(credentials.NewTLS(serverTlsConfig()))) 86 | mwitkow_testproto.RegisterTestServiceServer(tlsServer, &mwitkow_testproto.TestService{}) 87 | s.T().Logf("starting grpc.Server TLS at: %v", s.tlsGrpcListener.Addr().String()) 88 | go func() { 89 | tlsServer.Serve(s.tlsGrpcListener) 90 | }() 91 | 92 | s.httpProxyListener, err = net.Listen("tcp", "127.0.0.1:0") 93 | require.NoError(s.T(), err, "must be able to allocate a port for httpProxyListener") 94 | s.httpProxy = goproxy.NewProxyHttpServer() 95 | s.httpProxy.OnRequest().HandleConnect(goproxy.FuncHttpsHandler(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) { 96 | fmt.Printf("Got CONNECT Host: %v, URL: %v ReqHost: %v\n", host, ctx.Req.URL.String(), ctx.Req.Host) 97 | return goproxy.OkConnect, host 98 | })) 99 | s.T().Logf("starting http.Proxy at: %v", s.httpProxyListener.Addr().String()) 100 | go func() { 101 | http.Serve(s.httpProxyListener, expectBasicProxyAuth(s.httpProxy.ServeHTTP)) 102 | }() 103 | 104 | s.tlsProxyListener, err = net.Listen("tcp", "127.0.0.1:0") 105 | require.NoError(s.T(), err, "must be able to allocate a port for tlsProxyListener") 106 | s.T().Logf("starting tls http.Proxy at: %v", s.tlsProxyListener.Addr().String()) 107 | go func() { 108 | tlsListener := tls.NewListener(s.tlsProxyListener, serverTlsConfig()) 109 | http.Serve(tlsListener, expectBasicProxyAuth(s.httpProxy.ServeHTTP)) 110 | }() 111 | } 112 | 113 | func (s *DialerIntegrationTestSuite) TearDownSuite() { 114 | if s.grpcListener != nil { 115 | s.T().Logf("stopped grpc.Server at: %v", s.grpcListener.Addr().String()) 116 | s.grpcListener.Close() 117 | } 118 | if s.httpProxyListener != nil { 119 | s.httpProxyListener.Close() 120 | s.T().Logf("stopped httpProxy at: %v", s.httpProxyListener.Addr().String()) 121 | s.httpProxyListener.Close() 122 | } 123 | if s.tlsProxyListener != nil { 124 | s.tlsProxyListener.Close() 125 | s.T().Logf("stopped tls httpProxy at: %v", s.tlsProxyListener.Addr().String()) 126 | s.tlsProxyListener.Close() 127 | } 128 | if s.tlsGrpcListener != nil { 129 | s.T().Logf("stopped tls grpc.Server at: %v", s.grpcListener.Addr().String()) 130 | s.tlsGrpcListener.Close() 131 | } 132 | } 133 | 134 | func (s *DialerIntegrationTestSuite) SetupTest() { 135 | // Make all RPC calls last at most 2 sec, meaning all async issues or deadlock will not kill tests. 136 | s.ctx, _ = context.WithTimeout(context.TODO(), 2*time.Second) 137 | } 138 | 139 | func (s *DialerIntegrationTestSuite) grpcAddr() string { 140 | return s.grpcListener.Addr().String() 141 | } 142 | 143 | func (s *DialerIntegrationTestSuite) grpcTlsAddr() string { 144 | return s.tlsGrpcListener.Addr().String() 145 | } 146 | 147 | func (s *DialerIntegrationTestSuite) proxyUrl() *url.URL { 148 | u, err := url.Parse("http://" + s.httpProxyListener.Addr().String()) 149 | require.NoError(s.T(), err, "failed parsing httpProxyListener into URL") 150 | return u 151 | } 152 | 153 | func (s *DialerIntegrationTestSuite) proxyTlsUrl() *url.URL { 154 | u, err := url.Parse("https://" + s.tlsProxyListener.Addr().String()) 155 | require.NoError(s.T(), err, "failed parsing tlsProxyListener into URL") 156 | return u 157 | } 158 | 159 | func (s *DialerIntegrationTestSuite) Test_DialDirectly() { 160 | client, err := grpc.Dial(s.grpcAddr(), grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(2*time.Second)) 161 | require.NoError(s.T(), err, "must not error on client Dial") 162 | testClient := mwitkow_testproto.NewTestServiceClient(client) 163 | _, err = testClient.PingEmpty(s.ctx, &mwitkow_testproto.Empty{}) 164 | require.NoError(s.T(), err, "empty call must succeed") 165 | } 166 | 167 | func (s *DialerIntegrationTestSuite) Test_NoTls_NoTls() { 168 | dialer := http_dialer.New(s.proxyUrl(), withBasicProxyAuth) 169 | s.grpcCallAndAssert(false, dialer) 170 | } 171 | 172 | func (s *DialerIntegrationTestSuite) Test_ProxyTls_NoTls() { 173 | dialer := http_dialer.New(s.proxyTlsUrl(), http_dialer.WithTls(clientTlsConfig()), withBasicProxyAuth) 174 | s.grpcCallAndAssert(false, dialer) 175 | } 176 | 177 | func (s *DialerIntegrationTestSuite) Test_ProxyTls_Tls() { 178 | dialer := http_dialer.New(s.proxyTlsUrl(), http_dialer.WithTls(clientTlsConfig()), withBasicProxyAuth) 179 | s.grpcCallAndAssert(true, dialer) 180 | } 181 | 182 | func (s *DialerIntegrationTestSuite) Test_SupportsAuthChallenge_WithNoInitialHeader() { 183 | yoloBasicAuth := &yoloBasicAuthWithoutInitialHeaders{ 184 | username: expectedUser, 185 | password: expectedPassword, 186 | initialHeaderContent: "", // empty string causes no Proxy-Authenticate to be sent 187 | } 188 | dialer := http_dialer.New(s.proxyTlsUrl(), http_dialer.WithTls(clientTlsConfig()), http_dialer.WithProxyAuth(yoloBasicAuth)) 189 | s.grpcCallAndAssert(true, dialer) 190 | } 191 | 192 | func (s *DialerIntegrationTestSuite) Test_SupportsAuthChallenge_WithBadInitialHeader() { 193 | yoloBasicAuth := &yoloBasicAuthWithoutInitialHeaders{ 194 | username: expectedUser, 195 | password: expectedPassword, 196 | initialHeaderContent: "BadValue", // initial bad value will cause a reauthencite that will succeed. 197 | } 198 | dialer := http_dialer.New(s.proxyTlsUrl(), http_dialer.WithTls(clientTlsConfig()), http_dialer.WithProxyAuth(yoloBasicAuth)) 199 | s.grpcCallAndAssert(true, dialer) 200 | } 201 | 202 | func (s *DialerIntegrationTestSuite) grpcCallAndAssert(isGrpcTls bool, dialer *http_dialer.HttpTunnel) { 203 | opts := []grpc.DialOption{ 204 | grpc.WithBlock(), 205 | grpc.WithTimeout(2 * time.Second), 206 | grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { return dialer.Dial("tcp", addr) }), 207 | } 208 | addr := s.grpcAddr() 209 | if isGrpcTls { 210 | addr = s.grpcTlsAddr() 211 | opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(clientTlsConfig()))) 212 | } else { 213 | opts = append(opts, grpc.WithInsecure()) 214 | } 215 | client, err := grpc.Dial(addr, opts...) 216 | require.NoError(s.T(), err, "must not error on client Dial") 217 | testClient := mwitkow_testproto.NewTestServiceClient(client) 218 | _, err = testClient.PingEmpty(s.ctx, &mwitkow_testproto.Empty{}) 219 | require.NoError(s.T(), err, "empty call must succeed") 220 | } 221 | 222 | func serverTlsConfig() *tls.Config { 223 | cert, err := tls.LoadX509KeyPair("testdata/server1.pem", "testdata/server1.key") 224 | if err != nil { 225 | panic(fmt.Sprintf("failed reading serverTlsConfig: %v", err)) 226 | } 227 | return &tls.Config{Certificates: []tls.Certificate{cert}} 228 | } 229 | 230 | func clientTlsConfig() *tls.Config { 231 | b, err := ioutil.ReadFile("testdata/ca.pem") 232 | if err != nil { 233 | panic(fmt.Sprintf("failed reading clientTlsConfig: %v", err)) 234 | } 235 | cp := x509.NewCertPool() 236 | if !cp.AppendCertsFromPEM(b) { 237 | panic(fmt.Sprintf("failed appending certs in clientTlsConfig: %v", err)) 238 | } 239 | return &tls.Config{InsecureSkipVerify: true, RootCAs: cp} 240 | } 241 | 242 | type yoloBasicAuthWithoutInitialHeaders struct { 243 | username string 244 | password string 245 | initialHeaderContent string 246 | } 247 | 248 | func (b *yoloBasicAuthWithoutInitialHeaders) Type() string { 249 | return "Basic" 250 | } 251 | 252 | func (b *yoloBasicAuthWithoutInitialHeaders) InitialResponse() string { 253 | return b.initialHeaderContent 254 | } 255 | 256 | func (b *yoloBasicAuthWithoutInitialHeaders) ChallengeResponse(challenge string) string { 257 | resp := b.username + ":" + b.password 258 | return base64.StdEncoding.EncodeToString([]byte(resp)) 259 | } 260 | -------------------------------------------------------------------------------- /test/testdata/ca.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICSjCCAbOgAwIBAgIJAJHGGR4dGioHMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV 3 | BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX 4 | aWRnaXRzIFB0eSBMdGQxDzANBgNVBAMTBnRlc3RjYTAeFw0xNDExMTEyMjMxMjla 5 | Fw0yNDExMDgyMjMxMjlaMFYxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0 6 | YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxDzANBgNVBAMT 7 | BnRlc3RjYTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwEDfBV5MYdlHVHJ7 8 | +L4nxrZy7mBfAVXpOc5vMYztssUI7mL2/iYujiIXM+weZYNTEpLdjyJdu7R5gGUu 9 | g1jSVK/EPHfc74O7AyZU34PNIP4Sh33N+/A5YexrNgJlPY+E3GdVYi4ldWJjgkAd 10 | Qah2PH5ACLrIIC6tRka9hcaBlIECAwEAAaMgMB4wDAYDVR0TBAUwAwEB/zAOBgNV 11 | HQ8BAf8EBAMCAgQwDQYJKoZIhvcNAQELBQADgYEAHzC7jdYlzAVmddi/gdAeKPau 12 | sPBG/C2HCWqHzpCUHcKuvMzDVkY/MP2o6JIW2DBbY64bO/FceExhjcykgaYtCH/m 13 | oIU63+CFOTtR7otyQAWHqXa7q4SbCDlG7DyRFxqG0txPtGvy12lgldA2+RgcigQG 14 | Dfcog5wrJytaQ6UA0wE= 15 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /test/testdata/server1.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOHDFScoLCVJpYDD 3 | M4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1BgzkWF+slf 4 | 3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd9N8YwbBY 5 | AckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAECgYAn7qGnM2vbjJNBm0VZCkOkTIWm 6 | V10okw7EPJrdL2mkre9NasghNXbE1y5zDshx5Nt3KsazKOxTT8d0Jwh/3KbaN+YY 7 | tTCbKGW0pXDRBhwUHRcuRzScjli8Rih5UOCiZkhefUTcRb6xIhZJuQy71tjaSy0p 8 | dHZRmYyBYO2YEQ8xoQJBAPrJPhMBkzmEYFtyIEqAxQ/o/A6E+E4w8i+KM7nQCK7q 9 | K4JXzyXVAjLfyBZWHGM2uro/fjqPggGD6QH1qXCkI4MCQQDmdKeb2TrKRh5BY1LR 10 | 81aJGKcJ2XbcDu6wMZK4oqWbTX2KiYn9GB0woM6nSr/Y6iy1u145YzYxEV/iMwff 11 | DJULAkB8B2MnyzOg0pNFJqBJuH29bKCcHa8gHJzqXhNO5lAlEbMK95p/P2Wi+4Hd 12 | aiEIAF1BF326QJcvYKmwSmrORp85AkAlSNxRJ50OWrfMZnBgzVjDx3xG6KsFQVk2 13 | ol6VhqL6dFgKUORFUWBvnKSyhjJxurlPEahV6oo6+A+mPhFY8eUvAkAZQyTdupP3 14 | XEFQKctGz+9+gKkemDp7LBBMEMBXrGTLPhpEfcjv/7KPdnFHYmhYeBTBnuVmTVWe 15 | F98XJ7tIFfJq 16 | -----END PRIVATE KEY----- -------------------------------------------------------------------------------- /test/testdata/server1.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIICnDCCAgWgAwIBAgIBBzANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJBVTET 3 | MBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0cyBQ 4 | dHkgTHRkMQ8wDQYDVQQDEwZ0ZXN0Y2EwHhcNMTUxMTA0MDIyMDI0WhcNMjUxMTAx 5 | MDIyMDI0WjBlMQswCQYDVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNV 6 | BAcTB0NoaWNhZ28xFTATBgNVBAoTDEV4YW1wbGUsIENvLjEaMBgGA1UEAxQRKi50 7 | ZXN0Lmdvb2dsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOHDFSco 8 | LCVJpYDDM4HYtIdV6Ake/sMNaaKdODjDMsux/4tDydlumN+fm+AjPEK5GHhGn1Bg 9 | zkWF+slf3BxhrA/8dNsnunstVA7ZBgA/5qQxMfGAq4wHNVX77fBZOgp9VlSMVfyd 10 | 9N8YwbBYAckOeUQadTi2X1S6OgJXgQ0m3MWhAgMBAAGjazBpMAkGA1UdEwQCMAAw 11 | CwYDVR0PBAQDAgXgME8GA1UdEQRIMEaCECoudGVzdC5nb29nbGUuZnKCGHdhdGVy 12 | em9vaS50ZXN0Lmdvb2dsZS5iZYISKi50ZXN0LnlvdXR1YmUuY29thwTAqAEDMA0G 13 | CSqGSIb3DQEBCwUAA4GBAJFXVifQNub1LUP4JlnX5lXNlo8FxZ2a12AFQs+bzoJ6 14 | hM044EDjqyxUqSbVePK0ni3w1fHQB5rY9yYC5f8G7aqqTY1QOhoUk8ZTSTRpnkTh 15 | y4jjdvTZeLDVBlueZUTDRmy2feY5aZIU18vFDK08dTG0A87pppuv1LNIR3loveU8 16 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /test/testproto/Makefile: -------------------------------------------------------------------------------- 1 | all: test_go 2 | 3 | test_go: test.proto 4 | PATH="${GOPATH}/bin:${PATH}" protoc \ 5 | -I. \ 6 | -I${GOPATH}/src \ 7 | --go_out=plugins=grpc:. \ 8 | test.proto 9 | 10 | 11 | -------------------------------------------------------------------------------- /test/testproto/impl.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Michal Witkowski. All Rights Reserved. 2 | // See LICENSE for licensing terms. 3 | 4 | package mwitkow_testproto 5 | 6 | import ( 7 | "golang.org/x/net/context" 8 | "google.golang.org/grpc" 9 | "google.golang.org/grpc/codes" 10 | ) 11 | 12 | const ( 13 | PingDefaultValue = "I like kittens." 14 | CountListResponses = 20 15 | ) 16 | 17 | type TestService struct { 18 | } 19 | 20 | func (s *TestService) PingEmpty(ctx context.Context, _ *Empty) (*PingResponse, error) { 21 | return &PingResponse{Value: PingDefaultValue, Counter: 42}, nil 22 | } 23 | 24 | func (s *TestService) Ping(ctx context.Context, ping *PingRequest) (*PingResponse, error) { 25 | // Send user trailers and headers. 26 | return &PingResponse{Value: ping.Value, Counter: 42}, nil 27 | } 28 | 29 | func (s *TestService) PingError(ctx context.Context, ping *PingRequest) (*Empty, error) { 30 | code := codes.Code(ping.ErrorCodeReturned) 31 | return nil, grpc.Errorf(code, "Userspace error.") 32 | } 33 | 34 | func (s *TestService) PingList(ping *PingRequest, stream TestService_PingListServer) error { 35 | if ping.ErrorCodeReturned != 0 { 36 | return grpc.Errorf(codes.Code(ping.ErrorCodeReturned), "foobar") 37 | } 38 | // Send user trailers and headers. 39 | for i := 0; i < CountListResponses; i++ { 40 | stream.Send(&PingResponse{Value: ping.Value, Counter: int32(i)}) 41 | } 42 | return nil 43 | } 44 | -------------------------------------------------------------------------------- /test/testproto/test.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. 2 | // source: test.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package mwitkow_testproto is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | test.proto 10 | 11 | It has these top-level messages: 12 | Empty 13 | PingRequest 14 | PingResponse 15 | */ 16 | package mwitkow_testproto 17 | 18 | import proto "github.com/golang/protobuf/proto" 19 | import fmt "fmt" 20 | import math "math" 21 | 22 | import ( 23 | context "golang.org/x/net/context" 24 | grpc "google.golang.org/grpc" 25 | ) 26 | 27 | // Reference imports to suppress errors if they are not otherwise used. 28 | var _ = proto.Marshal 29 | var _ = fmt.Errorf 30 | var _ = math.Inf 31 | 32 | // This is a compile-time assertion to ensure that this generated file 33 | // is compatible with the proto package it is being compiled against. 34 | // A compilation error at this line likely means your copy of the 35 | // proto package needs to be updated. 36 | const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package 37 | 38 | type Empty struct { 39 | } 40 | 41 | func (m *Empty) Reset() { *m = Empty{} } 42 | func (m *Empty) String() string { return proto.CompactTextString(m) } 43 | func (*Empty) ProtoMessage() {} 44 | func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } 45 | 46 | type PingRequest struct { 47 | Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` 48 | SleepTimeMs int32 `protobuf:"varint,2,opt,name=sleep_time_ms,json=sleepTimeMs" json:"sleep_time_ms,omitempty"` 49 | ErrorCodeReturned uint32 `protobuf:"varint,3,opt,name=error_code_returned,json=errorCodeReturned" json:"error_code_returned,omitempty"` 50 | } 51 | 52 | func (m *PingRequest) Reset() { *m = PingRequest{} } 53 | func (m *PingRequest) String() string { return proto.CompactTextString(m) } 54 | func (*PingRequest) ProtoMessage() {} 55 | func (*PingRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } 56 | 57 | type PingResponse struct { 58 | Value string `protobuf:"bytes,1,opt,name=Value,json=value" json:"Value,omitempty"` 59 | Counter int32 `protobuf:"varint,2,opt,name=counter" json:"counter,omitempty"` 60 | } 61 | 62 | func (m *PingResponse) Reset() { *m = PingResponse{} } 63 | func (m *PingResponse) String() string { return proto.CompactTextString(m) } 64 | func (*PingResponse) ProtoMessage() {} 65 | func (*PingResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } 66 | 67 | func init() { 68 | proto.RegisterType((*Empty)(nil), "mwitkow.testproto.Empty") 69 | proto.RegisterType((*PingRequest)(nil), "mwitkow.testproto.PingRequest") 70 | proto.RegisterType((*PingResponse)(nil), "mwitkow.testproto.PingResponse") 71 | } 72 | 73 | // Reference imports to suppress errors if they are not otherwise used. 74 | var _ context.Context 75 | var _ grpc.ClientConn 76 | 77 | // This is a compile-time assertion to ensure that this generated file 78 | // is compatible with the grpc package it is being compiled against. 79 | const _ = grpc.SupportPackageIsVersion3 80 | 81 | // Client API for TestService service 82 | 83 | type TestServiceClient interface { 84 | PingEmpty(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*PingResponse, error) 85 | Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) 86 | PingError(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*Empty, error) 87 | PingList(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (TestService_PingListClient, error) 88 | } 89 | 90 | type testServiceClient struct { 91 | cc *grpc.ClientConn 92 | } 93 | 94 | func NewTestServiceClient(cc *grpc.ClientConn) TestServiceClient { 95 | return &testServiceClient{cc} 96 | } 97 | 98 | func (c *testServiceClient) PingEmpty(ctx context.Context, in *Empty, opts ...grpc.CallOption) (*PingResponse, error) { 99 | out := new(PingResponse) 100 | err := grpc.Invoke(ctx, "/mwitkow.testproto.TestService/PingEmpty", in, out, c.cc, opts...) 101 | if err != nil { 102 | return nil, err 103 | } 104 | return out, nil 105 | } 106 | 107 | func (c *testServiceClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) { 108 | out := new(PingResponse) 109 | err := grpc.Invoke(ctx, "/mwitkow.testproto.TestService/Ping", in, out, c.cc, opts...) 110 | if err != nil { 111 | return nil, err 112 | } 113 | return out, nil 114 | } 115 | 116 | func (c *testServiceClient) PingError(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*Empty, error) { 117 | out := new(Empty) 118 | err := grpc.Invoke(ctx, "/mwitkow.testproto.TestService/PingError", in, out, c.cc, opts...) 119 | if err != nil { 120 | return nil, err 121 | } 122 | return out, nil 123 | } 124 | 125 | func (c *testServiceClient) PingList(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (TestService_PingListClient, error) { 126 | stream, err := grpc.NewClientStream(ctx, &_TestService_serviceDesc.Streams[0], c.cc, "/mwitkow.testproto.TestService/PingList", opts...) 127 | if err != nil { 128 | return nil, err 129 | } 130 | x := &testServicePingListClient{stream} 131 | if err := x.ClientStream.SendMsg(in); err != nil { 132 | return nil, err 133 | } 134 | if err := x.ClientStream.CloseSend(); err != nil { 135 | return nil, err 136 | } 137 | return x, nil 138 | } 139 | 140 | type TestService_PingListClient interface { 141 | Recv() (*PingResponse, error) 142 | grpc.ClientStream 143 | } 144 | 145 | type testServicePingListClient struct { 146 | grpc.ClientStream 147 | } 148 | 149 | func (x *testServicePingListClient) Recv() (*PingResponse, error) { 150 | m := new(PingResponse) 151 | if err := x.ClientStream.RecvMsg(m); err != nil { 152 | return nil, err 153 | } 154 | return m, nil 155 | } 156 | 157 | // Server API for TestService service 158 | 159 | type TestServiceServer interface { 160 | PingEmpty(context.Context, *Empty) (*PingResponse, error) 161 | Ping(context.Context, *PingRequest) (*PingResponse, error) 162 | PingError(context.Context, *PingRequest) (*Empty, error) 163 | PingList(*PingRequest, TestService_PingListServer) error 164 | } 165 | 166 | func RegisterTestServiceServer(s *grpc.Server, srv TestServiceServer) { 167 | s.RegisterService(&_TestService_serviceDesc, srv) 168 | } 169 | 170 | func _TestService_PingEmpty_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 171 | in := new(Empty) 172 | if err := dec(in); err != nil { 173 | return nil, err 174 | } 175 | if interceptor == nil { 176 | return srv.(TestServiceServer).PingEmpty(ctx, in) 177 | } 178 | info := &grpc.UnaryServerInfo{ 179 | Server: srv, 180 | FullMethod: "/mwitkow.testproto.TestService/PingEmpty", 181 | } 182 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 183 | return srv.(TestServiceServer).PingEmpty(ctx, req.(*Empty)) 184 | } 185 | return interceptor(ctx, in, info, handler) 186 | } 187 | 188 | func _TestService_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 189 | in := new(PingRequest) 190 | if err := dec(in); err != nil { 191 | return nil, err 192 | } 193 | if interceptor == nil { 194 | return srv.(TestServiceServer).Ping(ctx, in) 195 | } 196 | info := &grpc.UnaryServerInfo{ 197 | Server: srv, 198 | FullMethod: "/mwitkow.testproto.TestService/Ping", 199 | } 200 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 201 | return srv.(TestServiceServer).Ping(ctx, req.(*PingRequest)) 202 | } 203 | return interceptor(ctx, in, info, handler) 204 | } 205 | 206 | func _TestService_PingError_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 207 | in := new(PingRequest) 208 | if err := dec(in); err != nil { 209 | return nil, err 210 | } 211 | if interceptor == nil { 212 | return srv.(TestServiceServer).PingError(ctx, in) 213 | } 214 | info := &grpc.UnaryServerInfo{ 215 | Server: srv, 216 | FullMethod: "/mwitkow.testproto.TestService/PingError", 217 | } 218 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 219 | return srv.(TestServiceServer).PingError(ctx, req.(*PingRequest)) 220 | } 221 | return interceptor(ctx, in, info, handler) 222 | } 223 | 224 | func _TestService_PingList_Handler(srv interface{}, stream grpc.ServerStream) error { 225 | m := new(PingRequest) 226 | if err := stream.RecvMsg(m); err != nil { 227 | return err 228 | } 229 | return srv.(TestServiceServer).PingList(m, &testServicePingListServer{stream}) 230 | } 231 | 232 | type TestService_PingListServer interface { 233 | Send(*PingResponse) error 234 | grpc.ServerStream 235 | } 236 | 237 | type testServicePingListServer struct { 238 | grpc.ServerStream 239 | } 240 | 241 | func (x *testServicePingListServer) Send(m *PingResponse) error { 242 | return x.ServerStream.SendMsg(m) 243 | } 244 | 245 | var _TestService_serviceDesc = grpc.ServiceDesc{ 246 | ServiceName: "mwitkow.testproto.TestService", 247 | HandlerType: (*TestServiceServer)(nil), 248 | Methods: []grpc.MethodDesc{ 249 | { 250 | MethodName: "PingEmpty", 251 | Handler: _TestService_PingEmpty_Handler, 252 | }, 253 | { 254 | MethodName: "Ping", 255 | Handler: _TestService_Ping_Handler, 256 | }, 257 | { 258 | MethodName: "PingError", 259 | Handler: _TestService_PingError_Handler, 260 | }, 261 | }, 262 | Streams: []grpc.StreamDesc{ 263 | { 264 | StreamName: "PingList", 265 | Handler: _TestService_PingList_Handler, 266 | ServerStreams: true, 267 | }, 268 | }, 269 | Metadata: fileDescriptor0, 270 | } 271 | 272 | func init() { proto.RegisterFile("test.proto", fileDescriptor0) } 273 | 274 | var fileDescriptor0 = []byte{ 275 | // 272 bytes of a gzipped FileDescriptorProto 276 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xa4, 0x91, 0x41, 0x4b, 0xc4, 0x30, 277 | 0x10, 0x85, 0xed, 0x6a, 0x5d, 0x77, 0xea, 0x1e, 0x36, 0x7a, 0x08, 0x1e, 0x54, 0x72, 0xf2, 0x14, 278 | 0x44, 0xef, 0x5e, 0x44, 0x54, 0x50, 0x94, 0xb8, 0x78, 0x2d, 0xda, 0x1d, 0x24, 0xb8, 0x6d, 0x6a, 279 | 0x92, 0x6e, 0xf1, 0xbf, 0xf9, 0xe3, 0x9c, 0x64, 0x2b, 0x08, 0x6b, 0x51, 0xf0, 0x38, 0xef, 0x1b, 280 | 0xde, 0x7b, 0x93, 0x00, 0x78, 0x74, 0x5e, 0xd6, 0xd6, 0x78, 0xc3, 0x26, 0x65, 0xab, 0xfd, 0xab, 281 | 0x69, 0x65, 0xd0, 0xa2, 0x24, 0x86, 0x90, 0x5e, 0x94, 0xb5, 0x7f, 0x17, 0x2d, 0x64, 0xf7, 0xba, 282 | 0x7a, 0x51, 0xf8, 0xd6, 0x10, 0x64, 0xbb, 0x90, 0x2e, 0x9e, 0xe6, 0x0d, 0xf2, 0xe4, 0x30, 0x39, 283 | 0x1a, 0xa9, 0xe5, 0xc0, 0x04, 0x8c, 0xdd, 0x1c, 0xb1, 0xce, 0xbd, 0x2e, 0x31, 0x2f, 0x1d, 0x1f, 284 | 0x10, 0x4d, 0x55, 0x16, 0xc5, 0x29, 0x69, 0xb7, 0x8e, 0x49, 0xd8, 0x41, 0x6b, 0x8d, 0xcd, 0x0b, 285 | 0x33, 0xc3, 0xdc, 0xa2, 0x6f, 0x6c, 0x85, 0x33, 0xbe, 0x4e, 0x9b, 0x63, 0x35, 0x89, 0xe8, 0x9c, 286 | 0x88, 0xea, 0x80, 0x38, 0x83, 0xed, 0x65, 0xb0, 0xab, 0x4d, 0xe5, 0x30, 0x24, 0x3f, 0xae, 0x26, 287 | 0x73, 0x18, 0x16, 0xa6, 0xa9, 0x3c, 0xda, 0x2e, 0xf3, 0x6b, 0x3c, 0xf9, 0x18, 0x40, 0x36, 0xa5, 288 | 0xca, 0x0f, 0x68, 0x17, 0xba, 0x40, 0x76, 0x05, 0xa3, 0xe0, 0x17, 0xaf, 0x62, 0x5c, 0xae, 0x9c, 289 | 0x2c, 0x23, 0xd9, 0x3b, 0xf8, 0x81, 0x7c, 0xef, 0x21, 0xd6, 0xd8, 0x35, 0x6c, 0x04, 0x85, 0xed, 290 | 0xf7, 0xae, 0xc6, 0xb7, 0xfa, 0x8b, 0xd5, 0x65, 0x57, 0x2a, 0x5c, 0xff, 0xab, 0x5f, 0x6f, 0x69, 291 | 0x32, 0xba, 0x83, 0xad, 0xb0, 0x7a, 0xa3, 0xe9, 0x8f, 0xfe, 0xdf, 0xeb, 0x38, 0x79, 0xde, 0x8c, 292 | 0xfa, 0xe9, 0x67, 0x00, 0x00, 0x00, 0xff, 0xff, 0x38, 0x3e, 0x02, 0xe9, 0x28, 0x02, 0x00, 0x00, 293 | } 294 | -------------------------------------------------------------------------------- /test/testproto/test.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package mwitkow.testproto; 4 | 5 | 6 | message Empty { 7 | } 8 | 9 | message PingRequest { 10 | string value = 1; 11 | int32 sleep_time_ms = 2; 12 | uint32 error_code_returned = 3; 13 | } 14 | 15 | message PingResponse { 16 | string Value = 1; 17 | int32 counter = 2; 18 | } 19 | 20 | service TestService { 21 | rpc PingEmpty(Empty) returns (PingResponse) {} 22 | 23 | rpc Ping(PingRequest) returns (PingResponse) {} 24 | 25 | rpc PingError(PingRequest) returns (Empty) {} 26 | 27 | rpc PingList(PingRequest) returns (stream PingResponse) {} 28 | } 29 | --------------------------------------------------------------------------------