json_client.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. Copyright (c) 2023-2023 VMware, Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package soap
  14. import (
  15. "bytes"
  16. "context"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "mime"
  21. "net/http"
  22. "reflect"
  23. "strings"
  24. "github.com/vmware/govmomi/vim25/xml"
  25. "github.com/vmware/govmomi/vim25/types"
  26. )
  27. const (
  28. sessionHeader = "vmware-api-session-id"
  29. )
  30. var (
  31. // errInvalidResponse is used during unmarshaling when the response content
  32. // does not match expectations e.g. unexpected HTTP status code or MIME
  33. // type.
  34. errInvalidResponse error = errors.New("Invalid response")
  35. // errInputError is used as root error when the request is malformed.
  36. errInputError error = errors.New("Invalid input error")
  37. )
  38. // Handles round trip using json HTTP
  39. func (c *Client) jsonRoundTrip(ctx context.Context, req, res HasFault) error {
  40. this, method, params, err := unpackSOAPRequest(req)
  41. if err != nil {
  42. return fmt.Errorf("Cannot unpack the request. %w", err)
  43. }
  44. return c.invoke(ctx, this, method, params, res)
  45. }
  46. // Invoke calls a managed object method
  47. func (c *Client) invoke(ctx context.Context, this types.ManagedObjectReference, method string, params interface{}, res HasFault) error {
  48. buffer := bytes.Buffer{}
  49. if params != nil {
  50. marshaller := types.NewJSONEncoder(&buffer)
  51. err := marshaller.Encode(params)
  52. if err != nil {
  53. return fmt.Errorf("Encoding request to JSON failed. %w", err)
  54. }
  55. }
  56. uri := c.getPathForName(this, method)
  57. req, err := http.NewRequest(http.MethodPost, uri, &buffer)
  58. if err != nil {
  59. return err
  60. }
  61. if len(c.cookie) != 0 {
  62. req.Header.Add(sessionHeader, c.cookie)
  63. }
  64. result, err := getSOAPResultPtr(res)
  65. if err != nil {
  66. return fmt.Errorf("Cannot get pointer to the result structure. %w", err)
  67. }
  68. return c.Do(ctx, req, c.responseUnmarshaler(&result))
  69. }
  70. // responseUnmarshaler create unmarshaler function for VMOMI JSON request. The
  71. // unmarshaler checks for errors and tries to load the response body in the
  72. // result structure. It is assumed that result is pointer to a data structure or
  73. // interface{}.
  74. func (c *Client) responseUnmarshaler(result interface{}) func(resp *http.Response) error {
  75. return func(resp *http.Response) error {
  76. if resp.StatusCode == http.StatusNoContent ||
  77. (!isError(resp.StatusCode) && resp.ContentLength == 0) {
  78. return nil
  79. }
  80. if e := checkJSONContentType(resp); e != nil {
  81. return e
  82. }
  83. if resp.StatusCode == 500 {
  84. bodyBytes, e := io.ReadAll(resp.Body)
  85. if e != nil {
  86. return e
  87. }
  88. var serverErr interface{}
  89. dec := types.NewJSONDecoder(bytes.NewReader(bodyBytes))
  90. e = dec.Decode(&serverErr)
  91. if e != nil {
  92. return e
  93. }
  94. var faultStringStruct struct {
  95. FaultString string `json:"faultstring,omitempty"`
  96. }
  97. dec = types.NewJSONDecoder(bytes.NewReader(bodyBytes))
  98. e = dec.Decode(&faultStringStruct)
  99. if e != nil {
  100. return e
  101. }
  102. f := &Fault{
  103. XMLName: xml.Name{
  104. Space: c.Namespace,
  105. Local: reflect.TypeOf(serverErr).Name() + "Fault",
  106. },
  107. String: faultStringStruct.FaultString,
  108. Code: "ServerFaultCode",
  109. }
  110. f.Detail.Fault = serverErr
  111. return WrapSoapFault(f)
  112. }
  113. if isError(resp.StatusCode) {
  114. return fmt.Errorf("Unexpected HTTP error code: %v. %w", resp.StatusCode, errInvalidResponse)
  115. }
  116. dec := types.NewJSONDecoder(resp.Body)
  117. e := dec.Decode(result)
  118. if e != nil {
  119. return e
  120. }
  121. c.checkForSessionHeader(resp)
  122. return nil
  123. }
  124. }
  125. func isError(statusCode int) bool {
  126. return statusCode < http.StatusOK || statusCode >= http.StatusMultipleChoices
  127. }
  128. // checkForSessionHeader checks if we have new session id.
  129. // This is a hack that intercepts the session id header and then repeats it.
  130. // It is very similar to cookie store but only for the special vCenter
  131. // session header.
  132. func (c *Client) checkForSessionHeader(resp *http.Response) {
  133. sessionKey := resp.Header.Get(sessionHeader)
  134. if len(sessionKey) > 0 {
  135. c.cookie = sessionKey
  136. }
  137. }
  138. // Checks if the payload of an HTTP response has the JSON MIME type.
  139. func checkJSONContentType(resp *http.Response) error {
  140. contentType := resp.Header.Get("content-type")
  141. mediaType, _, err := mime.ParseMediaType(contentType)
  142. if err != nil {
  143. return fmt.Errorf("error parsing content-type: %v, error %w", contentType, err)
  144. }
  145. if mediaType != "application/json" {
  146. return fmt.Errorf("content-type is not application/json: %v. %w", contentType, errInvalidResponse)
  147. }
  148. return nil
  149. }
  150. func (c *Client) getPathForName(this types.ManagedObjectReference, name string) string {
  151. const urnPrefix = "urn:"
  152. ns := c.Namespace
  153. if strings.HasPrefix(ns, urnPrefix) {
  154. ns = ns[len(urnPrefix):]
  155. }
  156. return fmt.Sprintf("%v/%v/%v/%v/%v/%v", c.u, ns, c.Version, this.Type, this.Value, name)
  157. }
  158. // unpackSOAPRequest converts SOAP request into this value, method nam and
  159. // parameters using reflection. The input is a one of the *Body structures
  160. // defined in methods.go. It is expected to have "Req" field that is a non-null
  161. // pointer to a struct. The struct simple type name is the method name. The
  162. // struct "This" member is the this MoRef value.
  163. func unpackSOAPRequest(req HasFault) (this types.ManagedObjectReference, method string, params interface{}, err error) {
  164. reqBodyPtr := reflect.ValueOf(req)
  165. if reqBodyPtr.Kind() != reflect.Ptr {
  166. err = fmt.Errorf("Expected pointer to request body as input. %w", errInputError)
  167. return
  168. }
  169. reqBody := reqBodyPtr.Elem()
  170. if reqBody.Kind() != reflect.Struct {
  171. err = fmt.Errorf("Expected Request body to be structure. %w", errInputError)
  172. return
  173. }
  174. methodRequestPtr := reqBody.FieldByName("Req")
  175. if methodRequestPtr.Kind() != reflect.Ptr {
  176. err = fmt.Errorf("Expected method request body field to be pointer to struct. %w", errInputError)
  177. return
  178. }
  179. methodRequest := methodRequestPtr.Elem()
  180. if methodRequest.Kind() != reflect.Struct {
  181. err = fmt.Errorf("Expected method request body to be structure. %w", errInputError)
  182. return
  183. }
  184. thisValue := methodRequest.FieldByName("This")
  185. if thisValue.Kind() != reflect.Struct {
  186. err = fmt.Errorf("Expected This field in the method request body to be structure. %w", errInputError)
  187. return
  188. }
  189. var ok bool
  190. if this, ok = thisValue.Interface().(types.ManagedObjectReference); !ok {
  191. err = fmt.Errorf("Expected This field to be MoRef. %w", errInputError)
  192. return
  193. }
  194. method = methodRequest.Type().Name()
  195. params = methodRequestPtr.Interface()
  196. return
  197. }
  198. // getSOAPResultPtr extract a pointer to the result data structure using go
  199. // reflection from a SOAP data structure used for marshalling.
  200. func getSOAPResultPtr(result HasFault) (res interface{}, err error) {
  201. resBodyPtr := reflect.ValueOf(result)
  202. if resBodyPtr.Kind() != reflect.Ptr {
  203. err = fmt.Errorf("Expected pointer to result body as input. %w", errInputError)
  204. return
  205. }
  206. resBody := resBodyPtr.Elem()
  207. if resBody.Kind() != reflect.Struct {
  208. err = fmt.Errorf("Expected result body to be structure. %w", errInputError)
  209. return
  210. }
  211. methodResponsePtr := resBody.FieldByName("Res")
  212. if methodResponsePtr.Kind() != reflect.Ptr {
  213. err = fmt.Errorf("Expected method response body field to be pointer to struct. %w", errInputError)
  214. return
  215. }
  216. if methodResponsePtr.IsNil() {
  217. methodResponsePtr.Set(reflect.New(methodResponsePtr.Type().Elem()))
  218. }
  219. methodResponse := methodResponsePtr.Elem()
  220. if methodResponse.Kind() != reflect.Struct {
  221. err = fmt.Errorf("Expected method response body to be structure. %w", errInputError)
  222. return
  223. }
  224. returnval := methodResponse.FieldByName("Returnval")
  225. if !returnval.IsValid() {
  226. // void method and we return nil, nil
  227. return
  228. }
  229. res = returnval.Addr().Interface()
  230. return
  231. }