1 // Copyright 2005-2019 The Mumble Developers. All rights reserved.
2 // Use of this source code is governed by a BSD-style license
3 // that can be found in the LICENSE file at the root of the
4 // Mumble source tree or at <https://www.mumble.info/LICENSE>.
5
6 #include "EnvUtils.h"
7
8 #include <QByteArray>
9
getenv(QString name)10 QString EnvUtils::getenv(QString name) {
11 #ifdef Q_OS_WIN
12 QByteArray buf;
13 size_t requiredSize = 0;
14
15 static_assert(sizeof(wchar_t) == sizeof(ushort), "expected 2-byte wchar_t");
16
17 const wchar_t *wname = reinterpret_cast<const wchar_t *>(name.utf16());
18
19 // Query the required buffer size (in elements).
20 if (_wgetenv_s(&requiredSize, 0, 0, wname) != 0) {
21 return QString();
22 }
23 if (requiredSize == 0) {
24 return QString();
25 }
26
27 // Resize buf to fit the value and put it there.
28 buf.resize(static_cast<int>(requiredSize * sizeof(wchar_t)));
29 if (_wgetenv_s(&requiredSize, reinterpret_cast<wchar_t *>(buf.data()), requiredSize, wname) != 0) {
30 return QString();
31 }
32
33 // Convert the value to QString and return it.
34 const wchar_t *wbuf = reinterpret_cast<const wchar_t *>(buf.constData());
35 return QString::fromWCharArray(wbuf);
36 #else
37 QByteArray name8bit = name.toLocal8Bit();
38 char *val = ::getenv(name8bit.constData());
39 if (val == NULL) {
40 return QString();
41 }
42 return QString::fromLocal8Bit(val);
43 #endif
44 }
45
setenv(QString name,QString value)46 bool EnvUtils::setenv(QString name, QString value) {
47 #ifdef Q_OS_WIN
48 return _wputenv_s(reinterpret_cast<const wchar_t *>(name.utf16()), reinterpret_cast<const wchar_t *>(value.utf16())) == 0;
49 #else
50 const int OVERWRITE = 1;
51 return ::setenv(name.toLocal8Bit().constData(), value.toLocal8Bit().constData(), OVERWRITE) == 0;
52 #endif
53 }
54