-
Notifications
You must be signed in to change notification settings - Fork 20
/
WLANOptimizer.cpp
369 lines (294 loc) · 9.95 KB
/
WLANOptimizer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/** \file
\brief WLAN Optimizer
\copyright Copyright (c) 2018 Christopher A. Taylor. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of WLAN Optimizer nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "WLANOptimizer.h"
#include <atomic>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <memory>
#include <chrono>
using namespace std::chrono_literals;
static std::mutex APILock;
//------------------------------------------------------------------------------
// Windows Version
#ifdef _WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT _WIN32_WINNT_WIN7 /* must be defined for wlanapi.h */
#include <windows.h>
#include <wlanapi.h>
#pragma comment(lib, "wlanapi")
//#pragma comment(lib, "ole32")
// Client handle shared between all calls.
// This is done because settings only persist until handle or app is closed.
static HANDLE m_clientHandle = nullptr;
// Set a Wlan setting
static OptimizeWLAN_Result SetWlanSetting(
const GUID* guidPtr,
WLAN_INTF_OPCODE opcode,
bool enable)
{
DWORD dataSize = 0;
void* dataPtr = nullptr;
WLAN_OPCODE_VALUE_TYPE opcodeType = wlan_opcode_value_type_invalid;
DWORD queryResult = ::WlanQueryInterface(
m_clientHandle,
guidPtr,
opcode,
nullptr,
&dataSize,
&dataPtr,
&opcodeType);
// If the query call failed:
if (queryResult != ERROR_SUCCESS ||
dataSize < 1 ||
!dataPtr ||
opcodeType == wlan_opcode_value_type_invalid)
{
return OptimizeWLAN_ReadFailure;
}
// If the current value of the setting is already the one we wanted:
const bool currentValue = *(BOOL*)dataPtr != 0;
if (currentValue == enable) {
// Avoid extra work (common case in steady state)
return OptimizeWLAN_Success;
}
BOOL targetValue = enable ? TRUE : FALSE;
// Note this function takes about 1 second to complete.
const DWORD setResult = ::WlanSetInterface(
m_clientHandle,
guidPtr,
opcode,
(DWORD)sizeof(targetValue),
&targetValue,
nullptr);
// If set call failed:
if (setResult != ERROR_SUCCESS)
{
// If the error was related to permissions, bubble that up:
if (setResult == ERROR_ACCESS_DENIED) {
return OptimizeWLAN_AccessDenied;
}
return OptimizeWLAN_SetFailure;
}
dataSize = 0;
dataPtr = nullptr;
opcodeType = wlan_opcode_value_type_invalid;
queryResult = ::WlanQueryInterface(
m_clientHandle,
guidPtr,
opcode,
nullptr,
&dataSize,
&dataPtr,
&opcodeType);
// If the readback call failed:
if (queryResult != ERROR_SUCCESS ||
dataSize < 1 ||
!dataPtr ||
*(BOOL*)dataPtr != targetValue ||
opcodeType == wlan_opcode_value_type_invalid)
{
return OptimizeWLAN_ReadFailure;
}
return OptimizeWLAN_Success;
}
#endif // _WIN32
//------------------------------------------------------------------------------
// OptimizeWLAN()
int OptimizeWLAN(int enable)
{
std::lock_guard<std::mutex> locker(APILock);
#ifdef _WIN32
// If the handle has not been opened yet:
if (!m_clientHandle)
{
const DWORD clientVersion = 2;
DWORD negotiatedVersion = 0;
const DWORD openResult = ::WlanOpenHandle(
clientVersion,
nullptr,
&negotiatedVersion,
&m_clientHandle);
// If the handle could not be opened:
if (openResult != ERROR_SUCCESS ||
!m_clientHandle)
{
return OptimizeWLAN_Unavailable;
}
}
OptimizeWLAN_Result result = OptimizeWLAN_Success;
bool foundConnection = false;
WLAN_INTERFACE_INFO_LIST* infoListPtr = nullptr;
const DWORD enumResult = ::WlanEnumInterfaces(
m_clientHandle,
nullptr,
&infoListPtr);
// If the enumeration call succeeded:
if (enumResult == ERROR_SUCCESS &&
infoListPtr != nullptr)
{
const int count = (int)infoListPtr->dwNumberOfItems;
// For each item:
for (int i = 0; i < count; ++i)
{
const WLAN_INTERFACE_INFO* info = &infoListPtr->InterfaceInfo[i];
// In my testing I found that only connected WiFi adapters are able to change this setting,
// as otherwise WlanSetInterface() returns ERROR_INVALID_STATE.
if (info->isState == wlan_interface_state_connected)
{
OptimizeWLAN_Result setResult;
setResult = SetWlanSetting(
&info->InterfaceGuid,
wlan_intf_opcode_media_streaming_mode,
enable != 0);
// If a failure occurred:
if (setResult != OptimizeWLAN_Success) {
// Return this failure
result = setResult;
}
setResult = SetWlanSetting(
&info->InterfaceGuid,
wlan_intf_opcode_background_scan_enabled,
enable == 0);
// If a failure occurred:
if (setResult != OptimizeWLAN_Success) {
// Return this failure
result = setResult;
}
foundConnection = true;
}
}
}
// Free memory for the enumerated info list
if (infoListPtr != nullptr) {
::WlanFreeMemory(infoListPtr);
}
// Leak handle intentionally here - When the app closes it will be released.
//::WlanCloseHandle(m_clientHandle, nullptr);
// If no connections were found:
if (!foundConnection) {
return OptimizeWLAN_NoConnections;
}
return result;
#else //_WIN32
(void)enable; // Unused
// TBD: Are there also correctable issues on Mac/Linux?
return OptimizeWLAN_Unavailable;
#endif //_WIN32
}
//------------------------------------------------------------------------------
// WLANOptimizerThread
class WLANOptimizerThread
{
public:
/// Start the optimizer thread
void Start();
/// Stop the optimizer thread
void Stop();
protected:
/// Lock preventing thread safety issues around Start() and Stop()
mutable std::mutex StartStopLock;
/// Lock protecting WakeCondition
mutable std::mutex WakeLock;
/// Condition that indicates the thread should wake up
std::condition_variable WakeCondition;
/// Background thread
std::shared_ptr<std::thread> Thread;
/// Should thread terminate?
std::atomic<bool> Terminated = ATOMIC_VAR_INIT(true);
/// Thread loop
void Loop();
};
void WLANOptimizerThread::Start()
{
std::lock_guard<std::mutex> startStopLocker(StartStopLock);
if (!Thread)
{
Terminated = false;
Thread = std::make_shared<std::thread>(&WLANOptimizerThread::Loop, this);
}
}
void WLANOptimizerThread::Stop()
{
std::lock_guard<std::mutex> startStopLocker(StartStopLock);
if (Thread)
{
Terminated = true;
// Make sure that queue notification happens after termination flag is set
{
std::unique_lock<std::mutex> wakeLocker(WakeLock);
WakeCondition.notify_all();
}
// Wait for thread to stop
try
{
if (Thread->joinable()) {
Thread->join();
}
}
catch (std::system_error& /*err*/)
{
}
Thread = nullptr;
}
}
void WLANOptimizerThread::Loop()
{
// Time between optimization attempts. Retries because WiFi might reconnect.
static const auto kOptimizeInterval = 11s; // chrono_literals
while (!Terminated)
{
int optimizeResult = OptimizeWLAN(1);
// If result was a failure code,
// and the code was not that no connections were available:
if (optimizeResult != OptimizeWLAN_Success &&
optimizeResult != OptimizeWLAN_NoConnections)
{
// Stop trying to optimize WLAN if we hit an unexpected failure
break;
}
// unique_lock used since QueueCondition.wait requires it
std::unique_lock<std::mutex> locker(WakeLock);
if (!Terminated) {
WakeCondition.wait_for(locker, kOptimizeInterval);
}
}
}
static WLANOptimizerThread m_WlanOptimizer;
void StartWLANOptimizerThread()
{
#ifdef _WIN32
// Only run the thread on Windows because currently it has no optimizations
// for other platforms.
m_WlanOptimizer.Start();
#endif // _WIN32
}
void StopWLANOptimizerThread()
{
#ifdef _WIN32
m_WlanOptimizer.Stop();
#endif // _WIN32
}