Commit ddc0ce4b authored by jan.koester's avatar jan.koester
Browse files

better windows service

parent 65483d83
Loading
Loading
Loading
Loading
+193 −64
Changes for src/blogi.cpp: 193 added lines, 64 removed lines.
Original line number Diff line number Diff line
@@ -836,83 +836,129 @@ int main(int argc, char* argv[]) {
    return 0;
}
#endif

#ifdef Windows

#define SERVICE_NAME _T("BlogiService") // <-- FIXED: Standard TCHAR definition

SERVICE_STATUS g_ServiceStatus = { 0 };
SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
HANDLE g_ServiceStopEvent = INVALID_HANDLE_VALUE;
HANDLE g_ServiceStopEvent = NULL; // Initialized to NULL for proper check

VOID WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
VOID WINAPI ServiceCtrlHandler(DWORD);

#define SERVICE_NAME _T(LPSTR("BlogiService"))

int _tmain(int argc, TCHAR* argv[]) {
    try {

        auto getexecdir = [](){
            wchar_t path[MAX_PATH];
            GetModuleFileNameW(NULL, path, MAX_PATH);
            PathRemoveFileSpecW(path);
            return std::wstring(path);
        };
// --- 1. LogToEventViewer Implementation ---
VOID LogToEventViewer(WORD type, const std::string& message) {
    HANDLE hEventSource = RegisterEventSource(NULL, SERVICE_NAME);
    if (hEventSource == NULL) {
        return;
    }

        std::wstring exe_dir = getexecdir();
    // Convert std::string to wide string (LPCWSTR/LPCTSTR) for Windows API
    std::wstring wMessage(message.begin(), message.end());
    // Note: If project uses UNICODE, LPCTSTR is LPCWSTR. If not, this cast might be unsafe.
    // Assuming UNICODE compilation (default for modern Windows services).
    LPCWSTR lpszStrings[1] = { wMessage.c_str() };

    ReportEvent(
        hEventSource,
        type,
        0,
        101, // Event ID
        NULL,
        1,
        0,
        lpszStrings,
        NULL
    );

        if (!SetCurrentDirectoryW( exe_dir.c_str() ) ) {
            std::wcerr << L"Failed to set current directory to: " << exe_dir << std::endl;
            return -1;
        }
    } catch (const std::exception& ex) {
        std::cerr << "Exception while setting current directory: " << ex.what() << std::endl;
        return -1;
    DeregisterEventSource(hEventSource);
}

    SERVICE_TABLE_ENTRY ServiceTable[] = {
        {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
        {NULL, NULL}
    };

    if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
        // This is where you would handle the case where the application is
        // not run as a service (e.g., in debug mode or from the command line).
        // You can check the error code to differentiate.
        DWORD err = GetLastError();
        if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
            cmdplus::CmdController* BlogiCmdCtl;
            BlogiCmdCtl = &cmdplus::CmdController::getInstance();
// --- 2. Custom Streambuf and Redirection Logic ---

            BlogiCmdCtl->registerCmd("help", 'h', false,"", "Helpmenu");
/**
 * @brief Custom streambuf to redirect stream output to LogToEventViewer
 */
class EventLogStreambuf : public std::streambuf {
private:
    std::string buffer;
    WORD logType;

            if (BlogiCmdCtl->getCmdbyKey("help") && BlogiCmdCtl->getCmdbyKey("help")->getFound()) {
                BlogiCmdCtl->printHelp();
                return 0;
protected:
    // Called when the internal buffer is full or when a stream is flushed.
    virtual int overflow(int c) override {
        if (c != EOF) {
            buffer += (char)c;
            if (c == '\n') {
                if (!buffer.empty()) {
                    // Remove trailing newline before logging
                    std::string messageToLog = buffer.substr(0, buffer.length() - 1);
                    LogToEventViewer(logType, messageToLog);
                }
                buffer.clear();
                return c; // Success
            }
        }
        return EOF;
    }

            BlogiCmdCtl->registerCmd("config", 'c', true,"", "Blogi Config File");
            BlogiCmdCtl->registerCmd("debug", 'd', false, (int)0, "Blogi runs Debugmod");
            BlogiCmdCtl->registerCmd("foreground", 'F', false, (int)0, "Blogi runs Foreground");
    // Called when the stream needs to flush manually
    virtual int sync() override {
        if (!buffer.empty()) {
            LogToEventViewer(logType, buffer);
            buffer.clear();
        }
        return 0; // Success
    }

            BlogiCmdCtl->parseCmd(argc, argv);
public:
    EventLogStreambuf(WORD type) : logType(type) {}
    ~EventLogStreambuf() override {
        sync();
    }
};

            const std::string config = BlogiCmdCtl->getCmdbyKey("config")->getValue();
            int debug = BlogiCmdCtl->getCmdbyKey("debug")->getValueInt();
// Global variables for redirection management
std::streambuf* g_OriginalCerrBuffer = nullptr;
std::unique_ptr<EventLogStreambuf> g_EventLogCerrStreambuf;

            if (config.empty())
                return -1;
std::streambuf* g_OriginalCoutBuffer = nullptr;
std::unique_ptr<EventLogStreambuf> g_EventLogCoutStreambuf;

            blogi::Blogi::Cfg = std::make_unique<blogi::Config>(config);
// --- Combined Redirection Function ---
void RedirectStreamsToEventLog() {
    // 1. Redirect std::cerr (Errors)
    g_EventLogCerrStreambuf = std::make_unique<EventLogStreambuf>(EVENTLOG_ERROR_TYPE);
    g_OriginalCerrBuffer = std::cerr.rdbuf();
    std::cerr.rdbuf(g_EventLogCerrStreambuf->rdbuf());

            HttpConD blogiD(debug);
    // 2. Redirect std::cout (Information)
    g_EventLogCoutStreambuf = std::make_unique<EventLogStreambuf>(EVENTLOG_INFORMATION_TYPE);
    g_OriginalCoutBuffer = std::cout.rdbuf();
    std::cout.rdbuf(g_EventLogCoutStreambuf->rdbuf());
}
        else {
            // Handle other errors.
            return err;

// --- Combined Restoration Function ---
void RestoreStreams() {
    // 1. Restore std::cout
    if (g_OriginalCoutBuffer) {
        std::cout.rdbuf(g_OriginalCoutBuffer);
        g_OriginalCoutBuffer = nullptr;
    }
    g_EventLogCoutStreambuf.reset();

    // 2. Restore std::cerr
    if (g_OriginalCerrBuffer) {
        std::cerr.rdbuf(g_OriginalCerrBuffer);
        g_OriginalCerrBuffer = nullptr;
    }
    return 0;
    g_EventLogCerrStreambuf.reset();
}


// --- 3. Windows Service Boilerplate Functions ---

// Function to report service status
VOID ReportSvcStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint) {
    static DWORD dwCheckPoint = 1;
@@ -940,7 +986,6 @@ VOID WINAPI ServiceCtrlHandler(DWORD CtrlCode) {
        }
        return;
    case SERVICE_CONTROL_INTERROGATE:
        // Just report the current status
        ReportSvcStatus(g_ServiceStatus.dwCurrentState, NO_ERROR, 0);
        return;
    default:
@@ -962,47 +1007,131 @@ VOID WINAPI ServiceMain(DWORD dwArgc, LPTSTR* lpszArgv) {
    ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000);

    // 2. Create the stop event
    g_ServiceStopEvent = CreateEvent(
        NULL,    // default security attributes
        TRUE,    // manual reset event
        FALSE,   // not signaled
        NULL);   // no name
    g_ServiceStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (g_ServiceStopEvent == NULL) {
        ReportSvcStatus(SERVICE_STOPPED, GetLastError(), 0);
        return;
    }

    // --- START LOGGING REDIRECTION ---
    RedirectStreamsToEventLog();

    // 3. Service initialization and configuration
    try {
        std::cout << "Blogi Service is starting up. Streams redirected to Event Log." << std::endl;

        try {
            blogi::Blogi::Cfg = std::unique_ptr<blogi::Config>(new blogi::Config("yaml:./../config.yaml"));
            std::cout << "Configuration loaded successfully." << std::endl;
        } catch (const std::exception& ex) {
            // This error is logged to the Event Log via std::cerr
            std::cerr << "Failed to load config: " << ex.what() << std::endl;
            ReportSvcStatus(SERVICE_STOPPED, ERROR_INVALID_DATA, 0);

            // Critical cleanup needs to happen here before returning on failure
            if (g_ServiceStopEvent) {
                CloseHandle(g_ServiceStopEvent);
            }
            RestoreStreams();
            return;
        }

        ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
        std::cout << "Blogi Service is running." << std::endl;

        // Run the server and wait for the stop event to be signaled
        HttpConD blogiD(false);

        CloseHandle(g_ServiceStopEvent);
        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
    }
    catch (const libhttppp::HTTPException& ex) {
        // Log the exception message to the event log
        // (You would add proper event logging here)
        std::cerr << "Critical HTTP Exception in ServiceMain: " << ex.what() << std::endl;
        ReportSvcStatus(SERVICE_STOPPED, ERROR_SERVICE_SPECIFIC_ERROR, 0);
        return;
    }
    catch (const std::exception& ex) {
        // Catch any other exceptions
        std::cerr << "Unknown exception in ServiceMain: " << ex.what() << std::endl;
        ReportSvcStatus(SERVICE_STOPPED, GetLastError(), 0);
    }

    // 4. Cleanup and report stop status
    // 4. Final Cleanup (Runs regardless of whether an exception occurred)
    if (g_ServiceStopEvent) {
        CloseHandle(g_ServiceStopEvent);
        g_ServiceStopEvent = NULL;
    }

    ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);

    // --- STOP LOGGING REDIRECTION ---
    RestoreStreams();
    LogToEventViewer(EVENTLOG_INFORMATION_TYPE, "Blogi Service has stopped. Streams restored.");
}


// --- 5. Main entry point (for service dispatcher or debug mode) ---
int _tmain(int argc, TCHAR* argv[]) {
    // Helper lambda to get the executable directory path
    auto getexecdir = []() {
        wchar_t path[MAX_PATH];
        GetModuleFileNameW(NULL, path, MAX_PATH);
        PathRemoveFileSpecW(path);
        return std::wstring(path);
    };

    try {
        std::wstring exe_dir = getexecdir();

        if (!SetCurrentDirectoryW( exe_dir.c_str() ) ) {
            // Note: Use LogToEventViewer here if you couldn't set the directory,
            // but this is before service dispatch, so std::wcerr is safer if not installed.
            std::wcerr << L"Failed to set current directory to: " << exe_dir << std::endl;
            return -1;
        }
    } catch (const std::exception& ex) {
        std::cerr << "Exception while setting current directory: " << ex.what() << std::endl;
        return -1;
    }

    SERVICE_TABLE_ENTRY ServiceTable[] = {
        {SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)ServiceMain},
        {NULL, NULL}
    };

    if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
        // Handle running in non-service mode (debug/command line)
        DWORD err = GetLastError();
        if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
            // Command line execution logic
            cmdplus::CmdController* BlogiCmdCtl;
            BlogiCmdCtl = &cmdplus::CmdController::getInstance();

            BlogiCmdCtl->registerCmd("help", 'h', false,"", "Helpmenu");

            if (BlogiCmdCtl->getCmdbyKey("help") && BlogiCmdCtl->getCmdbyKey("help")->getFound()) {
                BlogiCmdCtl->printHelp();
                return 0;
            }

            BlogiCmdCtl->registerCmd("config", 'c', true,"", "Blogi Config File");
            BlogiCmdCtl->registerCmd("debug", 'd', false, (int)0, "Blogi runs Debugmod");
            BlogiCmdCtl->registerCmd("foreground", 'F', false, (int)0, "Blogi runs Foreground");

            BlogiCmdCtl->parseCmd(argc, argv);

            const std::string config = BlogiCmdCtl->getCmdbyKey("config")->getValue();
            int debug = BlogiCmdCtl->getCmdbyKey("debug")->getValueInt();

            if (config.empty())
                return -1;

            blogi::Blogi::Cfg = std::make_unique<blogi::Config>(config);

            HttpConD blogiD(debug);
        }
        else {
            return err;
        }
    }
    return 0;
}
#endif