Re: possible encoding issues with libxml2 functions

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: Noah Misch <noah(at)leadboat(dot)com>
Cc: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: possible encoding issues with libxml2 functions
Date: 2017-08-19 07:13:50
Message-ID: CAFj8pRA9N9kd2ZqsH3oieonPB5JeVPgHRR6XDTfhro9x69ftVg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

>
> Isn't the most correct solution to call xml_parse function?
>

I am reply to self. Probably not.

Now, I am thinking so I found a reason of this issue. The document
processed in xpath_internal is passed to libXML2 by

doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL, NULL, 0);

We don't pass a encoding parameter so libXML2 expecting "UTF8" or expecting
correct encoding decl in XML document. When we pass incorrect document -
XML is in database encoding, but encoding decl is original, then it should
to fail.

the regress test can looks like your (but all chars are valid there)

postgres=# do $$
declare str text;
begin
if current_setting('server_encoding') <> 'UTF8' then return; end if;
str = '<?xml version="1.0"
encoding="windows-1250"?><enprimeur><vino><id>909</id><remark>'
|| convert_from('\xc588', 'UTF8')
|| '</remark></vino></enprimeur>';
raise notice '%', xpath('/enprimeur/vino/id', str::xml);
end; $$;
ERROR: could not parse XML document
DETAIL: input conversion failed due to input error, bytes 0x88 0x3C 0x2F
0x72
line 1: switching encoding: encoder error
�</remark></vino></enprimeur>
^
CONTEXT: PL/pgSQL function inline_code_block line 8 at RAISE

After correct fix:

doc = xmlCtxtReadMemory(ctxt, (char *) string, len, NULL,
pg_encoding_to_char(GetDatabaseEncoding()),
0);

It is working

postgres=# do $$
declare str text;
begin
if current_setting('server_encoding') <> 'UTF8' then return; end if;
str = '<?xml version="1.0"
encoding="windows-1250"?><enprimeur><vino><id>909</id><remark>'
|| convert_from('\xc588', 'UTF8')
|| '</remark></vino></enprimeur>';
raise notice '%', xpath('/enprimeur/vino/id', str::xml);
end; $$;
NOTICE: {<id>909</id>}
DO

This fix should be apply to xmltable function too.

patch attached

It doesn't fix xpath and xmltable functions issues when server encoding is
not UTF8. Looks so XPath functions from libXML2 requires UTF8 encoded
strings and the result is in UTF8 too - so result should be recoded to
server encoding.

I didn't find any info how to enable libXML2 XPath functions for other
encoding than UTF8 :( ??

Regards

Pavel

> Regards
>
> Pavel
>

Attachment Content-Type Size
encoding_for_xmlCtxtReadMemory.patch text/x-patch 4.3 KB

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Ildar Musin 2017-08-19 08:44:18 Re: Proposal: global index
Previous Message Amit Kapila 2017-08-19 06:07:31 Re: Page Scan Mode in Hash Index