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);