nssm.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #include "nssm.h"
  2. extern unsigned long tls_index;
  3. extern bool is_admin;
  4. extern imports_t imports;
  5. static TCHAR unquoted_imagepath[PATH_LENGTH];
  6. static TCHAR imagepath[PATH_LENGTH];
  7. /* Are two strings case-insensitively equivalent? */
  8. int str_equiv(const TCHAR *a, const TCHAR *b) {
  9. size_t len = _tcslen(a);
  10. if (_tcslen(b) != len) return 0;
  11. if (_tcsnicmp(a, b, len)) return 0;
  12. return 1;
  13. }
  14. /* Convert a string to a number. */
  15. int str_number(const TCHAR *string, unsigned long *number, TCHAR **bogus) {
  16. if (! string) return 1;
  17. *number = _tcstoul(string, bogus, 0);
  18. if (**bogus) return 2;
  19. return 0;
  20. }
  21. int str_number(const TCHAR *string, unsigned long *number) {
  22. TCHAR *bogus;
  23. return str_number(string, number, &bogus);
  24. }
  25. /* Remove basename of a path. */
  26. void strip_basename(TCHAR *buffer) {
  27. size_t len = _tcslen(buffer);
  28. size_t i;
  29. for (i = len; i && buffer[i] != _T('\\') && buffer[i] != _T('/'); i--);
  30. /* X:\ is OK. */
  31. if (i && buffer[i - 1] == _T(':')) i++;
  32. buffer[i] = _T('\0');
  33. }
  34. /* How to use me correctly */
  35. int usage(int ret) {
  36. if (GetConsoleWindow()) print_message(stderr, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_CONFIGURATION, NSSM_DATE);
  37. else popup_message(0, MB_OK, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_CONFIGURATION, NSSM_DATE);
  38. return(ret);
  39. }
  40. void check_admin() {
  41. is_admin = false;
  42. /* Lifted from MSDN examples */
  43. PSID AdministratorsGroup;
  44. SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
  45. if (! AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) return;
  46. CheckTokenMembership(0, AdministratorsGroup, /*XXX*/(PBOOL) &is_admin);
  47. FreeSid(AdministratorsGroup);
  48. }
  49. static int elevate(int argc, TCHAR **argv, unsigned long message) {
  50. print_message(stderr, message);
  51. SHELLEXECUTEINFO sei;
  52. ZeroMemory(&sei, sizeof(sei));
  53. sei.cbSize = sizeof(sei);
  54. sei.lpVerb = _T("runas");
  55. sei.lpFile = (TCHAR *) nssm_imagepath();
  56. TCHAR *args = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, EXE_LENGTH * sizeof(TCHAR));
  57. if (! args) {
  58. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("GetCommandLine()"), _T("elevate()"));
  59. return 111;
  60. }
  61. /* Get command line, which includes the path to NSSM, and skip that part. */
  62. _sntprintf_s(args, EXE_LENGTH, _TRUNCATE, _T("%s"), GetCommandLine());
  63. size_t s = _tcslen(argv[0]) + 1;
  64. if (args[0] == _T('"')) s += 2;
  65. while (isspace(args[s])) s++;
  66. sei.lpParameters = args + s;
  67. sei.nShow = SW_SHOW;
  68. unsigned long exitcode = 0;
  69. if (! ShellExecuteEx(&sei)) exitcode = 100;
  70. HeapFree(GetProcessHeap(), 0, (void *) args);
  71. return exitcode;
  72. }
  73. int num_cpus() {
  74. DWORD_PTR i, affinity, system_affinity;
  75. if (! GetProcessAffinityMask(GetCurrentProcess(), &affinity, &system_affinity)) return 64;
  76. for (i = 0; system_affinity & (1LL << i); i++);
  77. return (int) i;
  78. }
  79. const TCHAR *nssm_unquoted_imagepath() {
  80. return unquoted_imagepath;
  81. }
  82. const TCHAR *nssm_imagepath() {
  83. return imagepath;
  84. }
  85. int _tmain(int argc, TCHAR **argv) {
  86. check_console();
  87. #ifdef UNICODE
  88. /*
  89. Ensure we write in UTF-16 mode, so that non-ASCII characters don't get
  90. mangled. If we were compiled in ANSI mode it won't work.
  91. */
  92. _setmode(_fileno(stdout), _O_U16TEXT);
  93. _setmode(_fileno(stderr), _O_U16TEXT);
  94. #endif
  95. /* Remember if we are admin */
  96. check_admin();
  97. /* Set up function pointers. */
  98. if (get_imports()) exit(111);
  99. /* Remember our path for later. */
  100. GetModuleFileName(0, unquoted_imagepath, _countof(unquoted_imagepath));
  101. GetModuleFileName(0, imagepath, _countof(imagepath));
  102. PathQuoteSpaces(imagepath);
  103. /* Elevate */
  104. if (argc > 1) {
  105. /*
  106. Valid commands are:
  107. start, stop, pause, continue, install, edit, get, set, reset, unset, remove
  108. */
  109. if (str_equiv(argv[1], _T("start"))) exit(control_service(NSSM_SERVICE_CONTROL_START, argc - 2, argv + 2));
  110. if (str_equiv(argv[1], _T("stop"))) exit(control_service(SERVICE_CONTROL_STOP, argc - 2, argv + 2));
  111. if (str_equiv(argv[1], _T("restart"))) {
  112. int ret = control_service(SERVICE_CONTROL_STOP, argc - 2, argv + 2);
  113. if (ret) exit(ret);
  114. exit(control_service(NSSM_SERVICE_CONTROL_START, argc - 2, argv + 2));
  115. }
  116. if (str_equiv(argv[1], _T("pause"))) exit(control_service(SERVICE_CONTROL_PAUSE, argc - 2, argv + 2));
  117. if (str_equiv(argv[1], _T("continue"))) exit(control_service(SERVICE_CONTROL_CONTINUE, argc - 2, argv + 2));
  118. if (str_equiv(argv[1], _T("status"))) exit(control_service(SERVICE_CONTROL_INTERROGATE, argc - 2, argv + 2));
  119. if (str_equiv(argv[1], _T("rotate"))) exit(control_service(NSSM_SERVICE_CONTROL_ROTATE, argc - 2, argv + 2));
  120. if (str_equiv(argv[1], _T("install"))) {
  121. if (! is_admin) exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_INSTALL));
  122. exit(pre_install_service(argc - 2, argv + 2));
  123. }
  124. if (str_equiv(argv[1], _T("edit")) || str_equiv(argv[1], _T("get")) || str_equiv(argv[1], _T("set")) || str_equiv(argv[1], _T("reset")) || str_equiv(argv[1], _T("unset"))) {
  125. int ret = pre_edit_service(argc - 1, argv + 1);
  126. if (ret == 3 && ! is_admin && argc == 3) exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_EDIT));
  127. /* There might be a password here. */
  128. for (int i = 0; i < argc; i++) SecureZeroMemory(argv[i], _tcslen(argv[i]) * sizeof(TCHAR));
  129. exit(ret);
  130. }
  131. if (str_equiv(argv[1], _T("remove"))) {
  132. if (! is_admin) exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_REMOVE));
  133. exit(pre_remove_service(argc - 2, argv + 2));
  134. }
  135. }
  136. /* Thread local storage for error message buffer */
  137. tls_index = TlsAlloc();
  138. /* Register messages */
  139. if (is_admin) create_messages();
  140. /*
  141. Optimisation for Windows 2000:
  142. When we're run from the command line the StartServiceCtrlDispatcher() call
  143. will time out after a few seconds on Windows 2000. On newer versions the
  144. call returns instantly. Check for stdin first and only try to call the
  145. function if there's no input stream found. Although it's possible that
  146. we're running with input redirected it's much more likely that we're
  147. actually running as a service.
  148. This will save time when running with no arguments from a command prompt.
  149. */
  150. if (! GetStdHandle(STD_INPUT_HANDLE)) {
  151. /* Start service magic */
  152. SERVICE_TABLE_ENTRY table[] = { { NSSM, service_main }, { 0, 0 } };
  153. if (! StartServiceCtrlDispatcher(table)) {
  154. unsigned long error = GetLastError();
  155. /* User probably ran nssm with no argument */
  156. if (error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) exit(usage(1));
  157. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_DISPATCHER_FAILED, error_string(error), 0);
  158. free_imports();
  159. exit(100);
  160. }
  161. }
  162. else exit(usage(1));
  163. /* And nothing more to do */
  164. exit(0);
  165. }