{"id":178798,"date":"2020-06-03T17:55:23","date_gmt":"2020-06-03T17:55:23","guid":{"rendered":"https:\/\/www.noctua.org.uk\/blog\/?p=178798"},"modified":"2020-07-15T14:39:18","modified_gmt":"2020-07-15T14:39:18","slug":"unicodedecodeerror-with-stuff-from-the-network","status":"publish","type":"post","link":"https:\/\/www.noctua.org.uk\/blog\/2020\/06\/03\/unicodedecodeerror-with-stuff-from-the-network\/","title":{"rendered":"UnicodeDecodeError with stuff from the network"},"content":{"rendered":"\n<p>Occasionally I write about debugging, for the edification of others and to try to explain to muggles what I do all day. I ran into a fun one the other day.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Unicode<\/h3>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignright is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.jwz.org\/images\/2017\/frowning-pile-of-poo.png\" alt=\"\" width=\"206\" height=\"206\"\/><\/figure><\/div>\n\n\n\n<p>Joel Spolsky&#8217;s <a href=\"https:\/\/www.joelonsoftware.com\/2003\/10\/08\/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses\/\">explanation of Unicode<\/a> is excellent, but long. In brief: on a computer, we represent letters (&#8220;a&#8221;, &#8220;b&#8221; and so on) as numbers. Computers work with zeroes and ones, binary digits (or <em>bits<\/em>), usually in groups of 8 bits called <em>bytes<\/em>. Back in the mists of time, someone came up with <a href=\"https:\/\/en.wikipedia.org\/wiki\/ASCII\">ASCII<\/a>, a way to represent decent American letters by giving each letter a number. All those numbers fitted a single byte (a byte can represent 256 different numbers), so one byte was one letter, and all was well&#8230; unless you weren&#8217;t American and wanted to represent funny foreign letters like &#8220;\u00a3&#8221;, or some non-Latin alphabet, or a <a href=\"https:\/\/www.jwz.org\/blog\/2017\/11\/unicode-character-frowning-pile-of-poo-u1f979\/\">frowning pile of poo<\/a>.<\/p>\n\n\n\n<p>The modern way of handling those foreign letters and poos is Unicode. Each different letter still has a number assigned to it, but there are a lot them, so the numbers can be bigger than you can fit in a byte. Computers still like to work in bytes, so you need to represent a letter using a sequence of one or more bytes. A way of doing this is called an <em>encoding<\/em>. One popular encoding, <a href=\"https:\/\/en.wikipedia.org\/wiki\/UTF-8\">UTF-8<\/a>, has the handy feature that all those decent American letters have the same single byte representation as they did in ASCII, but other letters get longer sequences of bytes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Internet<\/h3>\n\n\n\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Series_of_tubes\">series of tubes<\/a> we call the Internet is a way of carrying bytes around. As a programmer, you often end up writing code to connect to other computers and read data. Suppose we just want to sit there forever doing something with a continuous stream of bytes the other computer is sending us<sup id=\"rf1-178798\"><a href=\"#fn1-178798\" title=\"We&#8217;ll not worry about the other side closing the connection or the wifi packing up, for now.\" rel=\"footnote\">1<\/a><\/sup>:<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">connection = connect_to_the_thing()\n\n# loop forever\nwhile True: \n    # receive up to 1024 bytes from the other computer\n    bytes = connection.recv(1024)\n    do_something_with(bytes)<\/pre><\/div>\n\n\n\n<p>The data that comes back from the other computer is a series of bytes. What if you know it&#8217;s UTF-8 encoded text, and you want to turn those bytes into that text?<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">connection = connect_to_the_thing()\n\n# loop forever\nwhile True: \n    # receive up to 1024 bytes from the other computer\n    bytes = connection.recv(1024)\n    # turn it into text\n    text = bytes.decode(\"utf-8\")\n    do_something_with(text)<\/pre><\/div>\n\n\n\n<p>This seems to work fine, but very occasionally crashes on line 5 with a mysterious error message: &#8220;UnicodeDecodeError: &#8216;utf-8&#8217; codec can&#8217;t decode byte 0xe2 in position 1023: unexpected end of data&#8221;. Whaaat?<\/p>\n\n\n\n<p>Some frantic Googling of &#8220;UnicodeDecodeError&#8221; turns up a bunch of people getting that error because they weren&#8217;t actually reading UTF-8 encoded text at all, but something else<sup id=\"rf2-178798\"><a href=\"#fn2-178798\" title=\"I do wonder whether questions on Stack Overflow about errors from Python&#8217;s Unicode handling have more views in the aggregate than the &#8220;&lt;a href=&quot;https:\/\/stackoverflow.com\/questions\/11828270\/how-do-i-exit-the-vim-editor&quot;&gt;How do I exit Vim&lt;\/a&gt;?&#8221; question (which is at 2.1 million views as I write this).\" rel=\"footnote\">2<\/a><\/sup>. So, you check what the other side is sending, and in this case, you&#8217;re pretty sure it <em>is<\/em> sending UTF-8. Whaaat?<\/p>\n\n\n\n<p>Squint at the error message a bit more, and you find it&#8217;s complaining about the last byte it&#8217;s read. You have to <a href=\"https:\/\/docs.python.org\/3\/library\/socket.html#socket.socket.recv\">give the <code>recv()<\/code> a maximum number of bytes to read<\/a>, so you picked 1024 (a handy power of 2, as is traditional). &#8220;Position 1023&#8221; is the 1024th byte received (since we start counting from 0, as is tradidional). That &#8220;0xe2&#8221; thing is <a href=\"https:\/\/www.mathsisfun.com\/hexadecimals.html\">hexadecimal<\/a> E2, equivalent to 11100010 in binary. Read the <a href=\"https:\/\/en.wikipedia.org\/wiki\/UTF-8#Description\">UTF-8 stuff<\/a> a bit more, and you find that 11100010 means &#8220;this letter is made up of this byte and the two more bytes following this one&#8221;. It stopped in the middle of the sequence of bytes which represent a single letter, hence the &#8220;unexpected end of data&#8221; in the error message.<\/p>\n\n\n\n<p>At this point, if you have control over the other computer, you might be thinking up cunning schemes to ensure that what it passes to each <a href=\"https:\/\/docs.python.org\/3\/library\/socket.html#socket.socket.send\"><code>send()<\/code><\/a> is always less than 1024 bytes at a time, without breaking up a multi-byte letter. After all, the data goes out in <a href=\"https:\/\/en.wikipedia.org\/wiki\/Network_packet\">packets<\/a>, so what you get when you invoke <code>recv()<\/code> must line up with the other side&#8217;s <code>send()<\/code>s, right? Wrong.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"alignright is-resized\"><a href=\"https:\/\/commons.wikimedia.org\/wiki\/File:Homing_pigeon.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/pics.livejournal.com\/pw201\/pic\/000f70dx\/s320x320\" alt=\"\" width=\"217\" height=\"174\"\/><\/a><figcaption>Avian carrier<\/figcaption><\/figure><\/div>\n\n\n\n<p>The series of tubes is narrower in some places than others, and your data <a href=\"https:\/\/en.wikipedia.org\/wiki\/IP_fragmentation\">may be broken up to fit<\/a>. A single <a href=\"https:\/\/tools.ietf.org\/html\/rfc1149\">carrier pigeon<\/a> can only carry so much weight, you see, and the RSPB is pretty strict about that sort of thing. All that&#8217;s guaranteed is that you get the bytes out in the order they went in, not how many you get out at a time.<\/p>\n\n\n\n<p>Fortunately, <a href=\"https:\/\/en.wikipedia.org\/wiki\/Guido_van_Rossum\">Guido<\/a> thought of this and blessed us with <code><a href=\"https:\/\/docs.python.org\/3\/library\/codecs.html#incrementaldecoder-objects\">IncrementalDecoder<\/a><\/code>, which knows how to remember that it was part way through a letter when it left off, so that the next time around the loop, it&#8217;ll hopefully get the rest of the bytes and give you the letter you were hoping for:<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"python\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">connection = connect_to_the_thing()\n\ndecoder_class = codecs.getincrementaldecoder(\"utf-8\")\n# Make a new instance of the decoder_class\ndecoder = decoder_class()\n\n# loop forever\nwhile True:\n    # receive up to 1024 bytes from the other computer\n    bytes = connection.recv(1024) \n    text = decoder.decode(bytes)\n    do_something_with(text)<\/pre><\/div>\n\n\n\n<p>Much better! Now to raise a <a href=\"https:\/\/github.com\/fgimian\/paramiko-expect\/pull\/60\">pull request<\/a> against <a href=\"https:\/\/github.com\/fgimian\/paramiko-expect\/blob\/136744afeb6d2c462a5da7450b68cde9a9319eca\/paramiko_expect.py#L156\">paramiko_expect<\/a>.<\/p>\n<hr class=\"footnotes\"><ol class=\"footnotes\" style=\"list-style-type:decimal\"><li id=\"fn1-178798\"><p >We&#8217;ll not worry about the other side closing the connection or the wifi packing up, for now.&nbsp;<a href=\"#rf1-178798\" class=\"backlink\" title=\"Return to footnote 1.\">&#8617;<\/a><\/p><\/li><li id=\"fn2-178798\"><p >I do wonder whether questions on Stack Overflow about errors from Python&#8217;s Unicode handling have more views in the aggregate than the &#8220;<a href=\"https:\/\/stackoverflow.com\/questions\/11828270\/how-do-i-exit-the-vim-editor\">How do I exit Vim<\/a>?&#8221; question (which is at 2.1 million views as I write this).&nbsp;<a href=\"#rf2-178798\" class=\"backlink\" title=\"Return to footnote 2.\">&#8617;<\/a><\/p><\/li><\/ol>","protected":false},"excerpt":{"rendered":"<p>Occasionally I write about debugging, for the edification of others and to try to explain to muggles what I do all day. I ran into a fun one the other day. Unicode Joel Spolsky&#8217;s explanation of Unicode is excellent, but long. In brief: on a computer, we represent letters (&#8220;a&#8221;, &#8220;b&#8221; and so on) as&hellip;<\/p>\n <a href=\"https:\/\/www.noctua.org.uk\/blog\/2020\/06\/03\/unicodedecodeerror-with-stuff-from-the-network\/\" title=\"UnicodeDecodeError with stuff from the network\" class=\"entry-more-link\"><span>Read More<\/span> <span class=\"screen-reader-text\">UnicodeDecodeError with stuff from the network<\/span><\/a>","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"Layout":"","footnotes":"","_links_to":"","_links_to_target":""},"categories":[19],"tags":[1281,146,151,1280],"class_list":["entry","author-paul","post-178798","post","type-post","status-publish","format-standard","category-blog","tag-network","tag-programming","tag-python","tag-unicode"],"_links":{"self":[{"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/posts\/178798","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/comments?post=178798"}],"version-history":[{"count":21,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/posts\/178798\/revisions"}],"predecessor-version":[{"id":178850,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/posts\/178798\/revisions\/178850"}],"wp:attachment":[{"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/media?parent=178798"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/categories?post=178798"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.noctua.org.uk\/blog\/wp-json\/wp\/v2\/tags?post=178798"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}