Debian Codegraph @

soap/soap.go

raw symbols SCIP
1 // Definition for the SOAP structure required for UPnP's SOAP usage.
2
3 package soap
4
5 import (
6 "bytes"
7 "encoding/xml"
8 "fmt"
9 "io/ioutil"
10 "net/http"
11 "net/url"
12 "reflect"
13 )
14
15 const (
16 soapEncodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"
17 soapPrefix = xml.Header + `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body>`
18 soapSuffix = `</s:Body></s:Envelope>`
19 )
20
21 type SOAPClient struct {
22 EndpointURL url.URL
23 HTTPClient http.Client
24 }
25
26 func NewSOAPClient(endpointURL url.URL) *SOAPClient {
27 return &SOAPClient{
28 EndpointURL: endpointURL,
29 }
30 }
31
32 // PerformSOAPAction makes a SOAP request, with the given action.
33 // inAction and outAction must both be pointers to structs with string fields
34 // only.
35 func (client *SOAPClient) PerformAction(actionNamespace, actionName string, inAction interface{}, outAction interface{}) error {
36 requestBytes, err := encodeRequestAction(actionNamespace, actionName, inAction)
37 if err != nil {
38 return err
39 }
40
41 response, err := client.HTTPClient.Do(&http.Request{
42 Method: "POST",
43 URL: &client.EndpointURL,
44 Header: http.Header{
45 "SOAPACTION": []string{`"` + actionNamespace + "#" + actionName + `"`},
46 "CONTENT-TYPE": []string{"text/xml; charset=\"utf-8\""},
47 },
48 Body: ioutil.NopCloser(bytes.NewBuffer(requestBytes)),
49 // Set ContentLength to avoid chunked encoding - some servers might not support it.
50 ContentLength: int64(len(requestBytes)),
51 })
52 if err != nil {
53 return fmt.Errorf("goupnp: error performing SOAP HTTP request: %v", err)
54 }
55 defer response.Body.Close()
56 if response.StatusCode != 200 {
57 return fmt.Errorf("goupnp: SOAP request got HTTP %s", response.Status)
58 }
59
60 responseEnv := newSOAPEnvelope()
61 decoder := xml.NewDecoder(response.Body)
62 if err := decoder.Decode(responseEnv); err != nil {
63 return fmt.Errorf("goupnp: error decoding response body: %v", err)
64 }
65
66 if responseEnv.Body.Fault != nil {
67 return responseEnv.Body.Fault
68 }
69
70 if outAction != nil {
71 if err := xml.Unmarshal(responseEnv.Body.RawAction, outAction); err != nil {
72 return fmt.Errorf("goupnp: error unmarshalling out action: %v, %v", err, responseEnv.Body.RawAction)
73 }
74 }
75
76 return nil
77 }
78
79 // newSOAPAction creates a soapEnvelope with the given action and arguments.
80 func newSOAPEnvelope() *soapEnvelope {
81 return &soapEnvelope{
82 EncodingStyle: soapEncodingStyle,
83 }
84 }
85
86 // encodeRequestAction is a hacky way to create an encoded SOAP envelope
87 // containing the given action. Experiments with one router have shown that it
88 // 500s for requests where the outer default xmlns is set to the SOAP
89 // namespace, and then reassigning the default namespace within that to the
90 // service namespace. Hand-coding the outer XML to work-around this.
91 func encodeRequestAction(actionNamespace, actionName string, inAction interface{}) ([]byte, error) {
92 requestBuf := new(bytes.Buffer)
93 requestBuf.WriteString(soapPrefix)
94 requestBuf.WriteString(`<u:`)
95 xml.EscapeText(requestBuf, []byte(actionName))
96 requestBuf.WriteString(` xmlns:u="`)
97 xml.EscapeText(requestBuf, []byte(actionNamespace))
98 requestBuf.WriteString(`">`)
99 if inAction != nil {
100 if err := encodeRequestArgs(requestBuf, inAction); err != nil {
101 return nil, err
102 }
103 }
104 requestBuf.WriteString(`</u:`)
105 xml.EscapeText(requestBuf, []byte(actionName))
106 requestBuf.WriteString(`>`)
107 requestBuf.WriteString(soapSuffix)
108 return requestBuf.Bytes(), nil
109 }
110
111 func encodeRequestArgs(w *bytes.Buffer, inAction interface{}) error {
112 in := reflect.Indirect(reflect.ValueOf(inAction))
113 if in.Kind() != reflect.Struct {
114 return fmt.Errorf("goupnp: SOAP inAction is not a struct but of type %v", in.Type())
115 }
116 enc := xml.NewEncoder(w)
117 nFields := in.NumField()
118 inType := in.Type()
119 for i := 0; i < nFields; i++ {
120 field := inType.Field(i)
121 argName := field.Name
122 if nameOverride := field.Tag.Get("soap"); nameOverride != "" {
123 argName = nameOverride
124 }
125 value := in.Field(i)
126 if value.Kind() != reflect.String {
127 return fmt.Errorf("goupnp: SOAP arg %q is not of type string, but of type %v", argName, value.Type())
128 }
129 if err := enc.EncodeElement(value.Interface(), xml.StartElement{xml.Name{"", argName}, nil}); err != nil {
130 return fmt.Errorf("goupnp: error encoding SOAP arg %q: %v", argName, err)
131 }
132 }
133 enc.Flush()
134 return nil
135 }
136
137 type soapEnvelope struct {
138 XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
139 EncodingStyle string `xml:"http://schemas.xmlsoap.org/soap/envelope/ encodingStyle,attr"`
140 Body soapBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
141 }
142
143 type soapBody struct {
144 Fault *SOAPFaultError `xml:"Fault"`
145 RawAction []byte `xml:",innerxml"`
146 }
147
148 // SOAPFaultError implements error, and contains SOAP fault information.
149 type SOAPFaultError struct {
150 FaultCode string `xml:"faultcode"`
151 FaultString string `xml:"faultstring"`
152 Detail string `xml:"detail"`
153 }
154
155 func (err *SOAPFaultError) Error() string {
156 return fmt.Sprintf("SOAP fault: %s", err.FaultString)
157 }