forked from privacybydesign/irmago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.go
320 lines (286 loc) · 9.08 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package irma
import (
"bytes"
"context"
"crypto/tls"
"encoding/hex"
"encoding/json"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/go-errors/errors"
"github.com/hashicorp/go-retryablehttp"
"github.com/privacybydesign/gabi"
"github.com/privacybydesign/gabi/revocation"
sseclient "github.com/sietseringers/go-sse"
"github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
"github.com/privacybydesign/irmago/internal/common"
"github.com/privacybydesign/irmago/internal/disable_sigpipe"
)
// HTTPTransport sends and receives JSON messages to a HTTP server.
type HTTPTransport struct {
Server string
Binary bool
ForceHTTPS bool
client *retryablehttp.Client
headers http.Header
}
var HTTPHeaders = map[string]http.Header{}
// Logger is used for logging. If not set, init() will initialize it to logrus.StandardLogger().
var Logger *logrus.Logger
var transportlogger *log.Logger
var tlsClientConfig *tls.Config
func init() {
logger := logrus.New()
logger.SetFormatter(&prefixed.TextFormatter{
DisableColors: true,
FullTimestamp: true,
TimestampFormat: "15:04:05.000000",
})
SetLogger(logger)
}
func SetLogger(logger *logrus.Logger) {
Logger = logger
gabi.Logger = Logger
common.Logger = Logger
revocation.Logger = Logger
sseclient.Logger = log.New(Logger.WithField("type", "sseclient").WriterLevel(logrus.TraceLevel), "", 0)
}
// SetTLSClientConfig sets the TLS configuration being used for future outbound connections.
// A TLS configuration instance should not be modified after being set.
func SetTLSClientConfig(config *tls.Config) {
tlsClientConfig = config
}
// NewHTTPTransport returns a new HTTPTransport.
func NewHTTPTransport(serverURL string, forceHTTPS bool) *HTTPTransport {
if Logger.IsLevelEnabled(logrus.TraceLevel) {
transportlogger = log.New(Logger.WriterLevel(logrus.TraceLevel), "transport: ", 0)
} else {
transportlogger = log.New(ioutil.Discard, "", 0)
}
if serverURL != "" && !strings.HasSuffix(serverURL, "/") {
serverURL += "/"
}
// Create a transport that dials with a SIGPIPE handler (which is only active on iOS)
innerTransport := &http.Transport{
TLSClientConfig: tlsClientConfig,
Dial: func(network, addr string) (c net.Conn, err error) {
c, err = net.Dial(network, addr)
if err != nil {
return c, err
}
if err = disable_sigpipe.DisableSigPipe(c); err != nil {
return c, err
}
return c, nil
},
}
client := &retryablehttp.Client{
Logger: transportlogger,
RetryWaitMin: 100 * time.Millisecond,
RetryWaitMax: 200 * time.Millisecond,
RetryMax: 2,
Backoff: retryablehttp.DefaultBackoff,
CheckRetry: func(ctx context.Context, resp *http.Response, err error) (bool, error) {
// Don't retry on 5xx (which retryablehttp does by default)
return err != nil || resp.StatusCode == 0, err
},
HTTPClient: &http.Client{
Timeout: time.Second * 3,
Transport: innerTransport,
},
}
var host string
u, err := url.Parse(serverURL)
if err != nil {
Logger.Warnf("failed to parse URL %s: %s", serverURL, err.Error())
} else {
host = u.Host
}
headers := HTTPHeaders[host].Clone()
if headers == nil {
headers = http.Header{}
}
return &HTTPTransport{
Server: serverURL,
ForceHTTPS: forceHTTPS,
headers: headers,
client: client,
}
}
func (transport *HTTPTransport) marshal(o interface{}) ([]byte, error) {
if transport.Binary {
return MarshalBinary(o)
}
return json.Marshal(o)
}
func (transport *HTTPTransport) unmarshal(data []byte, dst interface{}) error {
if transport.Binary {
return UnmarshalBinary(data, dst)
}
return json.Unmarshal(data, dst)
}
func (transport *HTTPTransport) unmarshalValidate(data []byte, dst interface{}) error {
if transport.Binary {
return UnmarshalValidateBinary(data, dst)
}
return UnmarshalValidate(data, dst)
}
func (transport *HTTPTransport) log(prefix string, message interface{}, binary bool) {
if !Logger.IsLevelEnabled(logrus.TraceLevel) {
return // do nothing if nothing would be printed anyway
}
var str string
switch s := message.(type) {
case []byte:
str = string(s)
case string:
str = s
default:
tmp, _ := json.Marshal(message)
str = string(tmp)
binary = false
}
if !binary {
Logger.Tracef("transport: %s: %s", prefix, str)
} else {
Logger.Tracef("transport: %s (hex): %s", prefix, hex.EncodeToString([]byte(str)))
}
}
// SetHeader sets a header to be sent in requests.
func (transport *HTTPTransport) SetHeader(name, val string) {
transport.headers.Set(name, val)
}
func (transport *HTTPTransport) request(
url string, method string, reader io.Reader, contenttype string,
) (response *http.Response, err error) {
var req retryablehttp.Request
u := transport.Server + url
if common.ForceHTTPS && transport.ForceHTTPS && !strings.HasPrefix(u, "https") {
return nil, &SessionError{ErrorType: ErrorHTTPS, Err: errors.New("remote server does not use https")}
}
req.Request, err = http.NewRequest(method, u, reader)
if err != nil {
return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
}
req.Header = transport.headers.Clone()
if req.Header.Get("User-agent") == "" {
req.Header.Set("User-Agent", "irmago")
}
if reader != nil && contenttype != "" {
req.Header.Set("Content-Type", contenttype)
}
res, err := transport.client.Do(&req)
if err != nil {
return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
}
return res, nil
}
func (transport *HTTPTransport) jsonRequest(url string, method string, result interface{}, object interface{}) error {
if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
panic("Unsupported HTTP method " + method)
}
if method == http.MethodGet && object != nil {
panic("Cannot GET and also post an object")
}
var reader io.Reader
var contenttype string
if object != nil {
switch o := object.(type) {
case []byte:
transport.log("body", o, true)
contenttype = "application/octet-stream"
reader = bytes.NewBuffer(o)
case string:
transport.log("body", o, false)
contenttype = "text/plain; charset=UTF-8"
reader = bytes.NewBuffer([]byte(o))
default:
marshaled, err := transport.marshal(object)
if err != nil {
return &SessionError{ErrorType: ErrorSerialization, Err: err}
}
transport.log("body", string(marshaled), transport.Binary)
if transport.Binary {
contenttype = "application/octet-stream"
} else {
contenttype = "application/json; charset=UTF-8"
}
reader = bytes.NewBuffer(marshaled)
}
}
res, err := transport.request(url, method, reader, contenttype)
if err != nil {
return err
}
// For DELETE requests it's common to receive a '204 No Content' on success.
if method == http.MethodDelete && (res.StatusCode == http.StatusOK || res.StatusCode == http.StatusNoContent) {
return nil
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
}
if res.StatusCode == http.StatusNoContent {
if result != nil {
return &SessionError{
ErrorType: ErrorServerResponse,
Err: errors.New("'204 No Content' received, but result was expected"),
RemoteStatus: res.StatusCode,
}
}
} else if res.StatusCode != http.StatusOK {
apierr := &RemoteError{}
err = transport.unmarshal(body, apierr)
if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
}
transport.log("error", apierr, false)
return &SessionError{ErrorType: ErrorApi, RemoteStatus: res.StatusCode, RemoteError: apierr}
}
transport.log("response", body, transport.Binary)
if result == nil { // caller doesn't care about server response
return nil
}
if _, resultstr := result.(*string); resultstr {
*result.(*string) = string(body)
} else {
err = transport.unmarshalValidate(body, result)
if err != nil {
return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
}
}
return nil
}
func (transport *HTTPTransport) GetBytes(url string) ([]byte, error) {
res, err := transport.request(url, http.MethodGet, nil, "")
if err != nil {
return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
}
if res.StatusCode != 200 {
return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
}
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
}
return b, nil
}
// Post sends the object to the server and parses its response into result.
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
return transport.jsonRequest(url, http.MethodPost, result, object)
}
// Get performs a GET request and parses the server's response into result.
func (transport *HTTPTransport) Get(url string, result interface{}) error {
return transport.jsonRequest(url, http.MethodGet, result, nil)
}
// Delete performs a DELETE.
func (transport *HTTPTransport) Delete() error {
return transport.jsonRequest("", http.MethodDelete, nil, nil)
}