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

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

16
	"github.com/go-errors/errors"
17
	"github.com/privacybydesign/irmago/internal/disable_sigpipe"
18
	"github.com/privacybydesign/irmago/internal/fs"
19
20
)

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

28
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
29

Sietse Ringers's avatar
Sietse Ringers committed
30
// NewHTTPTransport returns a new HTTPTransport.
31
32
func NewHTTPTransport(serverURL string) *HTTPTransport {
	url := serverURL
33
	if serverURL != "" && !strings.HasSuffix(url, "/") { // TODO fix this
34
35
		url += "/"
	}
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

	// 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
	}

Sietse Ringers's avatar
Sietse Ringers committed
51
52
53
54
55
56
57
58
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
		client: &http.Client{
			Timeout:   time.Second * 15,
			Transport: &innerTransport,
		},
	}
59
60
}

61
// SetHeader sets a header to be sent in requests.
Sietse Ringers's avatar
Sietse Ringers committed
62
63
64
65
func (transport *HTTPTransport) SetHeader(name, val string) {
	transport.headers[name] = val
}

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
func (transport *HTTPTransport) request(
	url string, method string, reader io.Reader, isstr bool,
) (response *http.Response, err error) {
	req, err := http.NewRequest(method, transport.Server+url, reader)
	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)
	}

	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 {
94
	if method != http.MethodPost && method != http.MethodGet && method != http.MethodDelete {
95
96
97
98
99
100
		panic("Unsupported HTTP method " + method)
	}
	if method == http.MethodGet && object != nil {
		panic("Cannot GET and also post an object")
	}

101
	var isstr bool
102
103
	var reader io.Reader
	if object != nil {
104
105
106
107
108
109
		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
110
				return &SessionError{ErrorType: ErrorSerialization, Err: err}
111
			}
Sietse Ringers's avatar
Sietse Ringers committed
112
			if verbose {
113
				fmt.Printf("%s %s: %s\n", method, url, string(marshaled))
Sietse Ringers's avatar
Sietse Ringers committed
114
			}
115
			reader = bytes.NewBuffer(marshaled)
116
		}
117
118
119
120
	} else {
		if verbose {
			fmt.Printf("%s %s\n", method, url)
		}
121
122
	}

123
	res, err := transport.request(url, method, reader, isstr)
124
	if err != nil {
125
		return err
126
	}
127
128
129
130
	if method == http.MethodDelete {
		return nil
	}

131
132
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
133
		return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
134
135
	}
	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
136
		apierr := &RemoteError{}
Sietse Ringers's avatar
Sietse Ringers committed
137
138
		err = json.Unmarshal(body, apierr)
		if err != nil || apierr.ErrorName == "" { // Not an ApiErrorMessage
Tomas's avatar
Tomas committed
139
			return &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
140
		}
Sietse Ringers's avatar
Sietse Ringers committed
141
142
143
		if verbose {
			fmt.Printf("ERROR: %+v\n", apierr)
		}
Tomas's avatar
Tomas committed
144
		return &SessionError{ErrorType: ErrorApi, RemoteStatus: res.StatusCode, RemoteError: apierr}
145
146
	}

Sietse Ringers's avatar
Sietse Ringers committed
147
148
149
	if verbose {
		fmt.Printf("RESPONSE: %s\n", string(body))
	}
150
151
152
153
154
	if _, resultstr := result.(*string); resultstr {
		*result.(*string) = string(body)
	} else {
		err = json.Unmarshal(body, result)
		if err != nil {
Tomas's avatar
Tomas committed
155
			return &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
156
		}
157
158
159
160
161
	}

	return nil
}

162
163
164
165
166
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}
	}
167
168

	if res.StatusCode != 200 {
Tomas's avatar
Tomas committed
169
		return nil, &SessionError{ErrorType: ErrorServerResponse, RemoteStatus: res.StatusCode}
170
	}
171
172
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
Tomas's avatar
Tomas committed
173
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, RemoteStatus: res.StatusCode}
174
175
176
177
	}
	return b, nil
}

178
func (transport *HTTPTransport) GetSignedFile(url string, dest string, hash ConfigurationFileHash) error {
179
180
181
182
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
183
184
185
186
	sha := sha256.Sum256(b)
	if hash != nil && !bytes.Equal(hash, sha[:]) {
		return errors.Errorf("Signature over new file %s is not valid", dest)
	}
187
	if err = fs.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
188
189
		return err
	}
190
	return fs.SaveFile(dest, b)
191
192
}

193
194
195
196
func (transport *HTTPTransport) GetFile(url string, dest string) error {
	return transport.GetSignedFile(url, dest, nil)
}

Sietse Ringers's avatar
Sietse Ringers committed
197
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
198
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
199
	return transport.jsonRequest(url, http.MethodPost, result, object)
200
201
}

Sietse Ringers's avatar
Sietse Ringers committed
202
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
203
func (transport *HTTPTransport) Get(url string, result interface{}) error {
204
	return transport.jsonRequest(url, http.MethodGet, result, nil)
205
206
}

Sietse Ringers's avatar
Sietse Ringers committed
207
// Delete performs a DELETE.
208
func (transport *HTTPTransport) Delete() {
209
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
210
}