OpenVPN 3 Core Library
Loading...
Searching...
No Matches
wstring.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12#pragma once
13
14#ifdef _WIN32
15
16#include <string>
17#include <vector>
18#include <memory>
19
20namespace openvpn::wstring {
21
28inline std::wstring from_utf8(const std::string &str)
29{
30 std::wstring wStr; // enable RVO
31 if (str.empty())
32 return wStr;
33 const int str_size = static_cast<int>(str.size());
34 const auto reqSize = ::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, nullptr, 0);
35 if (reqSize == 0)
36 throw std::runtime_error("MultiByteToWideChar(1) failed with code: [" + std::to_string(::GetLastError()) + "]");
37 wStr.resize(reqSize, L'\0'); // Allocate space
38 if (::MultiByteToWideChar(CP_UTF8, 0, str.data(), str_size, wStr.data(), reqSize) == 0)
39 throw std::runtime_error("MultiByteToWideChar(2) failed with code: [" + std::to_string(::GetLastError()) + "]");
40 return wStr;
41}
42
49inline std::string to_utf8(const std::wstring &wstr)
50{
51 std::string str; // For RVO
52 if (wstr.empty())
53 return str;
54 const int wstr_size = static_cast<int>(wstr.size());
55 const auto reqSize = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, nullptr, 0, nullptr, nullptr);
56 if (reqSize == 0)
57 throw std::runtime_error("WideCharToMultiByte(1) failed with code: [" + std::to_string(::GetLastError()) + "]");
58 str.resize(reqSize, '\0'); // Allocate space
59 if (::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, str.data(), reqSize, nullptr, nullptr) == 0)
60 throw std::runtime_error("WideCharToMultiByte(2) failed with code: [" + std::to_string(::GetLastError()) + "]");
61 return str;
62}
63
75inline std::wstring pack_string_vector(const std::vector<std::string> &strvec)
76{
77 if (strvec.empty())
78 {
79 return std::wstring(2, L'\0'); // empty MULTI_SZ
80 }
81 std::wstring ret;
82 for (auto &s : strvec)
83 {
84 ret += from_utf8(s);
85 ret += L'\0';
86 }
87 ret += L'\0';
88 return ret;
89}
90
91#endif // #ifdef _WIN32
92}
os<< "Session Name: "<< tbc-> session_name<< '\n';os<< "Layer: "<< tbc-> layer str()<< '\n'
std::string ret