transport.go 6.15 KB
Newer Older
1
package irma
2
3
4

import (
	"bytes"
5
	"crypto/sha256"
6
7
8
	"encoding/json"
	"io"
	"io/ioutil"
9
	"log"
10
	"net"
11
	"net/http"
12
	"path/filepath"
13
14
	"strings"
	"time"
15

16
	"github.com/Sirupsen/logrus"
17
	"github.com/go-errors/errors"
18
19
	"github.com/hashicorp/go-retryablehttp"

20
	"github.com/privacybydesign/irmago/internal/disable_sigpipe"
21
	"github.com/privacybydesign/irmago/internal/fs"
22
23
)

Sietse Ringers's avatar
Sietse Ringers committed
24
// HTTPTransport sends and receives JSON messages to a HTTP server.
25
type HTTPTransport struct {
Sietse Ringers's avatar
Sietse Ringers committed
26
	Server  string
27
	client  *retryablehttp.Client
Sietse Ringers's avatar
Sietse Ringers committed
28
	headers map[string]string
29
30
}

31
32
// Logger is used for logging. If not set, init() will initialize it to logrus.StandardLogger().
var Logger *logrus.Logger
Sietse Ringers's avatar
Sietse Ringers committed
33

34
35
36
var transportlogger *log.Logger

func init() {
37
38
	if Logger == nil {
		Logger = logrus.StandardLogger()
39
40
41
	}
}

Sietse Ringers's avatar
Sietse Ringers committed
42
// NewHTTPTransport returns a new HTTPTransport.
43
func NewHTTPTransport(serverURL string) *HTTPTransport {
44
45
46
47
	if Logger.IsLevelEnabled(logrus.TraceLevel) {
		transportlogger = log.New(Logger.WriterLevel(logrus.TraceLevel), "transport: ", 0)
	}

48
	url := serverURL
49
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
50
51
		url += "/"
	}
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

	// Create a transport that dials with a SIGPIPE handler (which is only active on iOS)
	var innerTransport http.Transport

	innerTransport.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
	}

67
68
69
70
	client := retryablehttp.NewClient()
	client.RetryMax = 3
	client.RetryWaitMin = 100 * time.Millisecond
	client.RetryWaitMax = 500 * time.Millisecond
71
	client.Logger = transportlogger
72
73
74
75
76
	client.HTTPClient = &http.Client{
		Timeout:   time.Second * 5,
		Transport: &innerTransport,
	}

Sietse Ringers's avatar
Sietse Ringers committed
77
78
79
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
80
		client:  client,
Sietse Ringers's avatar
Sietse Ringers committed
81
	}
82
83
}

84
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
85
86
87
88
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

89
90
91
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
92
93
	var req retryablehttp.Request
	req.Request, err = http.NewRequest(method, transport.Server+url, reader)
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}

	req.Header.Set("User-Agent", "irmago")
	if reader != nil {
		if isstr {
			req.Header.Set("Content-Type", "text/plain; charset=UTF-8")
		} else {
			req.Header.Set("Content-Type", "application/json; charset=UTF-8")
		}
	}
	for name, val := range transport.headers {
		req.Header.Set(name, val)
	}

110
	res, err := transport.client.Do(&req)
111
112
113
114
115
116
117
	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 {
118
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
119
120
121
122
123
124
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

125
	var isstr bool
126
127
	var reader io.Reader
	if object != nil {
128
129
130
131
132
133
		var objstr string
		if objstr, isstr = object.(string); isstr {
			reader = bytes.NewBuffer([]byte(objstr))
		} else {
			marshaled, err := json.Marshal(object)
			if err != nil {
Tomas's avatar
Tomas committed
134
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
135
			}
136
			Logger.Debugf("%s %s: %s\n", method, url, string(marshaled))
137
			reader = bytes.NewBuffer(marshaled)
138
		}
139
	} else {
140
		Logger.Debugf("%s %s\n", method, url)
141
142
	}

143
	res, err := transport.request(url, method, reader, isstr)
144
	if err != nil {
145
		return err
146
	}
147
148
149
150
	if method == http.MethodDelete {
		return nil
	}

151
152
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
153
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
154
155
	}
	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
156
		apierr := &RemoteError{}
Sietse Ringers's avatar
Sietse Ringers committed
157
158
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
159
			return &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
160
		}
161
		Logger.Debugf("ERROR: %+v\n", apierr)
Tomas's avatar
Tomas committed
162
		return &SessionError{ErrorType: ErrorApi, RemoteStatus: res.StatusCode, RemoteError: apierr}
163
164
	}

165
	Logger.Debugf("RESPONSE: %s\n", string(body))
166
167
168
169
170
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
171
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
172
		}
173
174
175
176
177
	}

	return nil
}

178
179
180
181
182
func (transport *HTTPTransport) GetBytes(url string) ([]byte, error) {
	res, err := transport.request(url, http.MethodGet, nil, false)
	if err != nil {
		return nil, &SessionError{ErrorType: ErrorTransport, Err: err}
	}
183
184

	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
185
		return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
186
	}
187
188
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
189
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
190
191
192
193
	}
	return b, nil
}

194
func (transport *HTTPTransport) GetSignedFile(url string, dest string, hash ConfigurationFileHash) error {
195
196
197
198
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
199
200
201
202
	sha := sha256.Sum256(b)
	if hash != nil && !bytes.Equal(hash, sha[:]) {
		return errors.Errorf("Signature over new file %s is not valid", dest)
	}
203
	if err = fs.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
204
205
		return err
	}
206
	return fs.SaveFile(dest, b)
207
208
}

209
210
211
212
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
213
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
214
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
215
	return transport.jsonRequest(url, http.MethodPost, result, object)
216
217
}

Sietse Ringers's avatar
Sietse Ringers committed
218
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
219
func (transport *HTTPTransport) Get(url string, result interface{}) error {
220
	return transport.jsonRequest(url, http.MethodGet, result, nil)
221
222
}

Sietse Ringers's avatar
Sietse Ringers committed
223
// Delete performs a DELETE.
224
func (transport *HTTPTransport) Delete() {
225
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
226
}