X-Git-Url: http://git.iain.cx/?a=blobdiff_plain;f=nssm.cpp;h=7a7311425f7fff20207c8389dec37b5ca03007b9;hb=fb6318bf814fd7f3445de8c83b7620e1b6b3c197;hp=3ba473ff6c22e1994d89d3b6a2b3ad1e73cd01e6;hpb=e9d9b2fa71473e96650fe3fc4ee0d5535c6725d8;p=nssm.git diff --git a/nssm.cpp b/nssm.cpp index 3ba473f..7a73114 100644 --- a/nssm.cpp +++ b/nssm.cpp @@ -1,5 +1,8 @@ #include "nssm.h" +extern unsigned long tls_index; +extern bool is_admin; + /* String function */ int str_equiv(const char *a, const char *b) { int i; @@ -25,30 +28,55 @@ int usage(int ret) { return(ret); } +void check_admin() { + is_admin = false; + + /* Lifted from MSDN examples */ + PSID AdministratorsGroup; + SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY; + if (! AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) return; + CheckTokenMembership(0, AdministratorsGroup, /*XXX*/(PBOOL) &is_admin); + FreeSid(AdministratorsGroup); +} + int main(int argc, char **argv) { - /* Require an argument since users may try to run nssm directly */ - if (argc == 1) exit(usage(1)); + /* Remember if we are admin */ + check_admin(); - /* Valid commands are install or remove */ - if (str_equiv(argv[1], "install")) { - exit(pre_install_service(argc - 2, argv + 2)); - } - if (str_equiv(argv[1], "remove")) { - exit(pre_remove_service(argc - 2, argv + 2)); + /* Elevate */ + if (argc > 1) { + if (str_equiv(argv[1], "install") || str_equiv(argv[1], "remove")) { + if (! is_admin) { + fprintf(stderr, "Administrator access is needed to %s a service.\n", argv[1]); + exit(100); + } + } + + /* Valid commands are install or remove */ + if (str_equiv(argv[1], "install")) { + exit(pre_install_service(argc - 2, argv + 2)); + } + if (str_equiv(argv[1], "remove")) { + exit(pre_remove_service(argc - 2, argv + 2)); + } } - /* Undocumented: "run" is used to actually do service stuff */ - if (! str_equiv(argv[1], NSSM_RUN)) exit(usage(2)); + + /* Thread local storage for error message buffer */ + tls_index = TlsAlloc(); /* Register messages */ - create_messages(); + if (is_admin) create_messages(); /* Start service magic */ SERVICE_TABLE_ENTRY table[] = { { NSSM, service_main }, { 0, 0 } }; if (! StartServiceCtrlDispatcher(table)) { - log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_DISPATCHER_FAILED, error_string(GetLastError()), 0); - return 100; + unsigned long error = GetLastError(); + /* User probably ran nssm with no argument */ + if (error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) exit(usage(1)); + log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_DISPATCHER_FAILED, error_string(error), 0); + exit(100); } /* And nothing more to do */ - return 0; + exit(0); }