Blob Blame History Raw
From 8406c694eb58e610fbf94eba00719e097bad34d8 Mon Sep 17 00:00:00 2001
From: Stephan Bergmann <sbergman@redhat.com>
Date: Tue, 4 Sep 2018 17:14:21 +0200
Subject: [PATCH] Properly encode OAuth2 credentials

Originally created as <https://gerrit.libreoffice.org/#/c/59986/> "Properly
encode OAuth2 credentials".  I was not sure which C++ version to target, so kept
it pretty basic.
---
 src/libcmis/oauth2-providers.cxx | 29 +++++++++++++++++++++++++++--
 1 file changed, 27 insertions(+), 2 deletions(-)

diff --git a/src/libcmis/oauth2-providers.cxx b/src/libcmis/oauth2-providers.cxx
index dd872dd..c14438f 100644
--- a/src/libcmis/oauth2-providers.cxx
+++ b/src/libcmis/oauth2-providers.cxx
@@ -26,6 +26,8 @@
  * instead of those above.
  */
 
+#include <cassert>
+
 #include <libxml/HTMLparser.h>
 #include <libxml/xmlreader.h>
 
@@ -41,6 +43,29 @@
 
 using namespace std;
 
+namespace {
+
+// See <https://url.spec.whatwg.org/#concept-urlencoded-byte-serializer>:
+void addXWwwFormUrlencoded(std::string * buffer, std::string const & data) {
+    assert(buffer);
+    for (string::const_iterator i = data.begin(); i != data.end(); ++i) {
+        unsigned char c = static_cast<unsigned char>(*i);
+        if (c == ' ' || c == '*' || c == '-' || c == '.' || (c >= '0' && c <= '9')
+            || (c >= 'A' && c <= 'Z') || c == '_' || (c >= 'a' && c <= 'z'))
+        {
+            *buffer += static_cast<char>(c);
+        } else {
+            static const char hex[16] = {
+                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+            *buffer += '%';
+            *buffer += hex[c >> 4];
+            *buffer += hex[c & 0xF];
+        }
+    }
+}
+
+}
+
 string OAuth2Providers::OAuth2Gdrive( HttpSession* session, const string& authUrl,
                                       const string& username, const string& password )
 {
@@ -93,7 +118,7 @@ string OAuth2Providers::OAuth2Gdrive( HttpSession* session, const string& authUr
         return string( );
 
     loginEmailPost += "Email=";
-    loginEmailPost += string( username );
+    addXWwwFormUrlencoded(&loginEmailPost, username);
 
     istringstream loginEmailIs( loginEmailPost );
     string loginEmailRes;
@@ -115,7 +140,7 @@ string OAuth2Providers::OAuth2Gdrive( HttpSession* session, const string& authUr
         return string( );
 
     loginPasswdPost += "Passwd=";
-    loginPasswdPost += string( password );
+    addXWwwFormUrlencoded(&loginPasswdPost, password);
 
     istringstream loginPasswdIs( loginPasswdPost );
     string loginPasswdRes;
-- 
2.17.1