OSDN Git Service

5b201ae1fd7792fe214f483e48d1d2fb9d92f9fb
[mutilities/MUtilities.git] / src / OSSupport_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 //
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
21
22 #pragma once
23
24 //Internal
25 #include <MUtils/Global.h>
26 #include <MUtils/OSSupport.h>
27 #include "CriticalSection_Win32.h"
28
29 //Win32 API
30 #define WIN32_LEAN_AND_MEAN 1
31 #include <Windows.h>
32 #include <Objbase.h>
33 #include <Psapi.h>
34 #include <Sensapi.h>
35
36 //Qt
37 #include <QMap>
38 #include <QReadWriteLock>
39 #include <QLibrary>
40 #include <QDir>
41
42 //Main thread ID
43 static const DWORD g_main_thread_id = GetCurrentThreadId();
44
45 ///////////////////////////////////////////////////////////////////////////////
46 // SYSTEM MESSAGE
47 ///////////////////////////////////////////////////////////////////////////////
48
49 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
50
51 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
52 {
53         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
54 }
55
56 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
57 {
58         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
59 }
60
61 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
62 {
63         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////
67 // OS VERSION DETECTION
68 ///////////////////////////////////////////////////////////////////////////////
69
70 static bool g_os_version_initialized = false;
71 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
72 static QReadWriteLock g_os_version_lock;
73
74 //Maps marketing names to the actual Windows NT versions
75 static const struct
76 {
77         MUtils::OS::Version::os_version_t version;
78         const char friendlyName[64];
79 }
80 g_os_version_lut[] =
81 {
82         { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000"                                  },        //2000
83         { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" },        //XP
84         { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64"         },        //XP_x64
85         { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008"          },        //Vista
86         { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2"           },        //7
87         { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012"              },        //8
88         { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2"         },        //8.1
89         { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)"   },        //10
90         { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
91 };
92
93 static bool verify_os_version(const DWORD major, const DWORD minor)
94 {
95         OSVERSIONINFOEXW osvi;
96         DWORDLONG dwlConditionMask = 0;
97
98         //Initialize the OSVERSIONINFOEX structure
99         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
100         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
101         osvi.dwMajorVersion = major;
102         osvi.dwMinorVersion = minor;
103         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
104
105         //Initialize the condition mask
106         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
107         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
108         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
109
110         // Perform the test
111         const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
112
113         //Error checking
114         if(!ret)
115         {
116                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
117                 {
118                         qWarning("VerifyVersionInfo() system call has failed!");
119                 }
120         }
121
122         return (ret != FALSE);
123 }
124
125 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
126 {
127         *major = *minor = 0;
128         *pbOverride = false;
129         
130         //Initialize local variables
131         OSVERSIONINFOEXW osvi;
132         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
133         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
134
135         //Try GetVersionEx() first
136         if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
137         {
138                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
139                 return false;
140         }
141
142         //Make sure we are running on NT
143         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
144         {
145                 *major = osvi.dwMajorVersion;
146                 *minor = osvi.dwMinorVersion;
147         }
148         else
149         {
150                 qWarning("Not running on Windows NT, unsupported operating system!");
151                 return false;
152         }
153
154         //Determine the real *major* version first
155         forever
156         {
157                 const DWORD nextMajor = (*major) + 1;
158                 if(verify_os_version(nextMajor, 0))
159                 {
160                         *pbOverride = true;
161                         *major = nextMajor;
162                         *minor = 0;
163                         continue;
164                 }
165                 break;
166         }
167
168         //Now also determine the real *minor* version
169         forever
170         {
171                 const DWORD nextMinor = (*minor) + 1;
172                 if(verify_os_version((*major), nextMinor))
173                 {
174                         *pbOverride = true;
175                         *minor = nextMinor;
176                         continue;
177                 }
178                 break;
179         }
180
181         return true;
182 }
183
184 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
185 {
186         QReadLocker readLock(&g_os_version_lock);
187
188         //Already initialized?
189         if(g_os_version_initialized)
190         {
191                 return g_os_version_info;
192         }
193         
194         readLock.unlock();
195         QWriteLocker writeLock(&g_os_version_lock);
196
197         //Initialized now?
198         if(g_os_version_initialized)
199         {
200                 return g_os_version_info;
201         }
202
203         //Detect OS version
204         unsigned int major, minor; bool overrideFlg;
205         if(get_real_os_version(&major, &minor, &overrideFlg))
206         {
207                 g_os_version_info.type = Version::OS_WINDOWS;
208                 g_os_version_info.versionMajor = major;
209                 g_os_version_info.versionMinor = minor;
210                 g_os_version_info.overrideFlag = overrideFlg;
211         }
212         else
213         {
214                 qWarning("Failed to determin the operating system version!");
215         }
216
217         g_os_version_initialized = true;
218         return g_os_version_info;
219 }
220
221 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
222 {
223         for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
224         {
225                 if(os_version == g_os_version_lut[i].version)
226                 {
227                         return g_os_version_lut[i].friendlyName;
228                 }
229         }
230
231         return NULL;
232 }
233
234 ///////////////////////////////////////////////////////////////////////////////
235 // KNWON FOLDERS
236 ///////////////////////////////////////////////////////////////////////////////
237
238 typedef QMap<size_t, QString> KFMap;
239 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
240 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
241
242 static QScopedPointer<KFMap>  g_known_folders_map;
243 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
244 static SHGetFolderPath_t      g_known_folders_fpGetFolderPath;
245 static QReadWriteLock         g_known_folders_lock;
246
247 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
248 {
249         static const int CSIDL_FLAG_CREATE = 0x8000;
250         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
251         
252         struct
253         {
254                 const int csidl;
255                 const GUID guid;
256         }
257         static s_folders[] =
258         {
259                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
260                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
261                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
262                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
263         };
264
265         size_t folderId = size_t(-1);
266
267         switch(folder_id)
268         {
269                 case FOLDER_LOCALAPPDATA: folderId = 0; break;
270                 case FOLDER_PROGRAMFILES: folderId = 1; break;
271                 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
272                 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
273         }
274
275         if(folderId == size_t(-1))
276         {
277                 qWarning("Invalid 'known' folder was requested!");
278                 return *reinterpret_cast<QString*>(NULL);
279         }
280
281         QReadLocker readLock(&g_known_folders_lock);
282
283         //Already in cache?
284         if(!g_known_folders_map.isNull())
285         {
286                 if(g_known_folders_map->contains(folderId))
287                 {
288                         return g_known_folders_map->operator[](folderId);
289                 }
290         }
291
292         //Obtain write lock to initialize
293         readLock.unlock();
294         QWriteLocker writeLock(&g_known_folders_lock);
295
296         //Still not in cache?
297         if(!g_known_folders_map.isNull())
298         {
299                 if(g_known_folders_map->contains(folderId))
300                 {
301                         return g_known_folders_map->operator[](folderId);
302                 }
303         }
304
305         //Initialize on first call
306         if(g_known_folders_map.isNull())
307         {
308                 QLibrary shell32("shell32.dll");
309                 if(shell32.load())
310                 {
311                         g_known_folders_fpGetFolderPath =      (SHGetFolderPath_t)      shell32.resolve("SHGetFolderPathW");
312                         g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
313                 }
314                 g_known_folders_map.reset(new QMap<size_t, QString>());
315         }
316
317         QString folderPath;
318
319         //Now try to get the folder path!
320         if(g_known_folders_fpGetKnownFolderPath)
321         {
322                 WCHAR *path = NULL;
323                 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
324                 {
325                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
326                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
327                         if(folderTemp.exists())
328                         {
329                                 folderPath = folderTemp.canonicalPath();
330                         }
331                         CoTaskMemFree(path);
332                 }
333         }
334         else if(g_known_folders_fpGetFolderPath)
335         {
336                 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
337                 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
338                 {
339                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
340                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
341                         if(folderTemp.exists())
342                         {
343                                 folderPath = folderTemp.canonicalPath();
344                         }
345                 }
346         }
347
348         //Update cache
349         g_known_folders_map->insert(folderId, folderPath);
350         return g_known_folders_map->operator[](folderId);
351 }
352
353 ///////////////////////////////////////////////////////////////////////////////
354 // CURRENT DATA (SAFE)
355 ///////////////////////////////////////////////////////////////////////////////
356
357 QDate MUtils::OS::current_date(void)
358 {
359         const DWORD MAX_PROC = 1024;
360         QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
361         DWORD bytesReturned = 0;
362         
363         if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
364         {
365                 return QDate::currentDate();
366         }
367
368         const DWORD procCount = bytesReturned / sizeof(DWORD);
369         ULARGE_INTEGER lastStartTime;
370         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
371
372         for(DWORD i = 0; i < procCount; i++)
373         {
374                 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
375                 {
376                         FILETIME processTime[4];
377                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
378                         {
379                                 ULARGE_INTEGER timeCreation;
380                                 timeCreation.LowPart  = processTime[0].dwLowDateTime;
381                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
382                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
383                                 {
384                                         lastStartTime.QuadPart = timeCreation.QuadPart;
385                                 }
386                         }
387                         CloseHandle(hProc);
388                 }
389         }
390         
391         FILETIME lastStartTime_fileTime;
392         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
393         lastStartTime_fileTime.dwLowDateTime  = lastStartTime.LowPart;
394
395         FILETIME lastStartTime_localTime;
396         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
397         {
398                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
399         }
400         
401         SYSTEMTIME lastStartTime_system;
402         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
403         {
404                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
405                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
406         }
407
408         const QDate currentDate = QDate::currentDate();
409         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
410         return (currentDate >= processDate) ? currentDate : processDate;
411 }
412
413 ///////////////////////////////////////////////////////////////////////////////
414 // NETWORK STATE
415 ///////////////////////////////////////////////////////////////////////////////
416
417 int MUtils::OS::network_status(void)
418 {
419         DWORD dwFlags;
420         const BOOL ret = IsNetworkAlive(&dwFlags);
421         if(GetLastError() == 0)
422         {
423                 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
424         }
425         return NETWORK_TYPE_ERR;
426 }
427
428 ///////////////////////////////////////////////////////////////////////////////
429 // FATAL EXIT
430 ///////////////////////////////////////////////////////////////////////////////
431
432 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
433 static volatile bool g_fatal_exit_flag = true;
434
435 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
436 {
437         MUtils::OS::system_message_err((LPWSTR) lpParameter, L"GURU MEDITATION");
438         return 0;
439 }
440
441 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
442 {
443         g_fatal_exit_lock.enter();
444         
445         if(!g_fatal_exit_flag)
446         {
447                 return; /*prevent recursive invocation*/
448         }
449
450         g_fatal_exit_flag = false;
451
452         if(g_main_thread_id != GetCurrentThreadId())
453         {
454                 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
455                 {
456                         SuspendThread(hThreadMain); /*stop main thread*/
457                 }
458         }
459
460         if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
461         {
462                 WaitForSingleObject(hThread, INFINITE);
463         }
464
465         for(;;)
466         {
467                 TerminateProcess(GetCurrentProcess(), 666);
468         }
469 }
470
471 ///////////////////////////////////////////////////////////////////////////////