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

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

15
	"github.com/privacybydesign/irmago/internal/disable_sigpipe"
16
	"github.com/privacybydesign/irmago/internal/fs"
17
18
)

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

26
const verbose = false
Sietse Ringers's avatar
Sietse Ringers committed
27

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

	// 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
49
50
51
52
53
54
55
56
	return &HTTPTransport{
		Server:  url,
		headers: map[string]string{},
		client: &http.Client{
			Timeout:   time.Second * 15,
			Transport: &innerTransport,
		},
	}
57
58
}

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

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

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

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

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

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

	return nil
}

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

	if res.StatusCode != 200 {
		return nil, &SessionError{ErrorType: ErrorServerResponse, Status: res.StatusCode}
	}
169
170
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
171
		return nil, &SessionError{ErrorType: ErrorServerResponse, Err: err, Status: res.StatusCode, StatusMessage: res.Status}
172
173
174
175
176
177
178
179
180
	}
	return b, nil
}

func (transport *HTTPTransport) GetFile(url string, dest string) error {
	b, err := transport.GetBytes(url)
	if err != nil {
		return err
	}
181
	if err = fs.EnsureDirectoryExists(filepath.Dir(dest)); err != nil {
182
183
		return err
	}
184
	return fs.SaveFile(dest, b)
185
186
}

Sietse Ringers's avatar
Sietse Ringers committed
187
// Post sends the object to the server and parses its response into result.
Sietse Ringers's avatar
Sietse Ringers committed
188
func (transport *HTTPTransport) Post(url string, result interface{}, object interface{}) error {
189
	return transport.jsonRequest(url, http.MethodPost, result, object)
190
191
}

Sietse Ringers's avatar
Sietse Ringers committed
192
// Get performs a GET request and parses the server's response into result.
Sietse Ringers's avatar
Sietse Ringers committed
193
func (transport *HTTPTransport) Get(url string, result interface{}) error {
194
	return transport.jsonRequest(url, http.MethodGet, result, nil)
195
196
}

Sietse Ringers's avatar
Sietse Ringers committed
197
// Delete performs a DELETE.
198
func (transport *HTTPTransport) Delete() {
199
	_ = transport.jsonRequest("", http.MethodDelete, nil, nil)
200
}