unofficial mirror of bug-guile@gnu.org 
 help / color / mirror / Atom feed
* bug#32528: http-post breaks with XML response payload containing boundary
@ 2018-08-25  8:49 Ricardo Wurmus
  2018-08-28 21:51 ` Mark H Weaver
  0 siblings, 1 reply; 5+ messages in thread
From: Ricardo Wurmus @ 2018-08-25  8:49 UTC (permalink / raw)
  To: 32528

Hi Guilers,

I’m having a problem with http-post and I think it might be a bug.  I’m
talking to a Debbugs SOAP service over HTTP by sending (via POST) an XML
request.  The Debbugs SOAP service responds with a string of XML.

Here’s a simplified version of what I do:

  (use-module (web http))
  (let ((req-xml "<soap:Envelope xmlns:soap...>"))
    (receive (response body)
        (http-post uri
                   #:body req-xml
                   #:headers
                   `((content-type . (text/xml))
                     (content-length . ,(string-length req-xml))))
     ;; Do something with the response body
     (xml->sxml body #:trim-whitespace? #t)))

This fails for some requests with an error like this:

    web/http.scm:1609:23: Bad Content-Type header: multipart/related; type="text/xml"; start="<main_envelope>"; boundary="=-=-="

Here’s a backtrace:

--8<---------------cut here---------------start------------->8---
In debbugs/soap.scm:
    101:8  9 (soap-invoke "https://debbugs.gnu.org/cgi/soap.cgi" _ . _)
In web/client.scm:
   386:24  8 (http-request _ #:body _ #:port _ #:method _ #:version _ #:keep-alive? _ #:headers _ #:decode-body? _ #:streaming? _ #:request _)
In web/response.scm:
   200:48  7 (read-response #<input-output: string 2db5690>)
In web/http.scm:
   225:33  6 (read-headers #<input-output: string 2db5690>)
   195:11  5 (read-header #<input-output: string 2db5690>)
  1606:12  4 (_ "multipart/related; type=\"text/xml\"; start=\"<main_envelope>\"; boundary=\"=-=-=\"")
In ice-9/boot-9.scm:
   222:29  3 (map1 (" type=\"text/xml\"" " start=\"<main_envelope>\"" " boundary=\"=-=-=\""))
   222:29  2 (map1 (" start=\"<main_envelope>\"" " boundary=\"=-=-=\""))
   222:17  1 (map1 (" boundary=\"=-=-=\""))
In web/http.scm:
  1609:23  0 (_ " boundary=\"=-=-=\"")
--8<---------------cut here---------------end--------------->8---

The reason why it fails is that Guile processes the response and treats
the *payload* contained in the XML response as HTTP.  In this case it
processes the response and stumbles upon a multipart email that contains
a Content-type header specifying a boundary string.

The Content-type handler in (web http) doesn’t like that the boundary
string contains “=” and aborts.

The point is, though, that it shouldn’t even try to parse the payload of
the XML response.  If you want to see the full XML response you can use
wget:

    wget --post-data="<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" soapenc:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><soap:Body><ns1:get_bug_log xmlns:ns1=\"urn:Debbugs/SOAP\" soapenc:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><ns1:bugnumber xsi:type=\"xsd:int\">32514</ns1:bugnumber></ns1:get_bug_log></soap:Body></soap:Envelope>" --header "Content-type: text/xml" -qO - "https://debbugs.gnu.org/cgi/soap.cgi"

Is this a problem with Guile when a response with Content-type text/xml
is received?

--
Ricardo






^ permalink raw reply	[flat|nested] 5+ messages in thread

* bug#32528: http-post breaks with XML response payload containing boundary
  2018-08-25  8:49 bug#32528: http-post breaks with XML response payload containing boundary Ricardo Wurmus
@ 2018-08-28 21:51 ` Mark H Weaver
  2018-08-29  3:28   ` Mark H Weaver
  2018-08-29 10:26   ` Ricardo Wurmus
  0 siblings, 2 replies; 5+ messages in thread
From: Mark H Weaver @ 2018-08-28 21:51 UTC (permalink / raw)
  To: Ricardo Wurmus; +Cc: 32528

Ricardo Wurmus <rekado@elephly.net> writes:

> I’m having a problem with http-post and I think it might be a bug.  I’m
> talking to a Debbugs SOAP service over HTTP by sending (via POST) an XML
> request.  The Debbugs SOAP service responds with a string of XML.
>
> Here’s a simplified version of what I do:
>
>   (use-module (web http))
>   (let ((req-xml "<soap:Envelope xmlns:soap...>"))
>     (receive (response body)
>         (http-post uri
>                    #:body req-xml
>                    #:headers
>                    `((content-type . (text/xml))
>                      (content-length . ,(string-length req-xml))))
>      ;; Do something with the response body
>      (xml->sxml body #:trim-whitespace? #t)))
>
> This fails for some requests with an error like this:
>
>     web/http.scm:1609:23: Bad Content-Type header: multipart/related; type="text/xml"; start="<main_envelope>"; boundary="=-=-="

[...]

> The reason why it fails is that Guile processes the response and treats
> the *payload* contained in the XML response as HTTP.

No, this was a good guess, but it's not actually the problem.

If you add --save-headers to the wget command line, you'll see the full
response, and the HTTP headers are what's being parsed, as it should be.
It looks like this (except that I removed the carriage returns below):

  HTTP/1.1 200 OK
  Date: Tue, 28 Aug 2018 21:40:30 GMT
  Server: Apache
  SOAPServer: SOAP::Lite/Perl/1.11
  Strict-Transport-Security: max-age=63072000
  Content-Length: 32650
  X-Content-Type-Options: nosniff
  X-Frame-Options: sameorigin
  X-XSS-Protection: 1; mode=block
  Keep-Alive: timeout=5, max=100
  Connection: Keep-Alive
  Content-Type: multipart/related; type="text/xml"; start="<main_envelope>"; boundary="=-=-="
  
  <?xml [...]

The problem is simply that our Content-Type header parser is broken.
It's very simplistic and merely splits the string wherever ';' is found,
and then checks to make sure there's only one '=' in each parameter,
without taking into account that quoted strings in the parameters might
include those characters.

I'll work on a proper parser for Content-Type headers.

      Thanks,
        Mark





^ permalink raw reply	[flat|nested] 5+ messages in thread

* bug#32528: http-post breaks with XML response payload containing boundary
  2018-08-28 21:51 ` Mark H Weaver
@ 2018-08-29  3:28   ` Mark H Weaver
  2019-06-25  8:25     ` Ludovic Courtès
  2018-08-29 10:26   ` Ricardo Wurmus
  1 sibling, 1 reply; 5+ messages in thread
From: Mark H Weaver @ 2018-08-29  3:28 UTC (permalink / raw)
  To: Ricardo Wurmus; +Cc: 32528

[-- Attachment #1: Type: text/plain, Size: 4588 bytes --]

Mark H Weaver <mhw@netris.org> writes:

> Ricardo Wurmus <rekado@elephly.net> writes:
>
>> I’m having a problem with http-post and I think it might be a bug.  I’m
>> talking to a Debbugs SOAP service over HTTP by sending (via POST) an XML
>> request.  The Debbugs SOAP service responds with a string of XML.
[...]
> The problem is simply that our Content-Type header parser is broken.
> It's very simplistic and merely splits the string wherever ';' is found,
> and then checks to make sure there's only one '=' in each parameter,
> without taking into account that quoted strings in the parameters might
> include those characters.
>
> I'll work on a proper parser for Content-Type headers.

I've attached preliminary patches to fix the Content-Type header parser,
and also to fix the parsing of response header lines to support
continuation lines.

With these patches applied, I'm able to fetch and decode the SOAP
response that you fetched with your 'wget' example, as follows:

--8<---------------cut here---------------start------------->8---
mhw@jojen ~/guile-stable-2.2 [env]$ meta/guile
GNU Guile 2.2.4.10-4c91d
Copyright (C) 1995-2017 Free Software Foundation, Inc.

Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'.
This program is free software, and you are welcome to redistribute it
under certain conditions; type `,show c' for details.

Enter `,help' for help.
scheme@(guile-user)> (use-modules (web http) (web uri) (web client) (sxml simple) (ice-9 receive))
scheme@(guile-user)> ,pp (let ((req-xml "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" soapenc:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><soap:Body><ns1:get_bug_log xmlns:ns1=\"urn:Debbugs/SOAP\" soapenc:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><ns1:bugnumber xsi:type=\"xsd:int\">32514</ns1:bugnumber></ns1:get_bug_log></soap:Body></soap:Envelope>"))
                           (receive (response body-port)
                               (http-post "https://debbugs.gnu.org/cgi/soap.cgi"
                                          #:streaming? #t
                                          #:body req-xml
                                          #:headers
                                          `((content-type . (text/xml))
                                            (content-length . ,(string-length req-xml))))
                             (set-port-encoding! body-port "UTF-8")
                             (xml->sxml body-port #:trim-whitespace? #t)))
$1 = (*TOP* (*PI* xml "version=\"1.0\" encoding=\"UTF-8\"")
       (http://schemas.xmlsoap.org/soap/envelope/:Envelope
         (@ (http://schemas.xmlsoap.org/soap/envelope/:encodingStyle
              "http://schemas.xmlsoap.org/soap/encoding/"))
         (http://schemas.xmlsoap.org/soap/envelope/:Body
           (urn:Debbugs/SOAP:get_bug_logResponse
             (http://schemas.xmlsoap.org/soap/encoding/:Array
               (@ (http://www.w3.org/1999/XMLSchema-instance:type
                    "soapenc:Array")
                  (http://schemas.xmlsoap.org/soap/encoding/:arrayType
                    "xsd:ur-type[4]"))
               (urn:Debbugs/SOAP:item
                 (urn:Debbugs/SOAP:header
                   (@ (http://www.w3.org/1999/XMLSchema-instance:type
                        "xsd:string"))
                   "Received: (at submit) by debbugs.gnu.org; 23 Aug 2018 20:17:46 +0000\nFrom debbugs-submit-bounces@debbugs.gnu.org [...]
[...]
--8<---------------cut here---------------end--------------->8---

Note that I needed to make two other changes to your preliminary code,
namely:

* I passed "#:streaming? #t" to 'http-post', to ask for a port to read
  the response body instead of reading it eagerly.

* I explicitly set the port encoding to "UTF-8" on that port before
  using 'xml->sxml' to read it.

Otherwise, the entire 'body' response will be returned as a bytevector,
because the response Content-Type is not recognized as a textual type.
The HTTP Content-Type is "multipart/related", with a parameter:
type="text/xml".  I'm not sure if we should be automatically
interpreting that as a textual type or not.

There's no 'charset' parameter in the Content-Type header, but the XML
internally specifies: encoding="UTF-8".

Anyway, here are the preliminary patches.

       Mark



[-- Attachment #2: [PATCH 1/2] web: Add support for HTTP header continuation lines --]
[-- Type: text/x-patch, Size: 2840 bytes --]

From 41764d60dba80126b3c97f883d0225510b55f3fa Mon Sep 17 00:00:00 2001
From: Mark H Weaver <mhw@netris.org>
Date: Tue, 28 Aug 2018 18:39:34 -0400
Subject: [PATCH 1/2] web: Add support for HTTP header continuation lines.

* module/web/http.scm (spaces-and-tabs, space-or-tab?): New variables.
(read-header-line): After reading a header, if a space or tab follows,
then read the continuation lines and append them all together.
---
 module/web/http.scm | 31 ++++++++++++++++++++++++-------
 1 file changed, 24 insertions(+), 7 deletions(-)

diff --git a/module/web/http.scm b/module/web/http.scm
index de61c9495..15f173173 100644
--- a/module/web/http.scm
+++ b/module/web/http.scm
@@ -1,6 +1,6 @@
 ;;; HTTP messages
 
-;; Copyright (C)  2010-2017 Free Software Foundation, Inc.
+;; Copyright (C)  2010-2018 Free Software Foundation, Inc.
 
 ;; This library is free software; you can redistribute it and/or
 ;; modify it under the terms of the GNU Lesser General Public
@@ -152,18 +152,35 @@ The default writer will call ‘put-string’."
         (lambda (val port)
           (put-string port val)))))
 
+(define spaces-and-tabs
+  (char-set #\space #\tab))
+
+(define (space-or-tab? c)
+  (case c
+    ((#\space #\tab) #t)
+    (else #f)))
+
 (define (read-header-line port)
-  "Read an HTTP header line and return it without its final CRLF or LF.
-Raise a 'bad-header' exception if the line does not end in CRLF or LF,
-or if EOF is reached."
+  "Read an HTTP header line, including any continuation lines, and
+return the combined string without its final CRLF or LF.  Raise a
+'bad-header' exception if the line does not end in CRLF or LF, or if EOF
+is reached."
   (match (%read-line port)
     (((? string? line) . #\newline)
      ;; '%read-line' does not consider #\return a delimiter; so if it's
      ;; there, remove it.  We are more tolerant than the RFC in that we
      ;; tolerate LF-only endings.
-     (if (string-suffix? "\r" line)
-         (string-drop-right line 1)
-         line))
+     (let ((line (if (string-suffix? "\r" line)
+                     (string-drop-right line 1)
+                     line)))
+       ;; If the next character is a space or tab, then there's at least
+       ;; one continuation line.  Read the continuation lines by calling
+       ;; 'read-header-line' recursively, and append them to this header
+       ;; line, folding the leading spaces and tabs to a single space.
+       (if (space-or-tab? (lookahead-char port))
+           (string-append line " " (string-trim (read-header-line port)
+                                                spaces-and-tabs))
+           line)))
     ((line . _)                                ;EOF or missing delimiter
      (bad-header 'read-header-line line))))
 
-- 
2.18.0


[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #3: [PATCH 2/2] PRELIMINARY: web: Fix parsing of HTTP Content-Type header --]
[-- Type: text/x-patch, Size: 5181 bytes --]

From 6af35a3997887fe24620fc7448ded3649e04b82b Mon Sep 17 00:00:00 2001
From: Mark H Weaver <mhw@netris.org>
Date: Tue, 28 Aug 2018 23:15:36 -0400
Subject: [PATCH 2/2] PRELIMINARY: web: Fix parsing of HTTP Content-Type
 header.

---
 module/web/http.scm | 109 +++++++++++++++++++++++++++++++++++---------
 1 file changed, 88 insertions(+), 21 deletions(-)

diff --git a/module/web/http.scm b/module/web/http.scm
index 15f173173..6ccd853c1 100644
--- a/module/web/http.scm
+++ b/module/web/http.scm
@@ -290,16 +290,94 @@ as an ordered alist."
 (define (write-opaque-string val port)
   (put-string port val))
 
-(define separators-without-slash
-  (string->char-set "[^][()<>@,;:\\\"?= \t]"))
-(define (validate-media-type str)
-  (let ((idx (string-index str #\/)))
-    (and idx (= idx (string-rindex str #\/))
-         (not (string-index str separators-without-slash)))))
+(define separators
+  (string->char-set "()<>@,;:\\\"/[]?={} \t"))
+
+(define (ascii-char? c)
+  (char-set-contains? char-set:ascii c))
+
+(define valid-token-chars
+  (char-set-difference char-set:ascii
+                       char-set:iso-control
+                       separators))
+
+(define (valid-token? str)
+  (and (not (string-null? str))
+       (string-every valid-token-chars str)))
+
+(define (string-skip* s pred i)
+  (or (string-skip s pred i)
+      (string-length s)))
+
+(define (parse-token str i)
+  (let* ((i   (string-skip* str spaces-and-tabs i))
+         (end (string-skip* str valid-token-chars i)))
+    (and (< i end)
+         (cons end (substring str i end)))))
+
+(define valid-text-chars
+  (char-set-adjoin (char-set-difference (ucs-range->char-set 0 256)
+                                        char-set:iso-control)
+                   #\space #\tab))
+
+(define (text-char? c)
+  (char-set-contains? valid-text-chars c))
+
+(define (parse-quoted-string str i)
+  (let ((len (string-length str))
+        (i   (string-skip* str spaces-and-tabs i)))
+    (and (< i len)
+         (eqv? #\" (string-ref str i))
+         (let loop ((i (+ i 1))
+                    (accum '()))
+           (and (< i len)
+                (match (string-ref str i)
+                  (#\" (cons (+ i 1) (reverse-list->string accum)))
+                  (#\\ (and (< (+ i 1) len)
+                            (let ((c (string-ref str (+ i 1))))
+                              (and (ascii-char? c)
+                                   (loop (+ i 2) (cons c accum))))))
+                  (c   (and (text-char? c)
+                            (loop (+ i 1) (cons c accum))))))))))
+
+(define (parse-parameter str i)
+  (let* ((eq (string-index str #\= i))
+         (attribute (string-trim-both (substring str i eq)
+                                      spaces-and-tabs)))
+    (and (valid-token? attribute)
+         (match (or (parse-token         str (+ eq 1))
+                    (parse-quoted-string str (+ eq 1)))
+           ((i . val) (cons i (cons (string->symbol attribute) val)))
+           (#f        #f)))))
+
+(define (parse-parameter-list str i)
+  (let ((len (string-length str))
+        (i   (string-skip* str spaces-and-tabs i)))
+    (if (= i len)
+        '()
+        (and (< i len)
+             (eqv? #\; (string-ref str i))
+             (match (parse-parameter str (+ i 1))
+               (#f      #f)
+               ((i . p) (match (parse-parameter-list str i)
+                          (#f  #f)
+                          (lst (cons p lst)))))))))
+
 (define (parse-media-type str)
-  (unless (validate-media-type str)
-    (bad-header-component 'media-type str))
-  (string->symbol str))
+  (let* ((i (or (string-index str #\;)
+                (string-length str)))
+         (params (parse-parameter-list str i)))
+    (or (match (string-split (substring str 0 i) #\/)
+          ((type* subtype*)
+           (let ((type    (string-trim-both type*    spaces-and-tabs))
+                 (subtype (string-trim-both subtype* spaces-and-tabs)))
+             (and (valid-token? type)
+                  (valid-token? subtype)
+                  params
+                  (cons (string->symbol (string-append type "/" subtype))
+                        params))))
+          (_ #f))
+        (bad-header 'content-type str))))
 
 (define* (skip-whitespace str #:optional (start 0) (end (string-length str)))
   (let lp ((i start))
@@ -1617,18 +1695,7 @@ treated specially, and is just returned as a plain string."
 ;; Content-Type = media-type
 ;;
 (declare-header! "Content-Type"
-  (lambda (str)
-    (let ((parts (string-split str #\;)))
-      (cons (parse-media-type (car parts))
-            (map (lambda (x)
-                   (let ((eq (string-index x #\=)))
-                     (unless (and eq (= eq (string-rindex x #\=)))
-                       (bad-header 'content-type str))
-                     (cons
-                      (string->symbol
-                       (string-trim x char-set:whitespace 0 eq))
-                      (string-trim-right x char-set:whitespace (1+ eq)))))
-                 (cdr parts)))))
+  parse-media-type
   (lambda (val)
     (match val
       (((? symbol?) ((? symbol?) . (? string?)) ...) #t)
-- 
2.18.0


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* bug#32528: http-post breaks with XML response payload containing boundary
  2018-08-28 21:51 ` Mark H Weaver
  2018-08-29  3:28   ` Mark H Weaver
@ 2018-08-29 10:26   ` Ricardo Wurmus
  1 sibling, 0 replies; 5+ messages in thread
From: Ricardo Wurmus @ 2018-08-29 10:26 UTC (permalink / raw)
  To: Mark H Weaver; +Cc: 32528


Hi Mark,

> Ricardo Wurmus <rekado@elephly.net> writes:
>
[…]
>> The reason why it fails is that Guile processes the response and treats
>> the *payload* contained in the XML response as HTTP.
>
> No, this was a good guess, but it's not actually the problem.

You are right.  I also ended up trying with “wget --save-headers” after
sending the bug report and noticed the offending header like you did:

>   Content-Type: multipart/related; type="text/xml"; start="<main_envelope>"; boundary="=-=-="
>
>   <?xml [...]

I assumed it was part of the payload when it really was a regular
header after all.

> The problem is simply that our Content-Type header parser is broken.
> It's very simplistic and merely splits the string wherever ';' is found,
> and then checks to make sure there's only one '=' in each parameter,
> without taking into account that quoted strings in the parameters might
> include those characters.

Right.  I worked around this in guile-debbugs simply by replacing the
Content-Type header parser with one that lacks the check for the unique
“=” in the string part.

> I'll work on a proper parser for Content-Type headers.

Thanks!

--
Ricardo






^ permalink raw reply	[flat|nested] 5+ messages in thread

* bug#32528: http-post breaks with XML response payload containing boundary
  2018-08-29  3:28   ` Mark H Weaver
@ 2019-06-25  8:25     ` Ludovic Courtès
  0 siblings, 0 replies; 5+ messages in thread
From: Ludovic Courtès @ 2019-06-25  8:25 UTC (permalink / raw)
  To: Mark H Weaver; +Cc: 32528

Hi Mark,

Mark H Weaver <mhw@netris.org> skribis:

>>From 6af35a3997887fe24620fc7448ded3649e04b82b Mon Sep 17 00:00:00 2001
> From: Mark H Weaver <mhw@netris.org>
> Date: Tue, 28 Aug 2018 23:15:36 -0400
> Subject: [PATCH 2/2] PRELIMINARY: web: Fix parsing of HTTP Content-Type
>  header.
>
> ---
>  module/web/http.scm | 109 +++++++++++++++++++++++++++++++++++---------
>  1 file changed, 88 insertions(+), 21 deletions(-)

This patch would be nice to have, if and when you can complete it.

Thanks,
Ludo’.





^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2019-06-25  8:25 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2018-08-25  8:49 bug#32528: http-post breaks with XML response payload containing boundary Ricardo Wurmus
2018-08-28 21:51 ` Mark H Weaver
2018-08-29  3:28   ` Mark H Weaver
2019-06-25  8:25     ` Ludovic Courtès
2018-08-29 10:26   ` Ricardo Wurmus

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).