Skip to content

Commit

Permalink
fix(server): use kernel mutex to ensure single instance (#207)
Browse files Browse the repository at this point in the history
  • Loading branch information
nameoverflow authored Apr 22, 2018
1 parent e18117b commit bd0c472
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 18 deletions.
12 changes: 8 additions & 4 deletions WeaselIPCServer/WeaselServerImpl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,14 @@ DWORD ServerImpl::OnCommand(WEASEL_IPC_COMMAND uMsg, DWORD wParam, DWORD lParam)

int ServerImpl::Start()
{
// assure single instance
if (FindWindow(WEASEL_IPC_WINDOW, NULL) != NULL)
{
return 0;
std::wstring instanceName = L"(WEASEL)Furandōru-Sukāretto-";
instanceName += getUsername();
HANDLE hMutexOneInstance = ::CreateMutex(NULL, FALSE, instanceName.c_str());
bool areYouOK = (::GetLastError() == ERROR_ALREADY_EXISTS ||
::GetLastError() == ERROR_ACCESS_DENIED);

if (areYouOK) {
return 0; // assure single instance
}

HWND hwnd = Create(NULL);
Expand Down
16 changes: 2 additions & 14 deletions include/WeaselIPC.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once
#include <WeaselCommon.h>
#include <WeaselUtility.h>
#include <windows.h>
#include <functional>
#include <memory>
Expand Down Expand Up @@ -168,21 +169,8 @@ namespace weasel
inline std::wstring GetPipeName()
{
std::wstring pipe_name;
DWORD len = 0;
GetUserName(NULL, &len);

if (len <= 0) {
return pipe_name;
}

std::unique_ptr<wchar_t[]> username(new wchar_t[len]);

GetUserName(username.get(), &len);
if (len <= 0) {
return pipe_name;
}
pipe_name += L"\\\\.\\pipe\\";
pipe_name += username.get();
pipe_name += getUsername();
pipe_name += L"\\";
pipe_name += WEASEL_IPC_PIPE_NAME;
return pipe_name;
Expand Down
20 changes: 20 additions & 0 deletions include/WeaselUtility.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ inline int utf8towcslen(const char* utf8_str, int utf8_len)
return MultiByteToWideChar(CP_UTF8, 0, utf8_str, utf8_len, NULL, 0);
}

inline std::wstring getUsername() {
DWORD len = 0;
GetUserName(NULL, &len);

if (len <= 0) {
return L"";
}

wchar_t *username = new wchar_t[len + 1];

GetUserName(username, &len);
if (len <= 0) {
delete[] username;
return L"";
}
auto res = std::wstring(username);
delete[] username;
return res;
}

// data directories
std::wstring WeaselUserDataPath();

Expand Down

0 comments on commit bd0c472

Please sign in to comment.