Fix (Windows Service): Remove the shit dropped by AI

This commit is contained in:
shaun
2025-12-11 11:00:52 +01:00
committed by yuanyuanxiang
parent 1915a0ea6d
commit ac0617e5ec
9 changed files with 245 additions and 343 deletions

View File

@@ -182,14 +182,24 @@ BOOL CALLBACK callback(DWORD CtrlType)
return TRUE; return TRUE;
} }
void ServiceLogger(const char* message) {
Logger::getInstance().log(NULL, 0, "%s", message);
}
int main(int argc, const char *argv[]) int main(int argc, const char *argv[])
{ {
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc>1 ? argv[1] : "", argc);
InitWindowsService({ "RemoteControlService", "Remote Control Service", "Provides remote desktop control functionality." }, ServiceLogger);
bool isService = g_SETTINGS.iStartup == Startup_GhostMsc; bool isService = g_SETTINGS.iStartup == Startup_GhostMsc;
// 注册启动项 // 注册启动项
int r = RegisterStartup("Windows Ghost", "WinGhost", !isService); int r = RegisterStartup("Windows Ghost", "WinGhost", !isService);
if (r <= 0) { if (r <= 0) {
BOOL s = self_del(); BOOL s = self_del();
if (!IsDebug)return r; if (!IsDebug) {
Mprintf("结束运行.");
Sleep(1000);
return r;
}
} }
if (!SetSelfStart(argv[0], REG_NAME)) { if (!SetSelfStart(argv[0], REG_NAME)) {
@@ -202,7 +212,11 @@ int main(int argc, const char *argv[])
for (int i = 0; !ret && i < argc; i++) { for (int i = 0; !ret && i < argc; i++) {
Mprintf(" Arg [%d]: %s\n", i, argv[i]); Mprintf(" Arg [%d]: %s\n", i, argv[i]);
} }
if (ret) return 0x20251123; if (ret) {
Mprintf("结束运行.");
Sleep(1000);
return 0x20251123;
}
} }
status = E_RUN; status = E_RUN;
@@ -212,6 +226,8 @@ int main(int argc, const char *argv[])
CloseHandle(hMutex); CloseHandle(hMutex);
hMutex = NULL; hMutex = NULL;
#ifndef _DEBUG #ifndef _DEBUG
Mprintf("结束运行.");
Sleep(1000);
return -2; return -2;
#endif #endif
} }
@@ -246,6 +262,7 @@ int main(int argc, const char *argv[])
status = E_STOP; status = E_STOP;
CloseHandle(hMutex); CloseHandle(hMutex);
Mprintf("结束运行.");
Logger::getInstance().stop(); Logger::getInstance().stop();
return 0; return 0;

View File

@@ -2,15 +2,7 @@
#include "SessionMonitor.h" #include "SessionMonitor.h"
#include <stdio.h> #include <stdio.h>
#ifndef Mprintf #define Mprintf(format, ...) MyLog(__FILE__, __LINE__, format, __VA_ARGS__)
#ifdef _DEBUG
#define Mprintf printf
#define Log(p) ServiceWriteLog(p, "C:\\GhostService.log")
#else
#define Mprintf(format, ...)
#define Log(p)
#endif
#endif
// 静态变量 // 静态变量
static MyService g_MyService = static MyService g_MyService =
@@ -19,14 +11,44 @@ static MyService g_MyService =
static SERVICE_STATUS g_ServiceStatus = { 0 }; static SERVICE_STATUS g_ServiceStatus = { 0 };
static SERVICE_STATUS_HANDLE g_StatusHandle = NULL; static SERVICE_STATUS_HANDLE g_StatusHandle = NULL;
static HANDLE g_StopEvent = NULL; static HANDLE g_StopEvent = NULL;
static ServiceLogFunc Log = NULL;
// 前向声明 // 前向声明
static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv); static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
static void WINAPI ServiceCtrlHandler(DWORD ctrlCode); static void WINAPI ServiceCtrlHandler(DWORD ctrlCode);
void InitWindowsService(MyService info) void MyLog(const char* file, int line, const char* format, ...) {
if (Log == NULL) {
return; // 没有设置日志回调,直接返回
}
char buffer[1024];
char message[1200];
// 处理可变参数
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
// 提取文件名(去掉路径)
const char* filename = strrchr(file, '/');
if (filename == NULL) {
filename = strrchr(file, '\\');
}
filename = (filename != NULL) ? (filename + 1) : file;
// 格式化完整的日志消息:[文件名:行号] 消息内容
snprintf(message, sizeof(message), "[%s:%d] %s", filename, line, buffer);
// 调用日志回调函数
Log(message);
}
void InitWindowsService(MyService info, ServiceLogFunc log)
{ {
memcpy(&g_MyService, &info, sizeof(MyService)); memcpy(&g_MyService, &info, sizeof(MyService));
Log = log;
} }
BOOL ServiceWrapper_CheckStatus(BOOL* registered, BOOL* running, BOOL ServiceWrapper_CheckStatus(BOOL* registered, BOOL* running,
@@ -59,7 +81,7 @@ BOOL ServiceWrapper_CheckStatus(BOOL* registered, BOOL* running,
SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG); SERVICE_QUERY_STATUS | SERVICE_QUERY_CONFIG);
if (!hService) { if (!hService) {
CloseServiceHandle(hSCM); CloseServiceHandle(hSCM);
return FALSE; // 未注册 return TRUE; // 未注册
} }
*registered = TRUE; *registered = TRUE;
@@ -140,13 +162,13 @@ int ServiceWrapper_Run(void)
ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL; ServiceTable[1].lpServiceProc = NULL;
Log("========================================"); Mprintf("========================================");
Log("ServiceWrapper_Run() called"); Mprintf("ServiceWrapper_Run() called");
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) { if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
err = GetLastError(); err = GetLastError();
sprintf(buffer, "StartServiceCtrlDispatcher failed: %d", (int)err); sprintf(buffer, "StartServiceCtrlDispatcher failed: %d", (int)err);
Log(buffer); Mprintf(buffer);
return (int)err; return (int)err;
} }
return ERROR_SUCCESS; return ERROR_SUCCESS;
@@ -159,7 +181,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
(void)argc; (void)argc;
(void)argv; (void)argv;
Log("ServiceMain() called"); Mprintf("ServiceMain() called");
g_StatusHandle = RegisterServiceCtrlHandler( g_StatusHandle = RegisterServiceCtrlHandler(
g_MyService.Name, g_MyService.Name,
@@ -167,7 +189,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
); );
if (g_StatusHandle == NULL) { if (g_StatusHandle == NULL) {
Log("RegisterServiceCtrlHandler failed"); Mprintf("RegisterServiceCtrlHandler failed");
return; return;
} }
@@ -184,7 +206,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); g_StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_StopEvent == NULL) { if (g_StopEvent == NULL) {
Log("CreateEvent failed"); Mprintf("CreateEvent failed");
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = GetLastError(); g_ServiceStatus.dwWin32ExitCode = GetLastError();
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
@@ -197,7 +219,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwCheckPoint = 0;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
Log("Service is now running"); Mprintf("Service is now running");
hThread = CreateThread(NULL, 0, ServiceWrapper_WorkerThread, NULL, 0, NULL); hThread = CreateThread(NULL, 0, ServiceWrapper_WorkerThread, NULL, 0, NULL);
if (hThread) { if (hThread) {
@@ -213,14 +235,14 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_ServiceStatus.dwCheckPoint = 3; g_ServiceStatus.dwCheckPoint = 3;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
Log("Service stopped"); Mprintf("Service stopped");
} }
static void WINAPI ServiceCtrlHandler(DWORD ctrlCode) static void WINAPI ServiceCtrlHandler(DWORD ctrlCode)
{ {
switch (ctrlCode) { switch (ctrlCode) {
case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_STOP:
Log("SERVICE_CONTROL_STOP received"); Mprintf("SERVICE_CONTROL_STOP received");
if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING) if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
break; break;
@@ -253,21 +275,21 @@ DWORD WINAPI ServiceWrapper_WorkerThread(LPVOID lpParam)
(void)lpParam; // 未使用参数 (void)lpParam; // 未使用参数
Log("========================================"); Mprintf("========================================");
Log("Worker thread started"); Mprintf("Worker thread started");
Log("Service will launch agent in user sessions"); Mprintf("Service will launch agent in user sessions");
// 初始化会话监控器 // 初始化会话监控器
SessionMonitor_Init(&monitor); SessionMonitor_Init(&monitor);
if (!SessionMonitor_Start(&monitor)) { if (!SessionMonitor_Start(&monitor)) {
Log("ERROR: Failed to start session monitor"); Mprintf("ERROR: Failed to start session monitor");
SessionMonitor_Cleanup(&monitor); SessionMonitor_Cleanup(&monitor);
return ERROR_SERVICE_SPECIFIC_ERROR; return ERROR_SERVICE_SPECIFIC_ERROR;
} }
Log("Session monitor started successfully"); Mprintf("Session monitor started successfully");
Log("Agent will be launched automatically"); Mprintf("Agent will be launched automatically");
// 主循环,只等待停止信号 // 主循环,只等待停止信号
// SessionMonitor 会在后台自动: // SessionMonitor 会在后台自动:
@@ -278,17 +300,17 @@ DWORD WINAPI ServiceWrapper_WorkerThread(LPVOID lpParam)
heartbeatCount++; heartbeatCount++;
if (heartbeatCount % 6 == 0) { // 每60秒记录一次 if (heartbeatCount % 6 == 0) { // 每60秒记录一次
sprintf(buf, "Service heartbeat - uptime: %d minutes", heartbeatCount / 6); sprintf(buf, "Service heartbeat - uptime: %d minutes", heartbeatCount / 6);
Log(buf); Mprintf(buf);
} }
} }
Log("Stop signal received"); Mprintf("Stop signal received");
Log("Stopping session monitor..."); Mprintf("Stopping session monitor...");
SessionMonitor_Stop(&monitor); SessionMonitor_Stop(&monitor);
SessionMonitor_Cleanup(&monitor); SessionMonitor_Cleanup(&monitor);
Log("Worker thread exiting"); Mprintf("Worker thread exiting");
Log("========================================"); Mprintf("========================================");
return ERROR_SUCCESS; return ERROR_SUCCESS;
} }
@@ -393,16 +415,10 @@ BOOL ServiceWrapper_Install(void)
CloseServiceHandle(schService); CloseServiceHandle(schService);
CloseServiceHandle(schSCManager); CloseServiceHandle(schSCManager);
Mprintf("\n=== Installation Complete ===\n"); Mprintf("=== Installation Complete ===\n");
Mprintf("Service installed successfully!\n"); Mprintf("Service installed successfully!\n");
Mprintf("\n");
Mprintf("IMPORTANT: This is a single-executable design.\n"); Mprintf("IMPORTANT: This is a single-executable design.\n");
Mprintf("The service will launch '%s -agent' in user sessions.\n", szPath); Mprintf("The service will launch '%s -agent' in user sessions.\n", szPath);
Mprintf("\n");
Mprintf("Logs will be written to:\n");
Mprintf(" - C:\\GhostService.log (service logs)\n");
Mprintf(" - C:\\SessionMonitor.log (session monitor logs)\n");
Mprintf("\n");
Mprintf("Commands:\n"); Mprintf("Commands:\n");
Mprintf(" To verify: sc query %s\n", g_MyService.Name); Mprintf(" To verify: sc query %s\n", g_MyService.Name);
Mprintf(" To start: net start %s\n", g_MyService.Name); Mprintf(" To start: net start %s\n", g_MyService.Name);
@@ -411,7 +427,7 @@ BOOL ServiceWrapper_Install(void)
return TRUE; return TRUE;
} }
void ServiceWrapper_Uninstall(void) BOOL ServiceWrapper_Uninstall(void)
{ {
SC_HANDLE schSCManager; SC_HANDLE schSCManager;
SC_HANDLE schService; SC_HANDLE schService;
@@ -428,7 +444,7 @@ void ServiceWrapper_Uninstall(void)
if (schSCManager == NULL) { if (schSCManager == NULL) {
Mprintf("ERROR: OpenSCManager failed (%d)\n", (int)GetLastError()); Mprintf("ERROR: OpenSCManager failed (%d)\n", (int)GetLastError());
Mprintf("Please run as Administrator\n"); Mprintf("Please run as Administrator\n");
return; return FALSE;
} }
schService = OpenService( schService = OpenService(
@@ -441,7 +457,7 @@ void ServiceWrapper_Uninstall(void)
Mprintf("ERROR: OpenService failed (%d)\n", (int)GetLastError()); Mprintf("ERROR: OpenService failed (%d)\n", (int)GetLastError());
Mprintf("Service may not be installed\n"); Mprintf("Service may not be installed\n");
CloseServiceHandle(schSCManager); CloseServiceHandle(schSCManager);
return; return FALSE;
} }
Mprintf("Stopping service...\n"); Mprintf("Stopping service...\n");
@@ -459,7 +475,6 @@ void ServiceWrapper_Uninstall(void)
break; break;
} }
} }
Mprintf("\n");
if (status.dwCurrentState == SERVICE_STOPPED) { if (status.dwCurrentState == SERVICE_STOPPED) {
Mprintf("SUCCESS: Service stopped\n"); Mprintf("SUCCESS: Service stopped\n");
@@ -474,18 +489,20 @@ void ServiceWrapper_Uninstall(void)
Mprintf("WARNING: Failed to stop service (%d)\n", (int)err); Mprintf("WARNING: Failed to stop service (%d)\n", (int)err);
} }
} }
BOOL result = TRUE;
Mprintf("Deleting service...\n"); Mprintf("Deleting service...\n");
if (DeleteService(schService)) { if (DeleteService(schService)) {
Mprintf("SUCCESS: Service uninstalled successfully\n"); Mprintf("SUCCESS: Service uninstalled successfully\n");
} else { } else {
Mprintf("ERROR: DeleteService failed (%d)\n", (int)GetLastError()); Mprintf("ERROR: DeleteService failed (%d)\n", (int)GetLastError());
result = FALSE;
} }
CloseServiceHandle(schService); CloseServiceHandle(schService);
CloseServiceHandle(schSCManager); CloseServiceHandle(schSCManager);
Mprintf("\n=== Uninstallation Complete ===\n"); Mprintf("=== Uninstallation Complete ===\n");
return result;
} }
void PrintUsage() void PrintUsage()
@@ -496,35 +513,6 @@ void PrintUsage()
Mprintf(" -service Run as service\n"); Mprintf(" -service Run as service\n");
Mprintf(" -agent Run as agent\n"); Mprintf(" -agent Run as agent\n");
Mprintf(" default Run as normal application\n"); Mprintf(" default Run as normal application\n");
Mprintf("\n");
}
// 从服务路径中提取可执行文件路径(去除引号和参数)
static void ExtractExePath(const char* input, char* output, size_t outSize)
{
const char* start = input;
const char* end;
size_t len;
if (outSize == 0) return;
output[0] = '\0';
// 跳过开头的引号
if (*start == '"') {
start++;
end = strchr(start, '"');
if (!end) end = start + strlen(start);
} else {
// 找到第一个空格(参数分隔)或字符串结尾
end = strchr(start, ' ');
if (!end) end = start + strlen(start);
}
len = end - start;
if (len >= outSize) len = outSize - 1;
strncpy(output, start, len);
output[len] = '\0';
} }
BOOL RunAsWindowsService(int argc, const char* argv[]) BOOL RunAsWindowsService(int argc, const char* argv[])
@@ -533,24 +521,30 @@ BOOL RunAsWindowsService(int argc, const char* argv[])
BOOL registered = FALSE; BOOL registered = FALSE;
BOOL running = FALSE; BOOL running = FALSE;
char servicePath[MAX_PATH] = { 0 }; char servicePath[MAX_PATH] = { 0 };
char serviceExePath[MAX_PATH] = { 0 };
char curPath[MAX_PATH] = { 0 }; char curPath[MAX_PATH] = { 0 };
ServiceWrapper_CheckStatus(&registered, &running, servicePath, MAX_PATH); BOOL b = ServiceWrapper_CheckStatus(&registered, &running, servicePath, MAX_PATH);
Mprintf("ServiceWrapper_CheckStatus: %s, Installed: %s, Running: %s\n", b ? "succeed" : "failed",
registered ? "Yes" : "No", running ? "Yes" : "No");
GetModuleFileName(NULL, curPath, MAX_PATH); GetModuleFileName(NULL, curPath, MAX_PATH);
// 从服务路径中提取可执行文件路径(去除引号和参数) if (registered) {
ExtractExePath(servicePath, serviceExePath, MAX_PATH); Mprintf("Current executable path: %s, Registered service path: %s\n", curPath, servicePath);
}
// 使用不区分大小写的比较 // 使用不区分大小写的比较
if (registered && _stricmp(curPath, serviceExePath) != 0) { _strlwr(servicePath);
Mprintf("RunAsWindowsService Uninstall: %s\n", servicePath); _strlwr(curPath);
ServiceWrapper_Uninstall(); BOOL same = (strstr(servicePath, curPath) != 0);
if (registered && !same) {
BOOL r = ServiceWrapper_Uninstall();
Mprintf("RunAsWindowsService Uninstall %s: %s\n", r ? "succeed" : "failed", servicePath);
registered = FALSE; registered = FALSE;
} }
if (!registered) { if (!registered) {
Mprintf("RunAsWindowsService Install: %s\n", curPath); BOOL r = ServiceWrapper_Install();
return ServiceWrapper_Install(); Mprintf("RunAsWindowsService Install %s: %s\n", r ? "succeed" : "failed", curPath);
return r;
} else if (!running) { } else if (!running) {
int r = ServiceWrapper_Run(); int r = ServiceWrapper_Run();
Mprintf("RunAsWindowsService Run '%s' %s\n", curPath, r == ERROR_SUCCESS ? "succeed" : "failed"); Mprintf("RunAsWindowsService Run '%s' %s\n", curPath, r == ERROR_SUCCESS ? "succeed" : "failed");

View File

@@ -9,6 +9,8 @@ typedef struct MyService {
char Description[512]; char Description[512];
} MyService; } MyService;
typedef void (*ServiceLogFunc)(const char* message);
#ifdef __cplusplus #ifdef __cplusplus
extern "C" { extern "C" {
#endif #endif
@@ -28,7 +30,7 @@ sc query RemoteControlService
*/ */
// 自定义服务信息 // 自定义服务信息
void InitWindowsService(MyService info); void InitWindowsService(MyService info, ServiceLogFunc log);
// 以Windows服务模式运行程序 // 以Windows服务模式运行程序
BOOL RunAsWindowsService(int argc, const char* argv[]); BOOL RunAsWindowsService(int argc, const char* argv[]);
@@ -55,7 +57,7 @@ int ServiceWrapper_Run(void);
BOOL ServiceWrapper_Install(void); BOOL ServiceWrapper_Install(void);
// 卸载服务 // 卸载服务
void ServiceWrapper_Uninstall(void); BOOL ServiceWrapper_Uninstall(void);
// 服务工作线程 // 服务工作线程
DWORD WINAPI ServiceWrapper_WorkerThread(LPVOID lpParam); DWORD WINAPI ServiceWrapper_WorkerThread(LPVOID lpParam);

View File

@@ -7,12 +7,9 @@
// <20><>̬<EFBFBD><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD> // <20><>̬<EFBFBD><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>
#define INITIAL_CAPACITY 4 #define INITIAL_CAPACITY 4
#define Mprintf(format, ...) MyLog(__FILE__, __LINE__, format, __VA_ARGS__)
#ifdef _DEBUG extern void MyLog(const char* file, int line, const char* format, ...);
#define SessionLog(p) ServiceWriteLog(p, "C:\\SessionMonitor.log")
#else
#define SessionLog(p)
#endif
// ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // ǰ<><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
static DWORD WINAPI MonitorThreadProc(LPVOID param); static DWORD WINAPI MonitorThreadProc(LPVOID param);
@@ -86,25 +83,6 @@ static void AgentArray_RemoveAt(AgentProcessArray* arr, size_t index)
arr->count--; arr->count--;
} }
// ============================================
// <20><>־<EFBFBD><D6BE><EFBFBD><EFBFBD>
// ============================================
void ServiceWriteLog(const char* message, const char* filename)
{
FILE* f;
SYSTEMTIME st;
f = fopen(filename, "a");
if (f) {
GetLocalTime(&st);
fprintf(f, "[%04d-%02d-%02d %02d:%02d:%02d] %s\n",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond,
message);
fclose(f);
}
}
// ============================================ // ============================================
// <20><><EFBFBD><EFBFBD><EFBFBD>ӿ<EFBFBD>ʵ<EFBFBD><CAB5> // <20><><EFBFBD><EFBFBD><EFBFBD>ӿ<EFBFBD>ʵ<EFBFBD><CAB5>
// ============================================ // ============================================
@@ -127,23 +105,23 @@ void SessionMonitor_Cleanup(SessionMonitor* self)
BOOL SessionMonitor_Start(SessionMonitor* self) BOOL SessionMonitor_Start(SessionMonitor* self)
{ {
if (self->running) { if (self->running) {
SessionLog("Monitor already running"); Mprintf("Monitor already running");
return TRUE; return TRUE;
} }
SessionLog("========================================"); Mprintf("========================================");
SessionLog("Starting session monitor..."); Mprintf("Starting session monitor...");
self->running = TRUE; self->running = TRUE;
self->monitorThread = CreateThread(NULL, 0, MonitorThreadProc, self, 0, NULL); self->monitorThread = CreateThread(NULL, 0, MonitorThreadProc, self, 0, NULL);
if (!self->monitorThread) { if (!self->monitorThread) {
SessionLog("ERROR: Failed to create monitor thread"); Mprintf("ERROR: Failed to create monitor thread");
self->running = FALSE; self->running = FALSE;
return FALSE; return FALSE;
} }
SessionLog("Session monitor thread created"); Mprintf("Session monitor thread created");
return TRUE; return TRUE;
} }
@@ -153,7 +131,7 @@ void SessionMonitor_Stop(SessionMonitor* self)
return; return;
} }
SessionLog("Stopping session monitor..."); Mprintf("Stopping session monitor...");
self->running = FALSE; self->running = FALSE;
if (self->monitorThread) { if (self->monitorThread) {
@@ -163,11 +141,11 @@ void SessionMonitor_Stop(SessionMonitor* self)
} }
// <20><>ֹ<EFBFBD><D6B9><EFBFBD>д<EFBFBD><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><>ֹ<EFBFBD><D6B9><EFBFBD>д<EFBFBD><D0B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
SessionLog("Terminating all agent processes..."); Mprintf("Terminating all agent processes...");
TerminateAllAgents(self); TerminateAllAgents(self);
SessionLog("Session monitor stopped"); Mprintf("Session monitor stopped");
SessionLog("========================================"); Mprintf("========================================");
} }
// ============================================ // ============================================
@@ -192,7 +170,7 @@ static void MonitorLoop(SessionMonitor* self)
char buf[256]; char buf[256];
int j; int j;
SessionLog("Monitor loop started"); Mprintf("Monitor loop started");
while (self->running) { while (self->running) {
loopCount++; loopCount++;
@@ -219,20 +197,20 @@ static void MonitorLoop(SessionMonitor* self)
sprintf(buf, "Active session found: ID=%d, Name=%s", sprintf(buf, "Active session found: ID=%d, Name=%s",
(int)sessionId, (int)sessionId,
pSessionInfo[i].pWinStationName); pSessionInfo[i].pWinStationName);
SessionLog(buf); Mprintf(buf);
} }
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7>ڸûỰ<C3BB><E1BBB0><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7>ڸûỰ<C3BB><E1BBB0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (!IsAgentRunningInSession(self, sessionId)) { if (!IsAgentRunningInSession(self, sessionId)) {
sprintf(buf, "Agent not running in session %d, launching...", (int)sessionId); sprintf(buf, "Agent not running in session %d, launching...", (int)sessionId);
SessionLog(buf); Mprintf(buf);
if (LaunchAgentInSession(self, sessionId)) { if (LaunchAgentInSession(self, sessionId)) {
SessionLog("Agent launched successfully"); Mprintf("Agent launched successfully");
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һЩʱ<D0A9><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һЩʱ<D0A9><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
Sleep(2000); Sleep(2000);
} else { } else {
SessionLog("Failed to launch agent"); Mprintf("Failed to launch agent");
} }
} }
@@ -242,13 +220,13 @@ static void MonitorLoop(SessionMonitor* self)
} }
if (!foundActiveSession && loopCount % 5 == 1) { if (!foundActiveSession && loopCount % 5 == 1) {
SessionLog("No active sessions found"); Mprintf("No active sessions found");
} }
WTSFreeMemory(pSessionInfo); WTSFreeMemory(pSessionInfo);
} else { } else {
if (loopCount % 5 == 1) { if (loopCount % 5 == 1) {
SessionLog("WTSEnumerateSessions failed"); Mprintf("WTSEnumerateSessions failed");
} }
} }
@@ -258,7 +236,7 @@ static void MonitorLoop(SessionMonitor* self)
} }
} }
SessionLog("Monitor loop exited"); Mprintf("Monitor loop exited");
} }
static BOOL IsAgentRunningInSession(SessionMonitor* self, DWORD sessionId) static BOOL IsAgentRunningInSession(SessionMonitor* self, DWORD sessionId)
@@ -292,7 +270,7 @@ static BOOL IsAgentRunningInSession(SessionMonitor* self, DWORD sessionId)
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̿<EFBFBD><CCBF><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̿<EFBFBD><CCBF><EFBFBD>
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) { if (hSnapshot == INVALID_HANDLE_VALUE) {
SessionLog("CreateToolhelp32Snapshot failed"); Mprintf("CreateToolhelp32Snapshot failed");
return FALSE; return FALSE;
} }
@@ -334,14 +312,14 @@ static void TerminateAllAgents(SessionMonitor* self)
EnterCriticalSection(&self->csProcessList); EnterCriticalSection(&self->csProcessList);
sprintf(buf, "Terminating %d agent process(es)", (int)self->agentProcesses.count); sprintf(buf, "Terminating %d agent process(es)", (int)self->agentProcesses.count);
SessionLog(buf); Mprintf(buf);
for (i = 0; i < self->agentProcesses.count; i++) { for (i = 0; i < self->agentProcesses.count; i++) {
info = &self->agentProcesses.items[i]; info = &self->agentProcesses.items[i];
sprintf(buf, "Terminating agent PID=%d (Session %d)", sprintf(buf, "Terminating agent PID=%d (Session %d)",
(int)info->processId, (int)info->sessionId); (int)info->processId, (int)info->sessionId);
SessionLog(buf); Mprintf(buf);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (GetExitCodeProcess(info->hProcess, &exitCode)) { if (GetExitCodeProcess(info->hProcess, &exitCode)) {
@@ -350,16 +328,16 @@ static void TerminateAllAgents(SessionMonitor* self)
if (!TerminateProcess(info->hProcess, 0)) { if (!TerminateProcess(info->hProcess, 0)) {
sprintf(buf, "WARNING: Failed to terminate PID=%d, error=%d", sprintf(buf, "WARNING: Failed to terminate PID=%d, error=%d",
(int)info->processId, (int)GetLastError()); (int)info->processId, (int)GetLastError());
SessionLog(buf); Mprintf(buf);
} else { } else {
SessionLog("Agent terminated successfully"); Mprintf("Agent terminated successfully");
// <20>ȴ<EFBFBD><C8B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȫ<EFBFBD>˳<EFBFBD> // <20>ȴ<EFBFBD><C8B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȫ<EFBFBD>˳<EFBFBD>
WaitForSingleObject(info->hProcess, 5000); WaitForSingleObject(info->hProcess, 5000);
} }
} else { } else {
sprintf(buf, "Agent PID=%d already exited with code %d", sprintf(buf, "Agent PID=%d already exited with code %d",
(int)info->processId, (int)exitCode); (int)info->processId, (int)exitCode);
SessionLog(buf); Mprintf(buf);
} }
} }
@@ -369,7 +347,7 @@ static void TerminateAllAgents(SessionMonitor* self)
self->agentProcesses.count = 0; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> self->agentProcesses.count = 0; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
LeaveCriticalSection(&self->csProcessList); LeaveCriticalSection(&self->csProcessList);
SessionLog("All agents terminated"); Mprintf("All agents terminated");
} }
// <20><><EFBFBD><EFBFBD><EFBFBD>Ѿ<EFBFBD><D1BE><EFBFBD>ֹ<EFBFBD>Ľ<EFBFBD><C4BD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD>Ѿ<EFBFBD><D1BE><EFBFBD>ֹ<EFBFBD>Ľ<EFBFBD><C4BD><EFBFBD>
@@ -391,7 +369,7 @@ static void CleanupDeadProcesses(SessionMonitor* self)
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˳<EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˳<EFBFBD>
sprintf(buf, "Agent PID=%d exited with code %d, cleaning up", sprintf(buf, "Agent PID=%d exited with code %d, cleaning up",
(int)info->processId, (int)exitCode); (int)info->processId, (int)exitCode);
SessionLog(buf); Mprintf(buf);
CloseHandle(info->hProcess); CloseHandle(info->hProcess);
AgentArray_RemoveAt(&self->agentProcesses, i); AgentArray_RemoveAt(&self->agentProcesses, i);
@@ -401,7 +379,7 @@ static void CleanupDeadProcesses(SessionMonitor* self)
// <20>޷<EFBFBD><DEB7><EFBFBD>ȡ<EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD><EBA3AC><EFBFBD>ܽ<EFBFBD><DCBD><EFBFBD><EFBFBD>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD><EFBFBD> // <20>޷<EFBFBD><DEB7><EFBFBD>ȡ<EFBFBD>˳<EFBFBD><CBB3><EFBFBD><EFBFBD><EFBFBD><EBA3AC><EFBFBD>ܽ<EFBFBD><DCBD><EFBFBD><EFBFBD>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD><EFBFBD>
sprintf(buf, "Cannot query agent PID=%d, removing from list", sprintf(buf, "Cannot query agent PID=%d, removing from list",
(int)info->processId); (int)info->processId);
SessionLog(buf); Mprintf(buf);
CloseHandle(info->hProcess); CloseHandle(info->hProcess);
AgentArray_RemoveAt(&self->agentProcesses, i); AgentArray_RemoveAt(&self->agentProcesses, i);
@@ -434,7 +412,7 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
memset(&pi, 0, sizeof(pi)); memset(&pi, 0, sizeof(pi));
sprintf(buf, "Attempting to launch agent in session %d", (int)sessionId); sprintf(buf, "Attempting to launch agent in session %d", (int)sessionId);
SessionLog(buf); Mprintf(buf);
si.cb = sizeof(STARTUPINFO); si.cb = sizeof(STARTUPINFO);
si.lpDesktop = (LPSTR)"winsta0\\default"; // <20>ؼ<EFBFBD><D8BC><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD> si.lpDesktop = (LPSTR)"winsta0\\default"; // <20>ؼ<EFBFBD><D8BC><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
@@ -442,7 +420,7 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
// <20><>ȡ<EFBFBD><C8A1>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̵<EFBFBD> SYSTEM <20><><EFBFBD><EFBFBD> // <20><>ȡ<EFBFBD><C8A1>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̵<EFBFBD> SYSTEM <20><><EFBFBD><EFBFBD>
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {
sprintf(buf, "OpenProcessToken failed: %d", (int)GetLastError()); sprintf(buf, "OpenProcessToken failed: %d", (int)GetLastError());
SessionLog(buf); Mprintf(buf);
return FALSE; return FALSE;
} }
@@ -450,7 +428,7 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL,
SecurityImpersonation, TokenPrimary, &hDupToken)) { SecurityImpersonation, TokenPrimary, &hDupToken)) {
sprintf(buf, "DuplicateTokenEx failed: %d", (int)GetLastError()); sprintf(buf, "DuplicateTokenEx failed: %d", (int)GetLastError());
SessionLog(buf); Mprintf(buf);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
@@ -458,30 +436,30 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
// <20>޸<EFBFBD><DEB8><EFBFBD><EFBFBD>ƵĻỰ ID ΪĿ<CEAA><C4BF><EFBFBD>û<EFBFBD><C3BB> // <20>޸<EFBFBD><DEB8><EFBFBD><EFBFBD>ƵĻỰ ID ΪĿ<CEAA><C4BF><EFBFBD>û<EFBFBD><C3BB>
if (!SetTokenInformation(hDupToken, TokenSessionId, &sessionId, sizeof(sessionId))) { if (!SetTokenInformation(hDupToken, TokenSessionId, &sessionId, sizeof(sessionId))) {
sprintf(buf, "SetTokenInformation failed: %d", (int)GetLastError()); sprintf(buf, "SetTokenInformation failed: %d", (int)GetLastError());
SessionLog(buf); Mprintf(buf);
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
SessionLog("Token duplicated"); Mprintf("Token duplicated");
// <20><>ȡ<EFBFBD><C8A1>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD>·<EFBFBD><C2B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Լ<EFBFBD><D4BC><EFBFBD> // <20><>ȡ<EFBFBD><C8A1>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD>·<EFBFBD><C2B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Լ<EFBFBD><D4BC><EFBFBD>
if (!GetModuleFileName(NULL, exePath, MAX_PATH)) { if (!GetModuleFileName(NULL, exePath, MAX_PATH)) {
SessionLog("GetModuleFileName failed"); Mprintf("GetModuleFileName failed");
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
sprintf(buf, "Service path: %s", exePath); sprintf(buf, "Service path: %s", exePath);
SessionLog(buf); Mprintf(buf);
// <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD> // <20><><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>
fileAttr = GetFileAttributes(exePath); fileAttr = GetFileAttributes(exePath);
if (fileAttr == INVALID_FILE_ATTRIBUTES) { if (fileAttr == INVALID_FILE_ATTRIBUTES) {
sprintf(buf, "ERROR: Executable not found at: %s", exePath); sprintf(buf, "ERROR: Executable not found at: %s", exePath);
SessionLog(buf); Mprintf(buf);
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
@@ -491,18 +469,18 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
sprintf(cmdLine, "\"%s\" -agent", exePath); sprintf(cmdLine, "\"%s\" -agent", exePath);
sprintf(buf, "Command line: %s", cmdLine); sprintf(buf, "Command line: %s", cmdLine);
SessionLog(buf); Mprintf(buf);
// <20><>ȡ<EFBFBD>û<EFBFBD><C3BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڻ<EFBFBD><DABB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // <20><>ȡ<EFBFBD>û<EFBFBD><C3BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڻ<EFBFBD><DABB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (!WTSQueryUserToken(sessionId, &hUserToken)) { if (!WTSQueryUserToken(sessionId, &hUserToken)) {
sprintf(buf, "WTSQueryUserToken failed: %d", (int)GetLastError()); sprintf(buf, "WTSQueryUserToken failed: %d", (int)GetLastError());
SessionLog(buf); Mprintf(buf);
} }
// ʹ<><CAB9><EFBFBD>û<EFBFBD><C3BB><EFBFBD><EFBFBD>ƴ<EFBFBD><C6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // ʹ<><CAB9><EFBFBD>û<EFBFBD><C3BB><EFBFBD><EFBFBD>ƴ<EFBFBD><C6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (hUserToken) { if (hUserToken) {
if (!CreateEnvironmentBlock(&lpEnvironment, hUserToken, FALSE)) { if (!CreateEnvironmentBlock(&lpEnvironment, hUserToken, FALSE)) {
SessionLog("CreateEnvironmentBlock failed"); Mprintf("CreateEnvironmentBlock failed");
} }
CloseHandle(hUserToken); CloseHandle(hUserToken);
} }
@@ -528,7 +506,7 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
if (result) { if (result) {
sprintf(buf, "SUCCESS: Agent process created (PID=%d)", (int)pi.dwProcessId); sprintf(buf, "SUCCESS: Agent process created (PID=%d)", (int)pi.dwProcessId);
SessionLog(buf); Mprintf(buf);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ<EFBFBD><CFA2><EFBFBD>Ա<EFBFBD>ֹͣʱ<D6B9><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֹ<EFBFBD><D6B9> // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϣ<EFBFBD><CFA2><EFBFBD>Ա<EFBFBD>ֹͣʱ<D6B9><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֹ<EFBFBD><D6B9>
EnterCriticalSection(&self->csProcessList); EnterCriticalSection(&self->csProcessList);
@@ -542,15 +520,15 @@ static BOOL LaunchAgentInSession(SessionMonitor* self, DWORD sessionId)
} else { } else {
err = GetLastError(); err = GetLastError();
sprintf(buf, "CreateProcessAsUser failed: %d", (int)err); sprintf(buf, "CreateProcessAsUser failed: %d", (int)err);
SessionLog(buf); Mprintf(buf);
// <20><EFBFBD><E1B9A9><EFBFBD><EFBFBD>ϸ<EFBFBD>Ĵ<EFBFBD><C4B4><EFBFBD><EFBFBD><EFBFBD>Ϣ // <20><EFBFBD><E1B9A9><EFBFBD><EFBFBD>ϸ<EFBFBD>Ĵ<EFBFBD><C4B4><EFBFBD><EFBFBD><EFBFBD>Ϣ
if (err == ERROR_FILE_NOT_FOUND) { if (err == ERROR_FILE_NOT_FOUND) {
SessionLog("ERROR: agent executable file not found"); Mprintf("ERROR: agent executable file not found");
} else if (err == ERROR_ACCESS_DENIED) { } else if (err == ERROR_ACCESS_DENIED) {
SessionLog("ERROR: Access denied - service may not have sufficient privileges"); Mprintf("ERROR: Access denied - service may not have sufficient privileges");
} else if (err == 1314) { } else if (err == 1314) {
SessionLog("ERROR: Service does not have SE_INCREASE_QUOTA privilege"); Mprintf("ERROR: Service does not have SE_INCREASE_QUOTA privilege");
} }
} }

View File

@@ -210,6 +210,10 @@ public:
} }
}; };
void ServiceLogger(const char* message) {
Logger::getInstance().log(NULL, 0, "%s", message);
}
// @brief <20><><EFBFBD>ȶ<EFBFBD>ȡsettings.ini<6E><69><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD>ȡIP<49>Ͷ˿<CDB6>. // @brief <20><><EFBFBD>ȶ<EFBFBD>ȡsettings.ini<6E><69><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD>ȡIP<49>Ͷ˿<CDB6>.
// [settings] // [settings]
// localIp=XXX // localIp=XXX
@@ -217,13 +221,18 @@ public:
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ھʹ<DABE><CDB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>л<EFBFBD>ȡIP<49>Ͷ˿<CDB6>. // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ھʹ<DABE><CDB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>л<EFBFBD>ȡIP<49>Ͷ˿<CDB6>.
int main(int argc, const char *argv[]) int main(int argc, const char *argv[])
{ {
InitWindowsService({"ClientDemoService", "Client Demo Service", "Provide a demo service."}); Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: %s %s. Arg Count: %d\n", argv[0], argc > 1 ? argv[1] : "", argc);
InitWindowsService({"ClientDemoService", "Client Demo Service", "Provide a demo service."}, ServiceLogger);
bool isService = g_ConnectAddress.iStartup == Startup_TestRunMsc; bool isService = g_ConnectAddress.iStartup == Startup_TestRunMsc;
// ע<><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> // ע<><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int r = RegisterStartup("Client Demo", "ClientDemo", !isService); int r = RegisterStartup("Client Demo", "ClientDemo", !isService);
if (r <= 0) { if (r <= 0) {
BOOL s = self_del(); BOOL s = self_del();
if (!IsDebug)return r; if (!IsDebug) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.");
Sleep(1000);
return r;
}
} }
BOOL ok = SetSelfStart(argv[0], REG_NAME); BOOL ok = SetSelfStart(argv[0], REG_NAME);
@@ -237,7 +246,11 @@ int main(int argc, const char *argv[])
for (int i = 0; !ret && i < argc; i++) { for (int i = 0; !ret && i < argc; i++) {
Mprintf(" Arg [%d]: %s\n", i, argv[i]); Mprintf(" Arg [%d]: %s\n", i, argv[i]);
} }
if (ret) return 0x20251202; if (ret) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.");
Sleep(1000);
return 0x20251202;
}
g_ConnectAddress.iStartup = Startup_MEMDLL; g_ConnectAddress.iStartup = Startup_MEMDLL;
} }
@@ -279,8 +292,11 @@ int main(int argc, const char *argv[])
} }
CloseHandle(hProcess); CloseHandle(hProcess);
Mprintf("Process [%d] is finished.\n", pid); Mprintf("Process [%d] is finished.\n", pid);
if (status == 1) if (status == 1) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.");
Sleep(1000);
return -1; return -1;
}
} while (pid); } while (pid);
} }
@@ -293,12 +309,18 @@ int main(int argc, const char *argv[])
argv[1] : (strlen(g_ConnectAddress.ServerIP()) == 0 ? "127.0.0.1" : g_ConnectAddress.ServerIP()), argv[1] : (strlen(g_ConnectAddress.ServerIP()) == 0 ? "127.0.0.1" : g_ConnectAddress.ServerIP()),
argc > 2 ? atoi(argv[2]) : (g_ConnectAddress.ServerPort() == 0 ? 6543 : g_ConnectAddress.ServerPort())); argc > 2 ? atoi(argv[2]) : (g_ConnectAddress.ServerPort() == 0 ? 6543 : g_ConnectAddress.ServerPort()));
if (ret == 1) { if (ret == 1) {
Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.");
Sleep(1000);
return -1; return -1;
} }
} while (status == 0); } while (status == 0);
status = 0; status = 0;
return -1; Mprintf("<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.");
Sleep(1000);
Logger::getInstance().stop();
return 0;
} }
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>в<EFBFBD><D0B2><EFBFBD>: IP <20><> <20>˿<EFBFBD>. // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>в<EFBFBD><D0B2><EFBFBD>: IP <20><> <20>˿<EFBFBD>.

View File

@@ -87,7 +87,9 @@ public:
auto timestamp = getCurrentTimestamp(); auto timestamp = getCurrentTimestamp();
std::string id = pid.empty() ? "" : "[" + pid + "]"; std::string id = pid.empty() ? "" : "[" + pid + "]";
std::string logEntry = id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message; std::string logEntry = file && line ?
id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message:
id + "[" + timestamp + "] " + message;
if (enable) { if (enable) {
if (running) { if (running) {
std::lock_guard<std::mutex> lock(queueMutex); std::lock_guard<std::mutex> lock(queueMutex);

View File

@@ -124,39 +124,6 @@ CMy2015RemoteApp::CMy2015RemoteApp()
CMy2015RemoteApp theApp; CMy2015RemoteApp theApp;
// 从服务路径中提取可执行文件路径(去除引号和参数)
static void ExtractExePathFromServicePath(const char* servicePath, char* exePath, size_t exePathSize)
{
if (!servicePath || !exePath || exePathSize == 0) {
if (exePath && exePathSize > 0) exePath[0] = '\0';
return;
}
const char* src = servicePath;
char* dst = exePath;
size_t remaining = exePathSize - 1;
// 跳过前导空格
while (*src == ' ') src++;
if (*src == '"') {
// 带引号的路径:提取引号内的内容
src++; // 跳过开始引号
while (*src && *src != '"' && remaining > 0) {
*dst++ = *src++;
remaining--;
}
} else {
// 不带引号的路径:提取到空格或结束
while (*src && *src != ' ' && remaining > 0) {
*dst++ = *src++;
remaining--;
}
}
*dst = '\0';
}
// 处理服务相关的命令行参数 // 处理服务相关的命令行参数
// 返回值: TRUE 表示已处理服务命令程序应退出FALSE 表示继续正常启动 // 返回值: TRUE 表示已处理服务命令程序应退出FALSE 表示继续正常启动
static BOOL HandleServiceCommandLine() static BOOL HandleServiceCommandLine()
@@ -203,18 +170,18 @@ static BOOL HandleServiceCommandLine()
char curPath[MAX_PATH]; char curPath[MAX_PATH];
GetModuleFileNameA(NULL, curPath, MAX_PATH); GetModuleFileNameA(NULL, curPath, MAX_PATH);
// 从服务路径中提取纯可执行文件路径(去除引号和参数) _strlwr(servicePath);
char serviceExePath[MAX_PATH] = { 0 }; _strlwr(curPath);
ExtractExePathFromServicePath(servicePath, serviceExePath, MAX_PATH); BOOL same = (strstr(servicePath, curPath) != 0);
if (registered && !same) {
if (registered && _stricmp(curPath, serviceExePath) != 0) { BOOL r = ServerService_Uninstall();
Mprintf("[HandleServiceCommandLine] ServerService Uninstall: %s\n", servicePath); Mprintf("[HandleServiceCommandLine] ServerService Uninstall %s: %s\n", r ? "succeed" : "failed", servicePath);
ServerService_Uninstall();
registered = FALSE; registered = FALSE;
} }
if (!registered) { if (!registered) {
Mprintf("[HandleServiceCommandLine] ServerService Install: %s\n", curPath); BOOL r = ServerService_Install();
return ServerService_Install(); Mprintf("[HandleServiceCommandLine] ServerService Install: %s\n", r ? "succeed" : "failed", curPath);
return r;
} else if (!running) { } else if (!running) {
int r = ServerService_Run(); int r = ServerService_Run();
Mprintf("[HandleServiceCommandLine] ServerService Run '%s' %s\n", curPath, r == ERROR_SUCCESS ? "succeed" : "failed"); Mprintf("[HandleServiceCommandLine] ServerService Run '%s' %s\n", curPath, r == ERROR_SUCCESS ? "succeed" : "failed");

View File

@@ -13,45 +13,6 @@ static HANDLE g_StopEvent = INVALID_HANDLE_VALUE;
// 前向声明 // 前向声明
static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv); static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv);
static void WINAPI ServiceCtrlHandler(DWORD ctrlCode); static void WINAPI ServiceCtrlHandler(DWORD ctrlCode);
static void ServiceWriteLog(const char* message);
// 获取日志文件路径(程序所在目录)
static void GetServiceLogPath(char* logPath, size_t size)
{
char exePath[MAX_PATH];
if (GetModuleFileNameA(NULL, exePath, MAX_PATH)) {
char* lastSlash = strrchr(exePath, '\\');
if (lastSlash) {
*lastSlash = '\0';
sprintf_s(logPath, size, "%s\\YamaService.log", exePath);
return;
}
}
// 备用路径Windows临时目录
char tempPath[MAX_PATH];
if (GetTempPathA(MAX_PATH, tempPath)) {
sprintf_s(logPath, size, "%sYamaService.log", tempPath);
} else {
strncpy_s(logPath, size, "YamaService.log", _TRUNCATE);
}
}
// 日志函数
static void ServiceWriteLog(const char* message)
{
char logPath[MAX_PATH];
GetServiceLogPath(logPath, sizeof(logPath));
FILE* f = fopen(logPath, "a");
if (f) {
SYSTEMTIME st;
GetLocalTime(&st);
fprintf(f, "[%04d-%02d-%02d %02d:%02d:%02d] %s\n",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond,
message);
fclose(f);
}
}
BOOL ServerService_CheckStatus(BOOL* registered, BOOL* running, BOOL ServerService_CheckStatus(BOOL* registered, BOOL* running,
char* exePath, size_t exePathSize) char* exePath, size_t exePathSize)
@@ -148,14 +109,14 @@ int ServerService_Run(void)
ServiceTable[1].lpServiceName = NULL; ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL; ServiceTable[1].lpServiceProc = NULL;
ServiceWriteLog("========================================"); Mprintf("========================================");
ServiceWriteLog("ServerService_Run() called"); Mprintf("ServerService_Run() called");
if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) { if (StartServiceCtrlDispatcher(ServiceTable) == FALSE) {
DWORD err = GetLastError(); DWORD err = GetLastError();
char buffer[256]; char buffer[256];
sprintf_s(buffer, sizeof(buffer), "StartServiceCtrlDispatcher failed: %d", (int)err); sprintf_s(buffer, sizeof(buffer), "StartServiceCtrlDispatcher failed: %d", (int)err);
ServiceWriteLog(buffer); Mprintf(buffer);
return (int)err; return (int)err;
} }
return ERROR_SUCCESS; return ERROR_SUCCESS;
@@ -226,7 +187,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
(void)argc; (void)argc;
(void)argv; (void)argv;
ServiceWriteLog("ServiceMain() called"); Mprintf("ServiceMain() called");
g_StatusHandle = RegisterServiceCtrlHandler( g_StatusHandle = RegisterServiceCtrlHandler(
SERVER_SERVICE_NAME, SERVER_SERVICE_NAME,
@@ -234,7 +195,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
); );
if (g_StatusHandle == NULL) { if (g_StatusHandle == NULL) {
ServiceWriteLog("RegisterServiceCtrlHandler failed"); Mprintf("RegisterServiceCtrlHandler failed");
return; return;
} }
@@ -251,7 +212,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); g_StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (g_StopEvent == NULL) { if (g_StopEvent == NULL) {
ServiceWriteLog("CreateEvent failed"); Mprintf("CreateEvent failed");
g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
g_ServiceStatus.dwWin32ExitCode = GetLastError(); g_ServiceStatus.dwWin32ExitCode = GetLastError();
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
@@ -264,7 +225,7 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwCheckPoint = 0;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
ServiceWriteLog("Service is now running"); Mprintf("Service is now running");
HANDLE hThread = CreateThread(NULL, 0, ServerService_WorkerThread, NULL, 0, NULL); HANDLE hThread = CreateThread(NULL, 0, ServerService_WorkerThread, NULL, 0, NULL);
if (hThread) { if (hThread) {
@@ -280,14 +241,14 @@ static void WINAPI ServiceMain(DWORD argc, LPTSTR* argv)
g_ServiceStatus.dwCheckPoint = 3; g_ServiceStatus.dwCheckPoint = 3;
SetServiceStatus(g_StatusHandle, &g_ServiceStatus); SetServiceStatus(g_StatusHandle, &g_ServiceStatus);
ServiceWriteLog("Service stopped"); Mprintf("Service stopped");
} }
static void WINAPI ServiceCtrlHandler(DWORD ctrlCode) static void WINAPI ServiceCtrlHandler(DWORD ctrlCode)
{ {
switch (ctrlCode) { switch (ctrlCode) {
case SERVICE_CONTROL_STOP: case SERVICE_CONTROL_STOP:
ServiceWriteLog("SERVICE_CONTROL_STOP received"); Mprintf("SERVICE_CONTROL_STOP received");
if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING) if (g_ServiceStatus.dwCurrentState != SERVICE_RUNNING)
break; break;
@@ -318,39 +279,39 @@ DWORD WINAPI ServerService_WorkerThread(LPVOID lpParam)
int heartbeatCount = 0; int heartbeatCount = 0;
char buf[128]; char buf[128];
ServiceWriteLog("========================================"); Mprintf("========================================");
ServiceWriteLog("Worker thread started"); Mprintf("Worker thread started");
ServiceWriteLog("Service will launch Yama GUI in user sessions"); Mprintf("Service will launch Yama GUI in user sessions");
// 初始化会话监控器 // 初始化会话监控器
ServerSessionMonitor monitor; ServerSessionMonitor monitor;
ServerSessionMonitor_Init(&monitor); ServerSessionMonitor_Init(&monitor);
if (!ServerSessionMonitor_Start(&monitor)) { if (!ServerSessionMonitor_Start(&monitor)) {
ServiceWriteLog("ERROR: Failed to start session monitor"); Mprintf("ERROR: Failed to start session monitor");
ServerSessionMonitor_Cleanup(&monitor); ServerSessionMonitor_Cleanup(&monitor);
return ERROR_SERVICE_SPECIFIC_ERROR; return ERROR_SERVICE_SPECIFIC_ERROR;
} }
ServiceWriteLog("Session monitor started successfully"); Mprintf("Session monitor started successfully");
ServiceWriteLog("Yama GUI will be launched automatically in user sessions"); Mprintf("Yama GUI will be launched automatically in user sessions");
// 主循环,只等待停止信号 // 主循环,只等待停止信号
while (WaitForSingleObject(g_StopEvent, 10000) != WAIT_OBJECT_0) { while (WaitForSingleObject(g_StopEvent, 10000) != WAIT_OBJECT_0) {
heartbeatCount++; heartbeatCount++;
if (heartbeatCount % 6 == 0) { // 每60秒记录一次10秒 * 6 = 60秒 if (heartbeatCount % 6 == 0) { // 每60秒记录一次10秒 * 6 = 60秒
sprintf_s(buf, sizeof(buf), "Service heartbeat - uptime: %d minutes", heartbeatCount / 6); sprintf_s(buf, sizeof(buf), "Service heartbeat - uptime: %d minutes", heartbeatCount / 6);
ServiceWriteLog(buf); Mprintf(buf);
} }
} }
ServiceWriteLog("Stop signal received"); Mprintf("Stop signal received");
ServiceWriteLog("Stopping session monitor..."); Mprintf("Stopping session monitor...");
ServerSessionMonitor_Stop(&monitor); ServerSessionMonitor_Stop(&monitor);
ServerSessionMonitor_Cleanup(&monitor); ServerSessionMonitor_Cleanup(&monitor);
ServiceWriteLog("Worker thread exiting"); Mprintf("Worker thread exiting");
ServiceWriteLog("========================================"); Mprintf("========================================");
return ERROR_SUCCESS; return ERROR_SUCCESS;
} }

View File

@@ -16,7 +16,6 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId);
static BOOL IsGuiRunningInSession(ServerSessionMonitor* self, DWORD sessionId); static BOOL IsGuiRunningInSession(ServerSessionMonitor* self, DWORD sessionId);
static void TerminateAllGui(ServerSessionMonitor* self); static void TerminateAllGui(ServerSessionMonitor* self);
static void CleanupDeadProcesses(ServerSessionMonitor* self); static void CleanupDeadProcesses(ServerSessionMonitor* self);
static void ServerMonitor_WriteLog(const char* message);
// 动态数组辅助函数 // 动态数组辅助函数
static void AgentArray_Init(ServerAgentProcessArray* arr); static void AgentArray_Init(ServerAgentProcessArray* arr);
@@ -77,46 +76,6 @@ static void AgentArray_RemoveAt(ServerAgentProcessArray* arr, size_t index)
arr->count--; arr->count--;
} }
// ============================================
// 日志函数
// ============================================
// 获取日志文件路径(程序所在目录)
static void GetMonitorLogPath(char* logPath, size_t size)
{
char exePath[MAX_PATH];
if (GetModuleFileNameA(NULL, exePath, MAX_PATH)) {
char* lastSlash = strrchr(exePath, '\\');
if (lastSlash) {
*lastSlash = '\0';
sprintf_s(logPath, size, "%s\\YamaSessionMonitor.log", exePath);
return;
}
}
// 备用路径Windows临时目录
char tempPath[MAX_PATH];
if (GetTempPathA(MAX_PATH, tempPath)) {
sprintf_s(logPath, size, "%sYamaSessionMonitor.log", tempPath);
} else {
strncpy_s(logPath, size, "YamaSessionMonitor.log", _TRUNCATE);
}
}
static void ServerMonitor_WriteLog(const char* message)
{
char logPath[MAX_PATH];
GetMonitorLogPath(logPath, sizeof(logPath));
FILE* f = fopen(logPath, "a");
if (f) {
SYSTEMTIME st;
GetLocalTime(&st);
fprintf(f, "[%04d-%02d-%02d %02d:%02d:%02d] %s\n",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, message);
fclose(f);
}
}
// ============================================ // ============================================
// 公共接口实现 // 公共接口实现
// ============================================ // ============================================
@@ -139,23 +98,23 @@ void ServerSessionMonitor_Cleanup(ServerSessionMonitor* self)
BOOL ServerSessionMonitor_Start(ServerSessionMonitor* self) BOOL ServerSessionMonitor_Start(ServerSessionMonitor* self)
{ {
if (self->running) { if (self->running) {
ServerMonitor_WriteLog("Monitor already running"); Mprintf("Monitor already running");
return TRUE; return TRUE;
} }
ServerMonitor_WriteLog("========================================"); Mprintf("========================================");
ServerMonitor_WriteLog("Starting server session monitor..."); Mprintf("Starting server session monitor...");
self->running = TRUE; self->running = TRUE;
self->monitorThread = CreateThread(NULL, 0, MonitorThreadProc, self, 0, NULL); self->monitorThread = CreateThread(NULL, 0, MonitorThreadProc, self, 0, NULL);
if (!self->monitorThread) { if (!self->monitorThread) {
ServerMonitor_WriteLog("ERROR: Failed to create monitor thread"); Mprintf("ERROR: Failed to create monitor thread");
self->running = FALSE; self->running = FALSE;
return FALSE; return FALSE;
} }
ServerMonitor_WriteLog("Server session monitor thread created"); Mprintf("Server session monitor thread created");
return TRUE; return TRUE;
} }
@@ -165,14 +124,14 @@ void ServerSessionMonitor_Stop(ServerSessionMonitor* self)
return; return;
} }
ServerMonitor_WriteLog("Stopping server session monitor..."); Mprintf("Stopping server session monitor...");
self->running = FALSE; self->running = FALSE;
if (self->monitorThread) { if (self->monitorThread) {
DWORD waitResult = WaitForSingleObject(self->monitorThread, 10000); DWORD waitResult = WaitForSingleObject(self->monitorThread, 10000);
if (waitResult == WAIT_TIMEOUT) { if (waitResult == WAIT_TIMEOUT) {
// 线程未在规定时间内退出,强制终止 // 线程未在规定时间内退出,强制终止
ServerMonitor_WriteLog("WARNING: Monitor thread did not exit in time, terminating..."); Mprintf("WARNING: Monitor thread did not exit in time, terminating...");
TerminateThread(self->monitorThread, 1); TerminateThread(self->monitorThread, 1);
} }
CloseHandle(self->monitorThread); CloseHandle(self->monitorThread);
@@ -180,11 +139,11 @@ void ServerSessionMonitor_Stop(ServerSessionMonitor* self)
} }
// 终止所有GUI进程 // 终止所有GUI进程
ServerMonitor_WriteLog("Terminating all GUI processes..."); Mprintf("Terminating all GUI processes...");
// TerminateAllGui(self); // TerminateAllGui(self);
ServerMonitor_WriteLog("Server session monitor stopped"); Mprintf("Server session monitor stopped");
ServerMonitor_WriteLog("========================================"); Mprintf("========================================");
} }
// ============================================ // ============================================
@@ -203,7 +162,7 @@ static void MonitorLoop(ServerSessionMonitor* self)
int loopCount = 0; int loopCount = 0;
char buf[256]; char buf[256];
ServerMonitor_WriteLog("Monitor loop started"); Mprintf("Monitor loop started");
while (self->running) { while (self->running) {
loopCount++; loopCount++;
@@ -230,20 +189,20 @@ static void MonitorLoop(ServerSessionMonitor* self)
sprintf_s(buf, sizeof(buf), "Active session found: ID=%d, Name=%s", sprintf_s(buf, sizeof(buf), "Active session found: ID=%d, Name=%s",
(int)sessionId, (int)sessionId,
pSessionInfo[i].pWinStationName); pSessionInfo[i].pWinStationName);
ServerMonitor_WriteLog(buf); Mprintf(buf);
} }
// 检查GUI是否在该会话中运行 // 检查GUI是否在该会话中运行
if (!IsGuiRunningInSession(self, sessionId)) { if (!IsGuiRunningInSession(self, sessionId)) {
sprintf_s(buf, sizeof(buf), "GUI not running in session %d, launching...", (int)sessionId); sprintf_s(buf, sizeof(buf), "GUI not running in session %d, launching...", (int)sessionId);
ServerMonitor_WriteLog(buf); Mprintf(buf);
if (LaunchGuiInSession(self, sessionId)) { if (LaunchGuiInSession(self, sessionId)) {
ServerMonitor_WriteLog("GUI launched successfully"); Mprintf("GUI launched successfully");
// 给程序一些时间启动 // 给程序一些时间启动
Sleep(2000); Sleep(2000);
} else { } else {
ServerMonitor_WriteLog("Failed to launch GUI"); Mprintf("Failed to launch GUI");
} }
} }
@@ -253,13 +212,13 @@ static void MonitorLoop(ServerSessionMonitor* self)
} }
if (!foundActiveSession && loopCount % 5 == 1) { if (!foundActiveSession && loopCount % 5 == 1) {
ServerMonitor_WriteLog("No active sessions found"); Mprintf("No active sessions found");
} }
WTSFreeMemory(pSessionInfo); WTSFreeMemory(pSessionInfo);
} else { } else {
if (loopCount % 5 == 1) { if (loopCount % 5 == 1) {
ServerMonitor_WriteLog("WTSEnumerateSessions failed"); Mprintf("WTSEnumerateSessions failed");
} }
} }
@@ -269,7 +228,7 @@ static void MonitorLoop(ServerSessionMonitor* self)
} }
} }
ServerMonitor_WriteLog("Monitor loop exited"); Mprintf("Monitor loop exited");
} }
static BOOL IsGuiRunningInSession(ServerSessionMonitor* self, DWORD sessionId) static BOOL IsGuiRunningInSession(ServerSessionMonitor* self, DWORD sessionId)
@@ -296,7 +255,7 @@ static BOOL IsGuiRunningInSession(ServerSessionMonitor* self, DWORD sessionId)
// 创建进程快照 // 创建进程快照
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot == INVALID_HANDLE_VALUE) { if (hSnapshot == INVALID_HANDLE_VALUE) {
ServerMonitor_WriteLog("CreateToolhelp32Snapshot failed"); Mprintf("CreateToolhelp32Snapshot failed");
return FALSE; return FALSE;
} }
@@ -338,14 +297,14 @@ static void TerminateAllGui(ServerSessionMonitor* self)
EnterCriticalSection(&self->csProcessList); EnterCriticalSection(&self->csProcessList);
sprintf_s(buf, sizeof(buf), "Terminating %d GUI process(es)", (int)self->agentProcesses.count); sprintf_s(buf, sizeof(buf), "Terminating %d GUI process(es)", (int)self->agentProcesses.count);
ServerMonitor_WriteLog(buf); Mprintf(buf);
for (size_t i = 0; i < self->agentProcesses.count; i++) { for (size_t i = 0; i < self->agentProcesses.count; i++) {
ServerAgentProcessInfo* info = &self->agentProcesses.items[i]; ServerAgentProcessInfo* info = &self->agentProcesses.items[i];
sprintf_s(buf, sizeof(buf), "Terminating GUI PID=%d (Session %d)", sprintf_s(buf, sizeof(buf), "Terminating GUI PID=%d (Session %d)",
(int)info->processId, (int)info->sessionId); (int)info->processId, (int)info->sessionId);
ServerMonitor_WriteLog(buf); Mprintf(buf);
// 检查进程是否还活着 // 检查进程是否还活着
DWORD exitCode; DWORD exitCode;
@@ -355,16 +314,16 @@ static void TerminateAllGui(ServerSessionMonitor* self)
if (!TerminateProcess(info->hProcess, 0)) { if (!TerminateProcess(info->hProcess, 0)) {
sprintf_s(buf, sizeof(buf), "WARNING: Failed to terminate PID=%d, error=%d", sprintf_s(buf, sizeof(buf), "WARNING: Failed to terminate PID=%d, error=%d",
(int)info->processId, (int)GetLastError()); (int)info->processId, (int)GetLastError());
ServerMonitor_WriteLog(buf); Mprintf(buf);
} else { } else {
ServerMonitor_WriteLog("GUI terminated successfully"); Mprintf("GUI terminated successfully");
// 等待进程完全退出 // 等待进程完全退出
WaitForSingleObject(info->hProcess, 5000); WaitForSingleObject(info->hProcess, 5000);
} }
} else { } else {
sprintf_s(buf, sizeof(buf), "GUI PID=%d already exited with code %d", sprintf_s(buf, sizeof(buf), "GUI PID=%d already exited with code %d",
(int)info->processId, (int)exitCode); (int)info->processId, (int)exitCode);
ServerMonitor_WriteLog(buf); Mprintf(buf);
} }
} }
@@ -374,7 +333,7 @@ static void TerminateAllGui(ServerSessionMonitor* self)
self->agentProcesses.count = 0; // 清空列表 self->agentProcesses.count = 0; // 清空列表
LeaveCriticalSection(&self->csProcessList); LeaveCriticalSection(&self->csProcessList);
ServerMonitor_WriteLog("All GUI processes terminated"); Mprintf("All GUI processes terminated");
} }
// 清理已经终止的进程 // 清理已经终止的进程
@@ -394,7 +353,7 @@ static void CleanupDeadProcesses(ServerSessionMonitor* self)
// 进程已退出 // 进程已退出
sprintf_s(buf, sizeof(buf), "GUI PID=%d exited with code %d, cleaning up", sprintf_s(buf, sizeof(buf), "GUI PID=%d exited with code %d, cleaning up",
(int)info->processId, (int)exitCode); (int)info->processId, (int)exitCode);
ServerMonitor_WriteLog(buf); Mprintf(buf);
CloseHandle(info->hProcess); CloseHandle(info->hProcess);
AgentArray_RemoveAt(&self->agentProcesses, i); AgentArray_RemoveAt(&self->agentProcesses, i);
@@ -404,7 +363,7 @@ static void CleanupDeadProcesses(ServerSessionMonitor* self)
// 无法获取退出代码,可能进程已不存在 // 无法获取退出代码,可能进程已不存在
sprintf_s(buf, sizeof(buf), "Cannot query GUI PID=%d, removing from list", sprintf_s(buf, sizeof(buf), "Cannot query GUI PID=%d, removing from list",
(int)info->processId); (int)info->processId);
ServerMonitor_WriteLog(buf); Mprintf(buf);
CloseHandle(info->hProcess); CloseHandle(info->hProcess);
AgentArray_RemoveAt(&self->agentProcesses, i); AgentArray_RemoveAt(&self->agentProcesses, i);
@@ -422,7 +381,7 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
char buf[512]; char buf[512];
sprintf_s(buf, sizeof(buf), "Attempting to launch GUI in session %d", (int)sessionId); sprintf_s(buf, sizeof(buf), "Attempting to launch GUI in session %d", (int)sessionId);
ServerMonitor_WriteLog(buf); Mprintf(buf);
STARTUPINFO si; STARTUPINFO si;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
@@ -436,7 +395,7 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
HANDLE hToken = NULL; HANDLE hToken = NULL;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) { if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {
sprintf_s(buf, sizeof(buf), "OpenProcessToken failed: %d", (int)GetLastError()); sprintf_s(buf, sizeof(buf), "OpenProcessToken failed: %d", (int)GetLastError());
ServerMonitor_WriteLog(buf); Mprintf(buf);
return FALSE; return FALSE;
} }
@@ -445,7 +404,7 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL, if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL,
SecurityImpersonation, TokenPrimary, &hDupToken)) { SecurityImpersonation, TokenPrimary, &hDupToken)) {
sprintf_s(buf, sizeof(buf), "DuplicateTokenEx failed: %d", (int)GetLastError()); sprintf_s(buf, sizeof(buf), "DuplicateTokenEx failed: %d", (int)GetLastError());
ServerMonitor_WriteLog(buf); Mprintf(buf);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
@@ -453,31 +412,31 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
// 修改令牌的会话 ID 为目标用户会话 // 修改令牌的会话 ID 为目标用户会话
if (!SetTokenInformation(hDupToken, TokenSessionId, &sessionId, sizeof(sessionId))) { if (!SetTokenInformation(hDupToken, TokenSessionId, &sessionId, sizeof(sessionId))) {
sprintf_s(buf, sizeof(buf), "SetTokenInformation failed: %d", (int)GetLastError()); sprintf_s(buf, sizeof(buf), "SetTokenInformation failed: %d", (int)GetLastError());
ServerMonitor_WriteLog(buf); Mprintf(buf);
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
ServerMonitor_WriteLog("Token duplicated"); Mprintf("Token duplicated");
// 获取当前程序路径(就是自己) // 获取当前程序路径(就是自己)
char exePath[MAX_PATH]; char exePath[MAX_PATH];
if (!GetModuleFileNameA(NULL, exePath, MAX_PATH)) { if (!GetModuleFileNameA(NULL, exePath, MAX_PATH)) {
ServerMonitor_WriteLog("GetModuleFileName failed"); Mprintf("GetModuleFileName failed");
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
} }
sprintf_s(buf, sizeof(buf), "Service path: %s", exePath); sprintf_s(buf, sizeof(buf), "Service path: %s", exePath);
ServerMonitor_WriteLog(buf); Mprintf(buf);
// 检查文件是否存在 // 检查文件是否存在
DWORD fileAttr = GetFileAttributesA(exePath); DWORD fileAttr = GetFileAttributesA(exePath);
if (fileAttr == INVALID_FILE_ATTRIBUTES) { if (fileAttr == INVALID_FILE_ATTRIBUTES) {
sprintf_s(buf, sizeof(buf), "ERROR: Executable not found at: %s", exePath); sprintf_s(buf, sizeof(buf), "ERROR: Executable not found at: %s", exePath);
ServerMonitor_WriteLog(buf); Mprintf(buf);
CloseHandle(hDupToken); CloseHandle(hDupToken);
CloseHandle(hToken); CloseHandle(hToken);
return FALSE; return FALSE;
@@ -488,20 +447,20 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
sprintf_s(cmdLine, sizeof(cmdLine), "\"%s\" -agent", exePath); sprintf_s(cmdLine, sizeof(cmdLine), "\"%s\" -agent", exePath);
sprintf_s(buf, sizeof(buf), "Command line: %s", cmdLine); sprintf_s(buf, sizeof(buf), "Command line: %s", cmdLine);
ServerMonitor_WriteLog(buf); Mprintf(buf);
// 获取用户令牌(用于获取环境块) // 获取用户令牌(用于获取环境块)
LPVOID lpEnvironment = NULL; LPVOID lpEnvironment = NULL;
HANDLE hUserToken = NULL; HANDLE hUserToken = NULL;
if (!WTSQueryUserToken(sessionId, &hUserToken)) { if (!WTSQueryUserToken(sessionId, &hUserToken)) {
sprintf_s(buf, sizeof(buf), "WTSQueryUserToken failed: %d", (int)GetLastError()); sprintf_s(buf, sizeof(buf), "WTSQueryUserToken failed: %d", (int)GetLastError());
ServerMonitor_WriteLog(buf); Mprintf(buf);
} }
// 使用用户令牌创建环境块 // 使用用户令牌创建环境块
if (hUserToken) { if (hUserToken) {
if (!CreateEnvironmentBlock(&lpEnvironment, hUserToken, FALSE)) { if (!CreateEnvironmentBlock(&lpEnvironment, hUserToken, FALSE)) {
ServerMonitor_WriteLog("CreateEnvironmentBlock failed"); Mprintf("CreateEnvironmentBlock failed");
} }
CloseHandle(hUserToken); CloseHandle(hUserToken);
} }
@@ -527,7 +486,7 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
if (result) { if (result) {
sprintf_s(buf, sizeof(buf), "SUCCESS: GUI process created (PID=%d)", (int)pi.dwProcessId); sprintf_s(buf, sizeof(buf), "SUCCESS: GUI process created (PID=%d)", (int)pi.dwProcessId);
ServerMonitor_WriteLog(buf); Mprintf(buf);
// 保存进程信息,以便停止时可以终止它 // 保存进程信息,以便停止时可以终止它
EnterCriticalSection(&self->csProcessList); EnterCriticalSection(&self->csProcessList);
@@ -542,15 +501,15 @@ static BOOL LaunchGuiInSession(ServerSessionMonitor* self, DWORD sessionId)
} else { } else {
DWORD err = GetLastError(); DWORD err = GetLastError();
sprintf_s(buf, sizeof(buf), "CreateProcessAsUser failed: %d", (int)err); sprintf_s(buf, sizeof(buf), "CreateProcessAsUser failed: %d", (int)err);
ServerMonitor_WriteLog(buf); Mprintf(buf);
// 提供更详细的错误信息 // 提供更详细的错误信息
if (err == ERROR_FILE_NOT_FOUND) { if (err == ERROR_FILE_NOT_FOUND) {
ServerMonitor_WriteLog("ERROR: Executable not found"); Mprintf("ERROR: Executable not found");
} else if (err == ERROR_ACCESS_DENIED) { } else if (err == ERROR_ACCESS_DENIED) {
ServerMonitor_WriteLog("ERROR: Access denied - service may not have sufficient privileges"); Mprintf("ERROR: Access denied - service may not have sufficient privileges");
} else if (err == 1314) { } else if (err == 1314) {
ServerMonitor_WriteLog("ERROR: Service does not have SE_INCREASE_QUOTA privilege"); Mprintf("ERROR: Service does not have SE_INCREASE_QUOTA privilege");
} }
} }