-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfakesoap.go
374 lines (311 loc) · 9.68 KB
/
fakesoap.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
* Copyright 2017-2019 Kopano and its licensors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kcc
import (
"bufio"
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/eternnoir/gncp"
)
const (
soapUserAgent = "kcc-go-fakesoap"
soapHeader = `<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xop="http://www.w3.org/2004/08/xop/include" xmlns:xmlmime="http://www.w3.org/2004/11/xmlmime" xmlns:ns="urn:zarafa"><SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">`
soapFooter = `</SOAP-ENV:Body></SOAP-ENV:Envelope>`
)
func soapEnvelope(payload *string) *bytes.Buffer {
var b bytes.Buffer
b.WriteString(soapHeader)
b.WriteString(*payload)
b.WriteString(soapFooter)
if debug {
raw, _ := ioutil.ReadAll(&b)
b = *bytes.NewBuffer(raw)
fmt.Printf("SOAP --- request start ---\n%s\nSOAP --- request end ---\n", string(raw))
}
return &b
}
func newSOAPRequest(ctx context.Context, url string, payload *string) (*http.Request, error) {
body := soapEnvelope(payload)
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
if ctx != nil {
req = req.WithContext(ctx)
}
req.Header.Set("Content-Type", "text/xml; charset=utf-8")
req.Header.Set("User-Agent", soapUserAgent+"/"+Version)
return req, nil
}
func debugRawResponse(code int, data io.Reader) (io.Reader, error) {
raw, err := ioutil.ReadAll(data)
if err != nil {
return nil, err
}
fmt.Printf("SOAP --- response %d start ---\n%s\nSOAP --- response end ---\n", code, string(raw))
return bytes.NewBuffer(raw), nil
}
func parseSOAPResponse(code int, data io.Reader, v interface{}) error {
if debug {
var err error
data, err = debugRawResponse(code, data)
if err != nil {
return err
}
}
decoder := xml.NewDecoder(data)
match := false
for {
t, _ := decoder.Token()
if t == nil {
break
}
switch se := t.(type) {
case xml.StartElement:
if match {
return decoder.DecodeElement(v, &se)
}
if se.Name.Local == "Body" {
match = true
}
}
}
return fmt.Errorf("failed to unmarshal SOAP response body")
}
// A SOAPClient is a network client which sends SOAP requests.
type SOAPClient interface {
DoRequest(ctx context.Context, payload *string, v interface{}) error
}
// A SOAPClientConfig is a collection of configuration settings used when
// constructing SOAP clients.
type SOAPClientConfig struct {
HTTPClient *http.Client
SocketDialer *net.Dialer
}
// DefaultSOAPClientConfig is the default SOAP client config which is used when
// constructing SOAP clients with default settings.
var DefaultSOAPClientConfig = &SOAPClientConfig{}
// A SOAPHTTPClient implements a SOAP client using the HTTP protocol.
type SOAPHTTPClient struct {
Client *http.Client
URI string
}
// A SOAPSocketClient implements a SOAP client connecting to a unix socket.
type SOAPSocketClient struct {
Dialer *net.Dialer
Pool gncp.ConnPool
Path string
}
// NewSOAPClient creates a new SOAP client for the protocol matching the
// provided URL using default connection settings. If the protocol is
// unsupported, an error is returned.
func NewSOAPClient(uri *url.URL) (SOAPClient, error) {
if uri == nil {
uri, _ = url.Parse(DefaultURI)
}
switch uri.Scheme {
case "https":
fallthrough
case "http":
return NewSOAPHTTPClient(uri, nil)
case "file":
return NewSOAPSocketClient(uri, nil)
default:
return nil, fmt.Errorf("invalid scheme '%v' for SOAP client", uri.Scheme)
}
}
// NewSOAPClientWithConfig create new SOAP client for the protocol matching
// the provided URL using defaulft uri and config if nil is providedl. If the
// protocol is unsupported, an error is returned.
func NewSOAPClientWithConfig(uri *url.URL, config *SOAPClientConfig) (SOAPClient, error) {
if uri == nil {
uri, _ = url.Parse(DefaultURI)
}
if config == nil {
config = DefaultSOAPClientConfig
}
switch uri.Scheme {
case "https":
fallthrough
case "http":
return NewSOAPHTTPClient(uri, config.HTTPClient)
case "file":
return NewSOAPSocketClient(uri, config.SocketDialer)
default:
return nil, fmt.Errorf("invalid scheme '%v' for SOAP client", uri.Scheme)
}
}
// NewSOAPHTTPClient creates a new SOAP HTTP client for the protocol matching the
// provided URL. A http.Client can be provided to further customize the behavior
// of the client instead of using the defaults. If the protocol is unsupported,
// an error is returned.
func NewSOAPHTTPClient(uri *url.URL, client *http.Client) (*SOAPHTTPClient, error) {
var err error
if uri == nil {
uri, err = uri.Parse(DefaultURI)
if err != nil {
return nil, err
}
}
if client == nil {
client = DefaultHTTPClient
}
switch uri.Scheme {
case "https":
fallthrough
case "http":
c := &SOAPHTTPClient{
Client: client,
URI: uri.String(),
}
return c, nil
default:
return nil, fmt.Errorf("invalid scheme '%v' for SOAP HTTP client", uri.Scheme)
}
}
// NewSOAPSocketClient creates a new SOAP socket client for the protocol
// matching the provided URL. A net.Dialer can be provided to further customize
// the behavior of the client instead of using the defaults. If the protocol is
// unsupported, an error is returned.
func NewSOAPSocketClient(uri *url.URL, dialer *net.Dialer) (*SOAPSocketClient, error) {
var err error
if uri == nil {
uri, err = uri.Parse(DefaultURI)
if err != nil {
return nil, err
}
}
if dialer == nil {
dialer = DefaultUnixDialer
}
if uri.Scheme != "file" {
return nil, fmt.Errorf("invalid scheme '%v' for SOAP socket client", uri.Scheme)
}
c := &SOAPSocketClient{
Dialer: dialer,
Path: uri.Path,
}
pool, err := gncp.NewPool(0, DefaultUnixMaxConnections, c.connect)
if err != nil {
return nil, err
}
c.Pool = pool
return c, nil
}
// DoRequest sends the provided payload data as SOAP through the means of the
// accociated client. Connections are automatically reused according to keep-alive
// configuration provided by the http.Client attached to the SOAPHTTPClient.
func (sc *SOAPHTTPClient) DoRequest(ctx context.Context, payload *string, v interface{}) error {
body := soapEnvelope(payload)
req, err := http.NewRequest(http.MethodPost, sc.URI, body)
if err != nil {
return err
}
if ctx != nil {
req = req.WithContext(ctx)
}
req.Header.Set("Content-Type", "text/xml; charset=utf-8")
req.Header.Set("User-Agent", soapUserAgent+"/"+Version)
resp, err := sc.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
debugRawResponse(resp.StatusCode, resp.Body)
return fmt.Errorf("unexpected http response status: %v", resp.StatusCode)
}
return parseSOAPResponse(resp.StatusCode, resp.Body, v)
}
func (sc *SOAPHTTPClient) String() string {
return fmt.Sprintf("<http:%s>", sc.URI)
}
// DoRequest sends the provided payload data as SOAP through the means of the
// accociated client.
func (sc *SOAPSocketClient) DoRequest(ctx context.Context, payload *string, v interface{}) error {
for {
// TODO(longsleep): Use a pool which allows to add additional connections
// in burst situations. With this current implementation based on Go
// channel select, requests can timeout on burst situations where
// constantly more requests than pooled connections are available come
// in as Go's select is non-deterministic.
c, err := sc.Pool.GetWithTimeout(sc.Dialer.Timeout)
if err != nil {
return fmt.Errorf("failed to open unix socket: %v", err)
}
body := soapEnvelope(payload)
r := bufio.NewReader(c)
c.SetWriteDeadline(time.Now().Add(sc.Dialer.Timeout))
_, err = body.WriteTo(c)
if err != nil {
// Remove from pool and retry on any write error. This will retry
// until the pool is not able to return a socket connection fast
// enough anymore.
sc.Pool.Remove(c)
continue
}
// NOTE(longsleep): Kopano SOAP socket return HTTP protocol data.
c.SetReadDeadline(time.Now().Add(sc.Dialer.Timeout))
resp, err := http.ReadResponse(r, nil)
if err != nil {
sc.Pool.Remove(c)
return fmt.Errorf("failed to read from unix socket: %v", err)
}
canReuseConnection := resp.Header.Get("Connection") == "keep-alive"
defer func() {
resp.Body.Close()
if canReuseConnection {
// Close makes the connection available to the pool again.
c.Close()
} else {
sc.Pool.Remove(c)
}
}()
if resp.StatusCode != http.StatusOK {
debugRawResponse(resp.StatusCode, resp.Body)
return fmt.Errorf("unexpected http response status: %v", resp.StatusCode)
}
return parseSOAPResponse(resp.StatusCode, resp.Body, v)
}
}
func (sc *SOAPSocketClient) connect() (net.Conn, error) {
return sc.Dialer.Dial("unix", sc.Path)
}
func (sc *SOAPSocketClient) String() string {
return fmt.Sprintf("<socket:%s>", sc.Path)
}
type xmlCharData []byte
func (s xmlCharData) String() string {
return string(s)
}
func (s xmlCharData) Escape() string {
var b strings.Builder
xml.EscapeText(&b, s)
return b.String()
}
func (s xmlCharData) WriteTo(w io.Writer) error {
return xml.EscapeText(w, s)
}