Subject: Re: bug#32528: http-post breaks with XML response payload containing boundary

From: Mark H Weaver <[email-masked]>
Date: Tue, 28 Aug 2018 23:28:19 -0400

Mark H Weaver <[email-masked]> writes:

> Ricardo Wurmus <[email-masked]> 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 [email-masked] [...]
[...]
--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

>From 41764d60dba80126b3c97f883d0225510b55f3fa Mon Sep 17 00:00:00 2001
From: Mark H Weaver <[email-masked]>
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

>From 6af35a3997887fe24620fc7448ded3649e04b82b Mon Sep 17 00:00:00 2001
From: Mark H Weaver <[email-masked]>
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