nssm.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. static TCHAR imageargv0[PATH_LENGTH];
  8. void nssm_exit(int status) {
  9. free_imports();
  10. unsetup_utf8();
  11. exit(status);
  12. }
  13. /* Are two strings case-insensitively equivalent? */
  14. int str_equiv(const TCHAR *a, const TCHAR *b) {
  15. size_t len = _tcslen(a);
  16. if (_tcslen(b) != len) return 0;
  17. if (_tcsnicmp(a, b, len)) return 0;
  18. return 1;
  19. }
  20. /* Convert a string to a number. */
  21. int str_number(const TCHAR *string, unsigned long *number, TCHAR **bogus) {
  22. if (! string) return 1;
  23. *number = _tcstoul(string, bogus, 0);
  24. if (**bogus) return 2;
  25. return 0;
  26. }
  27. /* User requested us to print our version. */
  28. static bool is_version(const TCHAR *s) {
  29. if (! s || ! *s) return false;
  30. /* /version */
  31. if (*s == '/') s++;
  32. else if (*s == '-') {
  33. /* -v, -V, -version, --version */
  34. s++;
  35. if (*s == '-') s++;
  36. else if (str_equiv(s, _T("v"))) return true;
  37. }
  38. if (str_equiv(s, _T("version"))) return true;
  39. return false;
  40. }
  41. int str_number(const TCHAR *string, unsigned long *number) {
  42. TCHAR *bogus;
  43. return str_number(string, number, &bogus);
  44. }
  45. /* Does a char need to be escaped? */
  46. static bool needs_escape(const TCHAR c) {
  47. if (c == _T('"')) return true;
  48. if (c == _T('&')) return true;
  49. if (c == _T('%')) return true;
  50. if (c == _T('^')) return true;
  51. if (c == _T('<')) return true;
  52. if (c == _T('>')) return true;
  53. if (c == _T('|')) return true;
  54. return false;
  55. }
  56. /* Does a char need to be quoted? */
  57. static bool needs_quote(const TCHAR c) {
  58. if (c == _T(' ')) return true;
  59. if (c == _T('\t')) return true;
  60. if (c == _T('\n')) return true;
  61. if (c == _T('\v')) return true;
  62. if (c == _T('"')) return true;
  63. if (c == _T('*')) return true;
  64. return needs_escape(c);
  65. }
  66. /* https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ */
  67. /* http://www.robvanderwoude.com/escapechars.php */
  68. int quote(const TCHAR *unquoted, TCHAR *buffer, size_t buflen) {
  69. size_t i, j, n;
  70. size_t len = _tcslen(unquoted);
  71. if (len > buflen - 1) return 1;
  72. bool escape = false;
  73. bool quotes = false;
  74. for (i = 0; i < len; i++) {
  75. if (needs_escape(unquoted[i])) {
  76. escape = quotes = true;
  77. break;
  78. }
  79. if (needs_quote(unquoted[i])) quotes = true;
  80. }
  81. if (! quotes) {
  82. memmove(buffer, unquoted, (len + 1) * sizeof(TCHAR));
  83. return 0;
  84. }
  85. /* "" */
  86. size_t quoted_len = 2;
  87. if (escape) quoted_len += 2;
  88. for (i = 0; ; i++) {
  89. n = 0;
  90. while (i != len && unquoted[i] == _T('\\')) {
  91. i++;
  92. n++;
  93. }
  94. if (i == len) {
  95. quoted_len += n * 2;
  96. break;
  97. }
  98. else if (unquoted[i] == _T('"')) quoted_len += n * 2 + 2;
  99. else quoted_len += n + 1;
  100. if (needs_escape(unquoted[i])) quoted_len += n;
  101. }
  102. if (quoted_len > buflen - 1) return 1;
  103. TCHAR *s = buffer;
  104. if (escape) *s++ = _T('^');
  105. *s++ = _T('"');
  106. for (i = 0; ; i++) {
  107. n = 0;
  108. while (i != len && unquoted[i] == _T('\\')) {
  109. i++;
  110. n++;
  111. }
  112. if (i == len) {
  113. for (j = 0; j < n * 2; j++) {
  114. if (escape) *s++ = _T('^');
  115. *s++ = _T('\\');
  116. }
  117. break;
  118. }
  119. else if (unquoted[i] == _T('"')) {
  120. for (j = 0; j < n * 2 + 1; j++) {
  121. if (escape) *s++ = _T('^');
  122. *s++ = _T('\\');
  123. }
  124. if (escape && needs_escape(unquoted[i])) *s++ = _T('^');
  125. *s++ = unquoted[i];
  126. }
  127. else {
  128. for (j = 0; j < n; j++) {
  129. if (escape) *s++ = _T('^');
  130. *s++ = _T('\\');
  131. }
  132. if (escape && needs_escape(unquoted[i])) *s++ = _T('^');
  133. *s++ = unquoted[i];
  134. }
  135. }
  136. if (escape) *s++ = _T('^');
  137. *s++ = _T('"');
  138. *s++ = _T('\0');
  139. return 0;
  140. }
  141. /* Remove basename of a path. */
  142. void strip_basename(TCHAR *buffer) {
  143. size_t len = _tcslen(buffer);
  144. size_t i;
  145. for (i = len; i && buffer[i] != _T('\\') && buffer[i] != _T('/'); i--);
  146. /* X:\ is OK. */
  147. if (i && buffer[i - 1] == _T(':')) i++;
  148. buffer[i] = _T('\0');
  149. }
  150. /* How to use me correctly */
  151. int usage(int ret) {
  152. if ((! GetConsoleWindow() || ! GetStdHandle(STD_OUTPUT_HANDLE)) && GetProcessWindowStation()) popup_message(0, MB_OK, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_CONFIGURATION, NSSM_DATE);
  153. else print_message(stderr, NSSM_MESSAGE_USAGE, NSSM_VERSION, NSSM_CONFIGURATION, NSSM_DATE);
  154. return(ret);
  155. }
  156. void check_admin() {
  157. is_admin = false;
  158. /* Lifted from MSDN examples */
  159. PSID AdministratorsGroup;
  160. SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
  161. if (! AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdministratorsGroup)) return;
  162. CheckTokenMembership(0, AdministratorsGroup, /*XXX*/(PBOOL) &is_admin);
  163. FreeSid(AdministratorsGroup);
  164. }
  165. static int elevate(int argc, TCHAR **argv, unsigned long message) {
  166. print_message(stderr, message);
  167. SHELLEXECUTEINFO sei;
  168. ZeroMemory(&sei, sizeof(sei));
  169. sei.cbSize = sizeof(sei);
  170. sei.lpVerb = _T("runas");
  171. sei.lpFile = (TCHAR *) nssm_imagepath();
  172. TCHAR *args = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, EXE_LENGTH * sizeof(TCHAR));
  173. if (! args) {
  174. print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("GetCommandLine()"), _T("elevate()"));
  175. return 111;
  176. }
  177. /* Get command line, which includes the path to NSSM, and skip that part. */
  178. _sntprintf_s(args, EXE_LENGTH, _TRUNCATE, _T("%s"), GetCommandLine());
  179. size_t s = _tcslen(argv[0]) + 1;
  180. if (args[0] == _T('"')) s += 2;
  181. while (isspace(args[s])) s++;
  182. sei.lpParameters = args + s;
  183. sei.nShow = SW_SHOW;
  184. unsigned long exitcode = 0;
  185. if (! ShellExecuteEx(&sei)) exitcode = 100;
  186. HeapFree(GetProcessHeap(), 0, (void *) args);
  187. return exitcode;
  188. }
  189. int num_cpus() {
  190. DWORD_PTR i, affinity, system_affinity;
  191. if (! GetProcessAffinityMask(GetCurrentProcess(), &affinity, &system_affinity)) return 64;
  192. for (i = 0; system_affinity & (1LL << i); i++) if (i == 64) break;
  193. return (int) i;
  194. }
  195. const TCHAR *nssm_unquoted_imagepath() {
  196. return unquoted_imagepath;
  197. }
  198. const TCHAR *nssm_imagepath() {
  199. return imagepath;
  200. }
  201. const TCHAR *nssm_exe() {
  202. return imageargv0;
  203. }
  204. int _tmain(int argc, TCHAR **argv) {
  205. if (check_console()) setup_utf8();
  206. /* Remember if we are admin */
  207. check_admin();
  208. /* Set up function pointers. */
  209. if (get_imports()) nssm_exit(111);
  210. /* Remember our path for later. */
  211. _sntprintf_s(imageargv0, _countof(imageargv0), _TRUNCATE, _T("%s"), argv[0]);
  212. PathQuoteSpaces(imageargv0);
  213. GetModuleFileName(0, unquoted_imagepath, _countof(unquoted_imagepath));
  214. GetModuleFileName(0, imagepath, _countof(imagepath));
  215. PathQuoteSpaces(imagepath);
  216. /* Elevate */
  217. if (argc > 1) {
  218. /*
  219. Valid commands are:
  220. start, stop, pause, continue, install, edit, get, set, reset, unset, remove
  221. status, statuscode, rotate, list, processes, version
  222. */
  223. if (is_version(argv[1])) {
  224. _tprintf(_T("%s %s %s %s\n"), NSSM, NSSM_VERSION, NSSM_CONFIGURATION, NSSM_DATE);
  225. nssm_exit(0);
  226. }
  227. if (str_equiv(argv[1], _T("start"))) nssm_exit(control_service(NSSM_SERVICE_CONTROL_START, argc - 2, argv + 2));
  228. if (str_equiv(argv[1], _T("stop"))) nssm_exit(control_service(SERVICE_CONTROL_STOP, argc - 2, argv + 2));
  229. if (str_equiv(argv[1], _T("restart"))) {
  230. int ret = control_service(SERVICE_CONTROL_STOP, argc - 2, argv + 2);
  231. if (ret) nssm_exit(ret);
  232. nssm_exit(control_service(NSSM_SERVICE_CONTROL_START, argc - 2, argv + 2));
  233. }
  234. if (str_equiv(argv[1], _T("pause"))) nssm_exit(control_service(SERVICE_CONTROL_PAUSE, argc - 2, argv + 2));
  235. if (str_equiv(argv[1], _T("continue"))) nssm_exit(control_service(SERVICE_CONTROL_CONTINUE, argc - 2, argv + 2));
  236. if (str_equiv(argv[1], _T("status"))) nssm_exit(control_service(SERVICE_CONTROL_INTERROGATE, argc - 2, argv + 2));
  237. if (str_equiv(argv[1], _T("statuscode"))) nssm_exit(control_service(SERVICE_CONTROL_INTERROGATE, argc - 2, argv + 2, true));
  238. if (str_equiv(argv[1], _T("rotate"))) nssm_exit(control_service(NSSM_SERVICE_CONTROL_ROTATE, argc - 2, argv + 2));
  239. if (str_equiv(argv[1], _T("install"))) {
  240. if (! is_admin) nssm_exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_INSTALL));
  241. create_messages();
  242. nssm_exit(pre_install_service(argc - 2, argv + 2));
  243. }
  244. 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")) || str_equiv(argv[1], _T("dump"))) {
  245. int ret = pre_edit_service(argc - 1, argv + 1);
  246. if (ret == 3 && ! is_admin && argc == 3) nssm_exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_EDIT));
  247. /* There might be a password here. */
  248. for (int i = 0; i < argc; i++) SecureZeroMemory(argv[i], _tcslen(argv[i]) * sizeof(TCHAR));
  249. nssm_exit(ret);
  250. }
  251. if (str_equiv(argv[1], _T("list"))) nssm_exit(list_nssm_services(argc - 2, argv + 2));
  252. if (str_equiv(argv[1], _T("processes"))) nssm_exit(service_process_tree(argc - 2, argv + 2));
  253. if (str_equiv(argv[1], _T("remove"))) {
  254. if (! is_admin) nssm_exit(elevate(argc, argv, NSSM_MESSAGE_NOT_ADMINISTRATOR_CANNOT_REMOVE));
  255. nssm_exit(pre_remove_service(argc - 2, argv + 2));
  256. }
  257. }
  258. /* Thread local storage for error message buffer */
  259. tls_index = TlsAlloc();
  260. /* Register messages */
  261. if (is_admin) create_messages();
  262. /*
  263. Optimisation for Windows 2000:
  264. When we're run from the command line the StartServiceCtrlDispatcher() call
  265. will time out after a few seconds on Windows 2000. On newer versions the
  266. call returns instantly. Check for stdin first and only try to call the
  267. function if there's no input stream found. Although it's possible that
  268. we're running with input redirected it's much more likely that we're
  269. actually running as a service.
  270. This will save time when running with no arguments from a command prompt.
  271. */
  272. if (! GetStdHandle(STD_INPUT_HANDLE)) {
  273. /* Start service magic */
  274. SERVICE_TABLE_ENTRY table[] = { { NSSM, service_main }, { 0, 0 } };
  275. if (! StartServiceCtrlDispatcher(table)) {
  276. unsigned long error = GetLastError();
  277. /* User probably ran nssm with no argument */
  278. if (error == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) nssm_exit(usage(1));
  279. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_DISPATCHER_FAILED, error_string(error), 0);
  280. nssm_exit(100);
  281. }
  282. }
  283. else nssm_exit(usage(1));
  284. /* And nothing more to do */
  285. nssm_exit(0);
  286. }