Skip to content

CurlAsyncHTTPClient does not support internationalized domain names #1490

Closed

Description

@Sjord

When I try to request a page with non-ASCII characters in the URL, e.g. http://stützstrümpfe.de/ or https://nl.wikipedia.org/wiki/België, I get an UnicodeEncodeError exception when using the curl client. It works as expected with the default simple HTTP client.

This can be fixed by splitting the URL and encoding all parts correctly, as in this example.

Script to reproduce:

# coding: utf-8
from tornado.httpclient import AsyncHTTPClient, HTTPClient
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
http_client = HTTPClient()
http_client.fetch('https://nl.wikipedia.org/wiki/België')
http_client.fetch('http://www.stützstrümpfe.de')

Exception:

Traceback (most recent call last):
  File "reproduce.py", line 6, in <module>
    http_client.fetch('https://nl.wikipedia.org/wiki/België')
  File "/home/sjoerd/.virtualenvs/protomon/lib/python3.4/site-packages/tornado/httpclient.py", line 102, in fetch
    self._async_client.fetch, request, **kwargs))
  File "/home/sjoerd/.virtualenvs/protomon/lib/python3.4/site-packages/tornado/ioloop.py", line 445, in run_sync
    return future_cell[0].result()
  File "/home/sjoerd/.virtualenvs/protomon/lib/python3.4/site-packages/tornado/concurrent.py", line 215, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/home/sjoerd/.virtualenvs/protomon/lib/python3.4/site-packages/tornado/curl_httpclient.py", line 214, in _process_queue
    curl.info["headers"])
  File "/home/sjoerd/.virtualenvs/protomon/lib/python3.4/site-packages/tornado/curl_httpclient.py", line 283, in _curl_setup_request
    curl.setopt(pycurl.URL, native_str(request.url))
UnicodeEncodeError: 'ascii' codec can't encode character '\xeb' in position 35: ordinal not in range(128)

Activity

  1. bdarnell commented on Aug 20, 2015

    @bdarnell
    Member

    There are two problems here. One is a difference between Python 2 and 3: The België URL works in python 2 but not in 3. This is probably a pycurl bug: it's following the python 2 rules where bytes and unicode are interchangeable only if they are ascii-only, when instead it should either disallow the implicit conversion completely or use utf8 instead of ascii. (this is exacerbated by Tornado's use of native_str() here; if we didn't do that then you could work around the problem by encoding the url yourself.

    Second, even in Python 2, IDNs don't seem to be working. My copy of libcurl (installed from macports) was not linked against libidn (a quick google search shows that this was disabled by default for security reasons recently). Even when I re-enabled it it's not working for me; I'm not sure what's going on.

  2. Sjord commented on Sep 2, 2015

    @Sjord
    Author

    I submitted an issue to pycurl about this.

  3. Sjord commented on Nov 26, 2015

    @Sjord
    Author

    Could you take another look at this now @p from pycurl replied on the other bug?

  4. bdarnell commented on Dec 8, 2015

    @bdarnell
    Member

    After some more experimentation, libcurl's behavior looks inconsistent: If there are non-ascii characters in the hostname, libcurl will perform the IDN conversion for you (if it is linked against libidn and you have called locale.setlocale()). However, if there are non-ascii characters elsewhere in the URL, libcurl leaves those bytes as they are instead of percent-encoding them (This happens to work in many cases at least for utf8, but it violates the spec).

    Is there any value to having libcurl handle half of the IRI-to-URI conversion? I don't think so, but it needs some investigation (do things like the Host: header and TLS certificate verification work when only given the idna-encoded hostname, or do they need to see the unicode hostname in some other encoding?). Assuming the answer is no, it sounds like we just need to apply a parse-and-encode function like the one in the linked gist before passing unicode URLs into libcurl (and we could do this in tornado.httpclient.HTTPRequest so simple_httpclient works the same way. If simple_httpclient is doing the right thing for non-ascii urls it's mostly by accident). This would avoid any confusion around whether or not libcurl is linked against libidn and whether the locale module is configured appropriately.

    We could also just push the burden back up to the application: we've never claimed to support IRIs, only URLs, so support for IDNs and IRIs is a new feature rather than a bug fix. However, I think that HTTP clients should support IRIs, so it would be good for Tornado to do this conversion itself.

  5. p commented on Dec 17, 2015

    @p
    http_client.fetch('https://nl.wikipedia.org/wiki/België')
    

    My reading of RFC 3986 suggests this is not a valid URL. I also don't know enough about IDNs to know whether IDN spec covers escaping of paths and query strings, but in Russian domains one may well expect a URL like that to be encoded into either utf-8 or one of the codepage encodings (cp1251, koi8-r) and sent to the server without invoking IDN transforms.

  6. bdarnell commented on Dec 18, 2015

    @bdarnell
    Member

    Right, these strings are not valid URIs because they contain non-ASCII characters. They are, however, valid IRIs as defined in RFC 3987. The question is which layer is responsible for performing the IRI-to-URI conversion. It's fine with me if the answer to that is Tornado's AsyncHTTPClient, although you could argue that it should be libcurl's responsibility instead (it already does part of the IRI conversion by transforming non-ASCII domain names, but it's not really possible to make use of this functionality if it doesn't also handle the rest of the IRI).

    I withdraw my earlier comment about there being a pycurl bug, BTW: unless libcurl intends to handle the complete IRI conversion, then pycurl is reasonable to insist that URLs only contain ASCII.

  7. p commented on Dec 20, 2015

    @p

    OK, reading RFC 3987 it seems that IRIs are utf8-encoded unicode, hence the feature request may be phrased as "when pycurl receives a unicode string, assume it is a IRI and utf-8 encode it (and url-encode as necessary to convert a IRI to URI)".

    Transforming byte strings seems like a bad idea, hence the conversion would only be done for unicode strings.

    it should be libcurl's responsibility instead (it already does part of the IRI conversion by transforming non-ASCII domain names, but it's not really possible to make use of this functionality if it doesn't also handle the rest of the IRI).

    Can you give an example of a conversion that libcurl performs?

  8. bdarnell commented on Dec 22, 2015

    @bdarnell
    Member

    the feature request may be phrased as "when pycurl receives a unicode string, assume it is a IRI and utf-8 encode it (and url-encode as necessary to convert a IRI to URI)".

    That's the right idea, but I don't actually think pycurl should do this. IMHO pycurl should be a thin wrapper around libcurl, and if libcurl requires URIs instead of IRIs, pycurl should do the same.

    My preference would be for libcurl to add a CURLOPT_URL_UTF8 flag (or more flexibly, an arbitrary CURLOPT_URL_ENCODING), which when set would trigger IRI processing of the given URL. Then if pycurl gets a unicode string for the url it would encode it accordingly and pass it off to libcurl.

    Transforming byte strings seems like a bad idea, hence the conversion would only be done for unicode strings.

    Yes.

    Can you give an example of a conversion that libcurl performs?

    When libcurl is configured to use libidn (which is not the default), it will perform the IDN transformation on the hostname portion of a URL (contrary to RFC 3987, it uses the system default encoding rather than UTF8. This means that the locale library must be initialized). It does nothing to the path portion of the URL.

    The following script demonstrates this behavior on Python 2.7 with Tornado 4.3, pycurl 7.19.5.3, and 7.45.0 compiled with libidn (note that it may fail if the default encoding is not utf8):

    # -*- coding: utf-8 -*-
    from tornado.curl_httpclient import CurlAsyncHTTPClient
    from tornado.httpclient import HTTPClient
    from tornado.options import options, parse_command_line
    import locale
    
    unicode_domain = 'http://stützstrümpfe.de/'
    unicode_path = 'https://nl.wikipedia.org/wiki/België'
    
    
    def main():
        locale.setlocale(locale.LC_ALL, '')
        options.logging = 'debug'
        parse_command_line()
    
        client = HTTPClient(CurlAsyncHTTPClient)
        client.fetch(unicode_domain, follow_redirects=False, raise_error=False)
        client.fetch(unicode_path, follow_redirects=False, raise_error=False)
    
    if __name__ == '__main__':
        main()
    

    The debugging output is somewhat verbose, but we can see that for the first url, it prints

    [D 151221 22:25:26 curl_httpclient:439] GET http://stützstrümpfe.de/
    [D 151221 22:25:26 curl_httpclient:484] Input domain encoded as `UTF-8'
    [D 151221 22:25:26 curl_httpclient:484] Trying 46.21.233.172...
    [D 151221 22:25:26 curl_httpclient:484] Connected to stützstrümpfe.de (46.21.233.172) port 80 (#0)
    [D 151221 22:25:26 curl_httpclient:487] > GET / HTTP/1.1
    [D 151221 22:25:26 curl_httpclient:487] > Host: xn--sttzstrmpfe-uhbf.de
    

    Indicating that it has transformed the url. For the second, it sends the raw string. Note that wikipedia recognizes this and redirects to a percent-encoded version:

    [D 151221 22:25:26 curl_httpclient:487] > GET /wiki/België HTTP/1.1
    ...
    [D 151221 22:25:26 curl_httpclient:487] < Location: https://nl.wikipedia.org/wiki/Belgi%C3%AB
    
  9. p commented on Dec 25, 2015

    @p
    [D 151221 22:25:26 curl_httpclient:439] GET http://stützstrümpfe.de/
    [D 151221 22:25:26 curl_httpclient:484] Input domain encoded as `UTF-8'
    

    Interesting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions