util: buffer: Properly URLencode strings

According to rfc3986:

2.3.  Unreserved Characters

   Characters that are allowed in a URI but do not have a reserved
   purpose are called unreserved.  These include uppercase and lowercase
   letters, decimal digits, hyphen, period, underscore, and tilde.

      unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

   URIs that differ in the replacement of an unreserved character with
   its corresponding percent-encoded US-ASCII octet are equivalent: they
   identify the same resource.  However, URI comparison implementations
   do not always perform normalization prior to comparison (see Section
   6).  For consistency, percent-encoded octets in the ranges of ALPHA
   (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E),
   underscore (%5F), or tilde (%7E) should not be created by URI
   producers and, when found in a URI, should be decoded to their
   corresponding unreserved characters by URI normalizers.

Thus we must not include few other characters which don't match
c_isalpha to conform to the rules.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
This commit is contained in:
Peter Krempa 2019-10-24 13:23:32 +02:00
parent 5e8551fbc0
commit 5fdad0db2c
2 changed files with 13 additions and 3 deletions

View File

@ -638,6 +638,16 @@ virBufferEscape(virBufferPtr buf, char escape, const char *toescape,
}
static bool
virBufferURIEncodeCharIsUnencoded(char c)
{
if (c == '-' || c == '.' || c == '_' || c == '~')
return true;
return c_isalnum(c);
}
/**
* virBufferURIEncodeString:
* @buf: the buffer to append to
@ -664,7 +674,7 @@ virBufferURIEncodeString(virBufferPtr buf, const char *str)
virBufferAddLit(buf, ""); /* auto-indent */
for (p = str; *p; ++p) {
if (c_isalnum(*p))
if (virBufferURIEncodeCharIsUnencoded(*p))
grow_size++;
else
grow_size += 3; /* %ab */
@ -674,7 +684,7 @@ virBufferURIEncodeString(virBufferPtr buf, const char *str)
return;
for (p = str; *p; ++p) {
if (c_isalnum(*p)) {
if (virBufferURIEncodeCharIsUnencoded(*p)) {
buf->content[buf->use++] = *p;
} else {
uc = (unsigned char) *p;

View File

@ -184,7 +184,7 @@ mymain(void)
{ NULL, NULL, false },
};
TEST_FULL("spice://[3ffe::104]:5900/?tlsSubject=C=XX,L=Testtown,O=Test%20Company,CN=tester.test",
"spice://[3ffe::104]:5900/?tlsSubject=C%3dXX%2cL%3dTesttown%2cO%3dTest%20Company%2cCN%3dtester%2etest",
"spice://[3ffe::104]:5900/?tlsSubject=C%3dXX%2cL%3dTesttown%2cO%3dTest%20Company%2cCN%3dtester.test",
"spice", "3ffe::104", 5900, "/", "tlsSubject=C=XX,L=Testtown,O=Test%20Company,CN=tester.test", NULL, NULL, spiceparams);
virURIParam params1[] = {