Win32_service.cpp 26.2 KB
Newer Older
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
/*
* Copyright (c), Microsoft Open Technologies, Inc.
* 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.
* 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.
*/

/*
This code implements the following new command line arguments for redis:

--service-install [additional command line arguments to pass to redis when launched as a service]

28 29 30
This must be the first argument on the redis-server command line. Arguments after this are passed in the order they occur to redis when the
service is launched. The service will be configured as Autostart and will be launched as "NT AUTHORITY\NetworkService". Upon successful
installation a success message will be displayed and redis will exit. For instance:
31

32
redis-server --service-install redis.conf --loglevel verbose
33

34
This command does not start the service.
35 36 37

--service-uninstall

38 39
This will remove the redis service configuration information from the registry. Upon successful uninstallation a success message will be
displayed and redis will exit.
40

41
This does command not stop the service.
42 43 44

--service-start

45
This will start the redis service. Upon successful startup a success message will be displayed and redis will exit.
46 47 48

--service-stop

49
This will stop the redis service. Upon successful termination a success message will be displayed and redis will exit.
50

51 52
The [--service-name name] arguments, modifies the preceding commands to target a specific service name. If present, 
this should preceed the other arguments passed to redis. For instance:
53

54
    redis-server --service-install --service-name testServiceName redis.windows.conf --loglevel verbose 
55 56
*/

57 58
#include "win32_types.h"

59
#include <windows.h>
60 61
#include <windowsx.h>
#include <shlobj.h>
62 63
#include <tchar.h>
#include <strsafe.h>
64
#include <aclapi.h>
65
#include "Win32_EventLog.h"
66 67 68 69 70
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
71
#include "..\redisLog.h"
72
#include "Win32_CommandLine.h"
73 74 75 76 77 78
using namespace std;

#include "Win32_SmartHandle.h"

#pragma comment(lib, "advapi32.lib")

79 80 81
#define DEFAULT_SERVICE_NAME "Redis"  
#define MAX_SERVICE_NAME_LENGTH 256
char g_serviceName[MAX_SERVICE_NAME_LENGTH + 1] = DEFAULT_SERVICE_NAME;
82 83 84

SERVICE_STATUS g_ServiceStatus = { 0 };
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;
85
HANDLE g_ServiceStoppedEvent = INVALID_HANDLE_VALUE;
86 87 88
vector<string> serviceRunArguments;
SERVICE_STATUS_HANDLE g_StatusHandle;
const ULONGLONG cThirtySeconds = 30 * 1000;
89
BOOL g_isRunningAsService = FALSE;
90
const int cPreshutdownInterval = 180000;
91 92
const char* cServiceInstallPipeName = "\\\\.\\pipe\\redis-service-install";

93 94
extern "C" int main(int argc, char** argv);

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
typedef class ServicePipeWriter {
public:
    static ServicePipeWriter& getInstance() {
        static ServicePipeWriter    instance;
        return instance;
    }

private:
    HANDLE pipe = INVALID_HANDLE_VALUE;
    ServicePipeWriter() {
        pipe = CreateFileA(cServiceInstallPipeName, GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL, NULL);
    }
    ServicePipeWriter(ServicePipeWriter const&);
    void operator=(ServicePipeWriter const&);
    ~ServicePipeWriter() {
        if (pipe != INVALID_HANDLE_VALUE) {
            CloseHandle(pipe);
            pipe = INVALID_HANDLE_VALUE;
        }
116
    }
117 118 119 120 121 122 123 124 125 126 127

public:
    void Write(string message) {
        if (pipe != INVALID_HANDLE_VALUE) {
            DWORD bytesWritten = 0;
            WriteFile(pipe, message.c_str(), (DWORD)message.length(), &bytesWritten, NULL);
        } else {
            ::redisLog(REDIS_WARNING, message.c_str());
        }
    }
} ServicePipeWriter;
128 129

BOOL RelaunchAsElevatedProcess(int argc, char** argv) {
130 131 132 133 134 135 136 137 138 139 140 141 142 143
    // create pipe for launched process to communicate back on
    SmartHandle pipe =
        CreateNamedPipeA(
        cServiceInstallPipeName, PIPE_ACCESS_INBOUND,
        PIPE_TYPE_BYTE, 1, 0, 0, PIPE_NOWAIT, NULL);

    stringstream  paramString;
    bool first = true;
    for (int n = 1; n < argc; n++) {
        if (first) {
            first = false;
        } else {
            paramString << " ";
        }
144 145 146 147 148 149
        string arg = argv[n];
        if (arg.find(' ') != string::npos)  {
            paramString << "\"" << arg << "\"";
        } else {
            paramString << arg;
        }
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
    }
    CHAR params[32768];
    memset(params, 0, 32768);
    memcpy(params, paramString.str().c_str(), paramString.str().length());

    // Launch itself as administrator.
    SHELLEXECUTEINFOA sei = { 0 };
    sei.cbSize = sizeof(SHELLEXECUTEINFOA);
    sei.lpVerb = "runas";
    sei.lpFile = _pgmptr;
    sei.lpParameters = params;
    sei.hwnd = 0;
    sei.fMask = SEE_MASK_NOCLOSEPROCESS;
    sei.lpDirectory = 0;
    sei.hInstApp = 0;

    if (ShellExecuteExA(&sei)) {
        if (sei.hProcess != NULL) {
            const int messageBufferSize = 10000;
            char buffer[messageBufferSize + 1];
            DWORD bytesRead;
            while (WaitForSingleObject(sei.hProcess, 0) != WAIT_OBJECT_0) {
                DWORD result = ReadFile(pipe, buffer, messageBufferSize, &bytesRead, NULL);
                if (result != 0 && bytesRead > 0) {
                    buffer[bytesRead] = '\0';	// ensure received message is null terminated;
175
                    ::redisLog(REDIS_WARNING, (const char*)buffer);
176 177 178 179 180 181 182 183
                }
            }
            CloseHandle(sei.hProcess);
        }
        return TRUE;
    } else {
        throw std::system_error(GetLastError(), system_category(), "ShellExecuteExA failed");
    }
184 185 186
}

bool IsProcessElevated() {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    DWORD dwError = ERROR_SUCCESS;
    SmartHandle shToken;

    // Open the primary access token of the process with TOKEN_QUERY.
    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, shToken)) {
        throw std::system_error(GetLastError(), system_category(), "OpenProcessTokenFailed failed");
    }

    // Retrieve token elevation information.
    TOKEN_ELEVATION elevation;
    DWORD dwSize;
    if (!GetTokenInformation(shToken, TokenElevation, &elevation,
        sizeof(elevation), &dwSize)) {
        throw std::system_error(GetLastError(), system_category(), "OpenProcessTokenFailed failed");
    }

    return  (elevation.TokenIsElevated != 0);
}

206 207 208 209
VOID InitializeServiceName() {
    if (g_argMap.find(cServiceName) != g_argMap.end()) {
        if (g_argMap[cServiceName].at(0).at(0).length() > MAX_SERVICE_NAME_LENGTH) {
            throw std::runtime_error("Service name too long.");
210
        }
211
        strcpy_s(g_serviceName, MAX_SERVICE_NAME_LENGTH, g_argMap[cServiceName].at(0).at(0).c_str());
212
    }
213 214
}

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
DWORD AddAceToObjectsSecurityDescriptor(
    LPSTR pszObjName,          
    SE_OBJECT_TYPE ObjectType,  
    LPSTR pszTrustee,          
    TRUSTEE_FORM TrusteeForm,   
    DWORD dwAccessRights,       
    ACCESS_MODE AccessMode,     
    DWORD dwInheritance         
    ) {
    DWORD dwRes = 0;
    PACL pOldDACL = NULL, pNewDACL = NULL;
    PSECURITY_DESCRIPTOR pSD = NULL;
    EXPLICIT_ACCESSA ea;

    if (NULL == pszObjName)
        return ERROR_INVALID_PARAMETER;

    dwRes = GetNamedSecurityInfoA(pszObjName, ObjectType,
        DACL_SECURITY_INFORMATION,
        NULL, NULL, &pOldDACL, NULL, &pSD);
    if (ERROR_SUCCESS != dwRes) {
236
        ::redisLog(REDIS_WARNING, "GetNamedSecurityInfo Error %u\n", dwRes);
237 238 239 240 241 242 243 244 245 246 247 248
        goto Cleanup;
    }

    ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
    ea.grfAccessPermissions = dwAccessRights;
    ea.grfAccessMode = AccessMode;
    ea.grfInheritance = dwInheritance;
    ea.Trustee.TrusteeForm = TrusteeForm;
    ea.Trustee.ptstrName = pszTrustee;

    dwRes = SetEntriesInAclA(1, &ea, pOldDACL, &pNewDACL);
    if (ERROR_SUCCESS != dwRes) {
249
        ::redisLog(REDIS_WARNING, "SetEntriesInAcl Error %u\n", dwRes);
250 251 252 253 254 255 256
        goto Cleanup;
    }

    dwRes = SetNamedSecurityInfoA(pszObjName, ObjectType,
        DACL_SECURITY_INFORMATION,
        NULL, NULL, pNewDACL, NULL);
    if (ERROR_SUCCESS != dwRes) {
257
        ::redisLog(REDIS_WARNING, "SetNamedSecurityInfo Error %u\n", dwRes);
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        goto Cleanup;
    }

Cleanup:

    if (pSD != NULL)
        LocalFree((HLOCAL)pSD);
    if (pNewDACL != NULL)
        LocalFree((HLOCAL)pNewDACL);

    return dwRes;
}

VOID SetAccessACLOnFolder(string user, string folder) {
    if (0 != AddAceToObjectsSecurityDescriptor( 
                (LPSTR)(folder.c_str()), SE_OBJECT_TYPE::SE_FILE_OBJECT,
                (LPSTR)(user.c_str()), TRUSTEE_FORM::TRUSTEE_IS_NAME,
                GENERIC_ALL, GRANT_ACCESS, SUB_CONTAINERS_AND_OBJECTS_INHERIT)) {
        throw std::system_error(GetLastError(), system_category(), "ServiceInstall: AddAceToObjectsSecurityDescriptor failed");
    }
}

280
VOID ServiceInstall(int argc, char ** argv) {
281 282 283
    SmartServiceHandle shSCManager;
    SmartServiceHandle shService;
    CHAR szPath[MAX_PATH];
284
    string userName = "NT AUTHORITY\\NetworkService";
285

286
    InitializeServiceName();
287 288 289 290 291

    // build arguments to pass to service when it auto starts
    if (GetModuleFileNameA(NULL, szPath, MAX_PATH) == 0) {
        throw std::system_error(GetLastError(), system_category(), "ServiceInstall: GetModuleFileNameA failed");
    }
292

293 294 295 296 297 298 299 300
    stringstream args;
    for (int a = 0; a < argc; a++) {
        if (a == 0) {
            args << "\"" << szPath << "\"";
        } else {
            args << " ";
            if (a == 1) {
                // replace --service-install argument with --service-run
301
                args << "--" << cServiceRun;
302
            } else {
303 304 305 306 307 308
                string arg = argv[a];
                if (arg.find(' ') != arg.npos)  {
                    args << "\"" << argv[a] << "\"";
                } else {
                    args << argv[a];
                }
309 310 311 312 313 314 315 316
            }
        }
    }

    shSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (shSCManager.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenSCManager failed");
    }
317

318 319 320 321 322 323 324 325 326 327
    shService = CreateServiceA(
        shSCManager,
        g_serviceName,
        g_serviceName,
        SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL,
        args.str().c_str(),
        NULL, NULL, NULL,
328
        userName.c_str(),
329 330 331 332 333 334 335 336 337 338 339 340 341
        NULL);
    if (shService.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "CreateService failed");
    }

    SERVICE_PRESHUTDOWN_INFO preshutdownInfo;
    preshutdownInfo.dwPreshutdownTimeout = cPreshutdownInterval;
    if (FALSE == ChangeServiceConfig2(shService, SERVICE_CONFIG_PRESHUTDOWN_INFO, &preshutdownInfo)) {
        throw std::system_error(GetLastError(), system_category(), "ChangeServiceConfig2 failed");
    }

    RedisEventLog().InstallEventLogSource(szPath);

342 343 344 345 346 347 348 349 350 351
    // make sure NT AUTHORITY\\NetworkService" has rights to every directory where a files may be accessed (CONF,AOF,RDB,DAT)
    stringstream aceMessage;
    aceMessage << "Granting read/write access to 'NT AUTHORITY\\NetworkService' on: ";
    for (auto folder : GetAccessPaths()) {
        SetAccessACLOnFolder(userName, folder);
        aceMessage << "\"" << folder.c_str() << "\" ";
    }
    ServicePipeWriter::getInstance().Write(aceMessage.str().c_str());

    ServicePipeWriter::getInstance().Write("Redis successfully installed as a service.");
352 353
}

354 355 356 357
VOID ServiceStart(int argc, char ** argv) {
    SmartServiceHandle shSCManager;
    SmartServiceHandle shService;

358
    InitializeServiceName();
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

    shSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (shSCManager.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenSCManager failed");
    }
    shService = OpenServiceA(shSCManager, g_serviceName, SERVICE_ALL_ACCESS);
    if (shService.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenService failed");
    }
    if (FALSE == StartServiceA(shService, 0, NULL)) {
        throw std::system_error(GetLastError(), system_category(), "StartService failed");
    }

    // it will take atleast a couple of seconds for the service to start.
    Sleep(2000);

    SERVICE_STATUS status;
376
    DWORD start = GetTickCount();
377 378
    while (QueryServiceStatus(shService, &status) == TRUE) {
        if (status.dwCurrentState == SERVICE_RUNNING) {
379
            ServicePipeWriter::getInstance().Write("Redis service successfully started.");
380 381
            break;
        } else if (status.dwCurrentState == SERVICE_STOPPED) {
382
            ServicePipeWriter::getInstance().Write("Redis service failed to start.");
383 384 385
            break;
        }

386
        DWORD current = GetTickCount();
387
        if (current - start >= cThirtySeconds) {
388
            ServicePipeWriter::getInstance().Write("Redis service start timed out.");
389 390 391
            break;
        }
    }
392 393 394

}

395 396 397 398
VOID ServiceStop(int argc, char ** argv) {
    SmartServiceHandle shSCManager;
    SmartServiceHandle shService;

399
    InitializeServiceName();
400 401 402 403 404 405 406 407 408 409 410 411 412 413

    shSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (shSCManager.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenSCManager failed");
    }
    shService = OpenServiceA(shSCManager, g_serviceName, SERVICE_ALL_ACCESS);
    if (shService.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenService failed");
    }
    SERVICE_STATUS status;
    if (FALSE == ControlService(shService, SERVICE_CONTROL_STOP, &status)) {
        throw std::system_error(GetLastError(), system_category(), "ControlService failed");
    }

414
    DWORD start = GetTickCount();
415 416
    while (QueryServiceStatus(shService, &status) == TRUE) {
        if (status.dwCurrentState == SERVICE_STOPPED) {
417
            ServicePipeWriter::getInstance().Write("Redis service successfully stopped.");
418 419
            break;
        }
420
        DWORD current = GetTickCount();
421
        if (current - start >= cThirtySeconds) {
422
            ServicePipeWriter::getInstance().Write("Redis service stop timed out.");
423 424 425
            break;
        }
    }
426 427
}

428 429 430
VOID ServiceUninstall(int argc, char** argv) {
    SmartServiceHandle shSCManager;
    SmartServiceHandle shService;
431

432
    InitializeServiceName();
433

434 435 436 437 438 439 440 441 442 443
    shSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (shSCManager.Invalid()) {
        throw std::system_error(GetLastError(), system_category(), "OpenSCManager failed");
    }
    shService = OpenServiceA(shSCManager, g_serviceName, SERVICE_ALL_ACCESS);
    if (shService.Valid()) {
        if (FALSE == DeleteService(shService)) {
            throw std::system_error(GetLastError(), system_category(), "DeleteService failed");
        }
    }
444

445 446
    RedisEventLog().UninstallEventLogSource();

447
    ServicePipeWriter::getInstance().Write("Redis service successfully uninstalled.");
448 449 450
}

DWORD WINAPI ServiceWorkerThread(LPVOID lpParam) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
    try {
        int argc = (int)(serviceRunArguments.size());
        char** argv = new char*[argc];
        if (argv == nullptr)
            throw std::runtime_error("new() failed");

        int argIndex = 0;
        for each(string arg in serviceRunArguments) {
            argv[argIndex] = new char[arg.length() + 1];
            if (argv[argIndex] == nullptr)
                throw std::runtime_error("new() failed");
            memcpy_s(argv[argIndex], arg.length() + 1, arg.c_str(), arg.length());
            argv[argIndex][arg.size()] = '\0';
            ++argIndex;
        }

        // When the service starts the current directory is %systemdir%. If the launching user does not have permission there(i.e., NETWORK SERVICE), the 
        // memory mapped file will not be able to be created. Thus Redis will fail to start. Setting the current directory to the executable directory
        // should fix this.
        char szFilePath[MAX_PATH];
        if (GetModuleFileNameA(NULL, szFilePath, MAX_PATH) == 0) {
            throw std::system_error(GetLastError(), system_category(), "ServiceWrokerThread: GetModuleFileName failed");
        }
        string currentDir = szFilePath;
        auto pos = currentDir.rfind("\\");
        currentDir.erase(pos);

        if (FALSE == SetCurrentDirectoryA(currentDir.c_str())) {
            throw std::system_error(GetLastError(), system_category(), "SetCurrentDirectory failed");
        }

        // call redis main without the --service-run argument
        main(argc, argv);

        for (int a = 0; a < argc; a++) {
            delete argv[a];
            argv[a] = nullptr;
        }
        delete argv;
        argv = nullptr;

        SetEvent(g_ServiceStoppedEvent);

        return ERROR_SUCCESS;
    } catch (std::system_error syserr) {
        stringstream err;
        err << "ServiceWorkerThread: system error caught. error code=0x" << hex << syserr.code().value() << ", message = " << syserr.what() << endl;
        OutputDebugStringA(err.str().c_str());
    } catch (std::runtime_error runerr) {
        stringstream err;
        err << "runtime error caught. message=" << runerr.what() << endl;
        OutputDebugStringA(err.str().c_str());
    } catch (...) {
        OutputDebugStringA("ServiceWorkerThread: other exception caught.\n");
    }

    return  ERROR_PROCESS_ABORTED;
508 509
}

510
DWORD WINAPI ServiceCtrlHandler(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpContext) {
511 512 513
    switch (dwControl) {
        case SERVICE_CONTROL_PRESHUTDOWN:
        {
514
            SetEvent(g_ServiceStopEvent);
515

516 517 518 519
            g_ServiceStatus.dwControlsAccepted = 0;
            g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
            g_ServiceStatus.dwWin32ExitCode = 0;
            g_ServiceStatus.dwCheckPoint = 4;
520

521 522 523
            if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
                throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
            }
524

525
            break;
526 527 528 529
        }

        case SERVICE_CONTROL_STOP:
        {
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
            DWORD start = GetTickCount();
            while (GetTickCount() - start > cPreshutdownInterval) {
                if (WaitForSingleObject(g_ServiceStoppedEvent, cPreshutdownInterval / 10) == WAIT_OBJECT_0) {
                    break;
                }

                g_ServiceStatus.dwControlsAccepted = 0;
                g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
                g_ServiceStatus.dwWin32ExitCode = 0;
                g_ServiceStatus.dwCheckPoint = 4;

                if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
                    throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
                }
            }

            g_ServiceStatus.dwControlsAccepted = 0;
            g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
            g_ServiceStatus.dwWin32ExitCode = 0;
            g_ServiceStatus.dwCheckPoint = 4;

            if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
                throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
            }
            break;
555 556 557 558 559 560 561 562 563
        }

        default:
        {
                   break;
        }
    }

    return NO_ERROR;
564 565 566
}

VOID WINAPI ServiceMain(DWORD argc, LPTSTR *argv) {
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    DWORD Status = E_FAIL;

    g_StatusHandle = RegisterServiceCtrlHandlerExA(g_serviceName, ServiceCtrlHandler, NULL);
    if (g_StatusHandle == NULL) {
        return;
    }

    ZeroMemory(&g_ServiceStatus, sizeof (g_ServiceStatus));
    g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    g_ServiceStatus.dwControlsAccepted = 0;
    g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwServiceSpecificExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
    }

    g_ServiceStoppedEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (g_ServiceStopEvent == NULL) {
        g_ServiceStatus.dwControlsAccepted = 0;
        g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
        g_ServiceStatus.dwWin32ExitCode = GetLastError();
        g_ServiceStatus.dwCheckPoint = 1;

        if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
            throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
        }

        return;
    }

    g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PRESHUTDOWN;
    g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 0;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
    }

    HANDLE hThread = CreateThread(NULL, 0, ServiceWorkerThread, NULL, 0, NULL);

    WaitForSingleObject(hThread, INFINITE);

    CloseHandle(g_ServiceStopEvent);

    g_ServiceStatus.dwControlsAccepted = 0;
    g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
    g_ServiceStatus.dwWin32ExitCode = 0;
    g_ServiceStatus.dwCheckPoint = 3;

    if (SetServiceStatus(g_StatusHandle, &g_ServiceStatus) == FALSE) {
        throw std::system_error(GetLastError(), system_category(), "SetServiceStatus failed");
    }
624 625 626
}

void ServiceRun() {
627 628 629 630 631 632 633 634 635
    SERVICE_TABLE_ENTRYA ServiceTable[] =
    {
        { g_serviceName, (LPSERVICE_MAIN_FUNCTIONA)ServiceMain },
        { NULL, NULL }
    };

    if (StartServiceCtrlDispatcherA(ServiceTable) == FALSE) {
        throw std::system_error(GetLastError(), system_category(), "StartServiceCtrlDispatcherA failed");
    }
636 637 638
}

void BuildServiceRunArguments(int argc, char** argv) {
639
    InitializeServiceName();
640
	string serviceNameFullArgument = "--" + cServiceName;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655

    // build argument list to be used by ServiceRun
    for (int n = 0; n < argc; n++) {
        if (n == 0) {
            CHAR szPath[MAX_PATH];
            if (GetModuleFileNameA(NULL, szPath, MAX_PATH) == 0) {
                throw std::system_error(GetLastError(), system_category(), "BuildServiceRunArguments: GetModuleFileNameA failed");
            }
            stringstream ss;
            ss << "\"" << szPath << "\"";
            serviceRunArguments.push_back(ss.str());
        } else if (n == 1) {
            // bypass --service-run argument
            continue;
        } else {
656
			if (_stricmp(argv[n], serviceNameFullArgument.c_str()) == 0) {
657 658 659 660 661 662 663 664
                // bypass --service-name argument and the name of the service
                n++;
                continue; 
            } else {
                serviceRunArguments.push_back(argv[n]);
            }
        }
    }
665 666 667
}

extern "C" BOOL HandleServiceCommands(int argc, char **argv) {
668 669
    try {
        if (argc > 1) {
670 671
            string servicearg = string(argv[1]);
            servicearg = servicearg.substr(2, servicearg.length());
672
            std::transform(servicearg.begin(), servicearg.end(), servicearg.begin(), ::tolower);
673
            if (servicearg == cServiceInstall) {
674 675 676 677 678 679
                if (!IsProcessElevated()) {
                    return RelaunchAsElevatedProcess(argc, argv);
                } else {
                    ServiceInstall(argc, argv);
                    return TRUE;
                }
680
            } else if (servicearg == cServiceUninstall) {
681 682 683 684 685 686
                if (!IsProcessElevated()) {
                    return RelaunchAsElevatedProcess(argc, argv);
                } else {
                    ServiceUninstall(argc, argv);
                    return TRUE;
                }
687
            } else if (servicearg == cServiceRun) {
688 689 690 691
                g_isRunningAsService = TRUE;
                BuildServiceRunArguments(argc, argv);
                ServiceRun();
                return TRUE;
692
            } else if (servicearg == cServiceStart) {
693 694 695 696 697 698
                if (!IsProcessElevated()) {
                    return RelaunchAsElevatedProcess(argc, argv);
                } else {
                    ServiceStart(argc, argv);
                    return TRUE;
                }
699
            } else if (servicearg == cServiceStop) {
700 701 702 703 704 705 706 707 708 709 710 711 712 713
                if (!IsProcessElevated()) {
                    return RelaunchAsElevatedProcess(argc, argv);
                } else {
                    ServiceStop(argc, argv);
                    return TRUE;
                }
            }
        }

        // not a service command. start redis normally.
        return FALSE;
    } catch (std::system_error syserr) {
        stringstream ss;
        ss << "HandleServiceCommands: system error caught. error code=" << syserr.code().value() << ", message = " << syserr.what() << endl;
714
        ServicePipeWriter::getInstance().Write(ss.str());
715 716 717
        exit(1);
    } catch (std::runtime_error runerr) {
        stringstream err;
718
        err << "HandleServiceCommands: runtime error caught. message=" << runerr.what() << endl;
719
        ServicePipeWriter::getInstance().Write(err.str());
720 721 722 723
        exit(1);
    } catch (...) {
        stringstream ss;
        ss << "HandleServiceCommands: other exception caught." << endl;
724
        ServicePipeWriter::getInstance().Write(ss.str());
725 726
        exit(1);
    }
727 728 729
}

extern "C" BOOL ServiceStopIssued() {
730 731
    if (g_ServiceStopEvent == INVALID_HANDLE_VALUE) return FALSE;
    return (WaitForSingleObject(g_ServiceStopEvent, 0) == WAIT_OBJECT_0) ? TRUE : FALSE;
732 733
}

734
extern "C" BOOL RunningAsService() {
735
    return g_isRunningAsService;
736 737
}

738 739 740
extern "C" const char* GetServiceName()  {
    return g_serviceName;
}
741