Fix too small buffer in Websockets::DoClientConnect()
authorKrzysztof Malysa <k.malysa@samsung.com>
Tue, 2 Apr 2024 12:07:35 +0000 (14:07 +0200)
committerKrzysztof Jackiewicz <k.jackiewicz@samsung.com>
Fri, 12 Apr 2024 10:05:05 +0000 (12:05 +0200)
Change-Id: I23ce05a1e71b10224747c88065f98e3d17a30b81

srcs/websockets.cpp

index f7752bb73d360a34b92d8888e5f5181269c31b4e..e075ae3bde526f36975e7d696d53ea51cb92a097 100644 (file)
@@ -81,23 +81,31 @@ LwsContext *Websockets::CreateContext() noexcept
 Lws *Websockets::DoClientConnect(LwsContext *context, const std::string &url, int sslFlags) noexcept
 {
     struct lws_client_connect_info cInfo;
-    const char *protocol, *path1;
-    char path[128];
-    std::vector<char> urlMutable(url.c_str(), url.c_str() + url.size() + 1);
+    const char *protocol, *path;
+
+    std::vector<char> urlMutable;
+    urlMutable.reserve(url.size() + 3); // leave place for inserting {'/', '\0'}
+    urlMutable.insert(urlMutable.end(), url.c_str(), url.c_str() + url.size() + 1);
 
     memset(&cInfo, 0, sizeof cInfo);
 
     cInfo.port = WSS_PORT;
-    if (lws_parse_uri(urlMutable.data(), &protocol, &cInfo.address, &cInfo.port, &path1)) {
+    if (lws_parse_uri(urlMutable.data(), &protocol, &cInfo.address, &cInfo.port, &path)) {
         TRY_LOG_ERROR("lws_parse_uri() failed for " << url);
         return nullptr;
     }
 
-    path[0] = '/';
-    unsigned n = 0;
-    if (path1[0] == '/')
-        n = 1;
-    lws_strncpy(&path[1], &path1[n], sizeof(path) - n);
+    // path may point outside urlMutable.data() if path part is empty, but from the implementation
+    // it is equal to "/" then. So we need to add the leading '/' only if the path points to inside
+    // urlMutable.data()
+    if (urlMutable.data() <= path && path < urlMutable.data() + urlMutable.size()) {
+        urlMutable.insert(urlMutable.begin() + (path - urlMutable.data()), '/');
+    } else {
+        // In case the url's path part is absent, we have to insert it completely.
+        urlMutable.insert(urlMutable.end(), '/');
+        urlMutable.insert(urlMutable.end(), '\0');
+        path = urlMutable.data() + (urlMutable.size() - 2);
+    }
 
     if (strcmp(protocol, "wss") != 0) {
         TRY_LOG_ERROR("Unexpected protocol " << protocol);