Debian Codegraph @

goupnp/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 resp, _ := ioutil.ReadAll(response.Body)
58 return fmt.Errorf("goupnp: SOAP request got HTTP %s: %s", response.Status, resp)
59 }
60
61 responseEnv := newSOAPEnvelope()
62 decoder := xml.NewDecoder(response.Body)
63 if err := decoder.Decode(responseEnv); err != nil {
64 return fmt.Errorf("goupnp: error decoding response body: %v", err)
65 }
66
67 if responseEnv.Body.Fault != nil {
68 return responseEnv.Body.Fault
69 }
70
71 if outAction != nil {
72 if err := xml.Unmarshal(responseEnv.Body.RawAction, outAction); err != nil {
73 return fmt.Errorf("goupnp: error unmarshalling out action: %v, %v", err, responseEnv.Body.RawAction)
74 }
75 }
76
77 return nil
78 }
79
80 // newSOAPAction creates a soapEnvelope with the given action and arguments.
81 func newSOAPEnvelope() *soapEnvelope {
82 return &soapEnvelope{
83 EncodingStyle: soapEncodingStyle,
84 }
85 }
86
87 // encodeRequestAction is a hacky way to create an encoded SOAP envelope
88 // containing the given action. Experiments with one router have shown that it
89 // 500s for requests where the outer default xmlns is set to the SOAP
90 // namespace, and then reassigning the default namespace within that to the
91 // service namespace. Hand-coding the outer XML to work-around this.
92 func encodeRequestAction(actionNamespace, actionName string, inAction interface{}) ([]byte, error) {
93 requestBuf := new(bytes.Buffer)
94 requestBuf.WriteString(soapPrefix)
95 requestBuf.WriteString(`<u:`)
96 xml.EscapeText(requestBuf, []byte(actionName))
97 requestBuf.WriteString(` xmlns:u="`)
98 xml.EscapeText(requestBuf, []byte(actionNamespace))
99 requestBuf.WriteString(`">`)
100 if inAction != nil {
101 if err := encodeRequestArgs(requestBuf, inAction); err != nil {
102 return nil, err
103 }
104 }
105 requestBuf.WriteString(`</u:`)
106 xml.EscapeText(requestBuf, []byte(actionName))
107 requestBuf.WriteString(`>`)
108 requestBuf.WriteString(soapSuffix)
109 return requestBuf.Bytes(), nil
110 }
111
112 func encodeRequestArgs(w *bytes.Buffer, inAction interface{}) error {
113 in := reflect.Indirect(reflect.ValueOf(inAction))
114 if in.Kind() != reflect.Struct {
115 return fmt.Errorf("goupnp: SOAP inAction is not a struct but of type %v", in.Type())
116 }
117 enc := xml.NewEncoder(w)
118 nFields := in.NumField()
119 inType := in.Type()
120 for i := 0; i < nFields; i++ {
121 field := inType.Field(i)
122 argName := field.Name
123 if nameOverride := field.Tag.Get("soap"); nameOverride != "" {
124 argName = nameOverride
125 }
126 value := in.Field(i)
127 if value.Kind() != reflect.String {
128 return fmt.Errorf("goupnp: SOAP arg %q is not of type string, but of type %v", argName, value.Type())
129 }
130 if err := enc.EncodeElement(value.Interface(), xml.StartElement{xml.Name{"", argName}, nil}); err != nil {
131 return fmt.Errorf("goupnp: error encoding SOAP arg %q: %v", argName, err)
132 }
133 }
134 enc.Flush()
135 return nil
136 }
137
138 type soapEnvelope struct {
139 XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
140 EncodingStyle string `xml:"http://schemas.xmlsoap.org/soap/envelope/ encodingStyle,attr"`
141 Body soapBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
142 }
143
144 type soapBody struct {
145 Fault *SOAPFaultError `xml:"Fault"`
146 RawAction []byte `xml:",innerxml"`
147 }
148
149 // SOAPFaultError implements error, and contains SOAP fault information.
150 type SOAPFaultError struct {
151 FaultCode string `xml:"faultcode"`
152 FaultString string `xml:"faultstring"`
153 Detail string `xml:"detail"`
154 }
155
156 func (err *SOAPFaultError) Error() string {
157 return fmt.Sprintf("SOAP fault: %s", err.FaultString)
158 }