registry.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. #include "nssm.h"
  2. extern const TCHAR *exit_action_strings[];
  3. static int service_registry_path(const TCHAR *service_name, bool parameters, const TCHAR *sub, TCHAR *buffer, unsigned long buflen) {
  4. int ret;
  5. if (parameters) {
  6. if (sub) ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY _T("\\") NSSM_REG_PARAMETERS _T("\\%s"), service_name, sub);
  7. else ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY _T("\\") NSSM_REG_PARAMETERS, service_name);
  8. }
  9. else ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY, service_name);
  10. return ret;
  11. }
  12. static long open_registry_key(const TCHAR *registry, REGSAM sam, HKEY *key, bool must_exist) {
  13. long error;
  14. if (sam & KEY_SET_VALUE) {
  15. error = RegCreateKeyEx(HKEY_LOCAL_MACHINE, registry, 0, 0, REG_OPTION_NON_VOLATILE, sam, 0, key, 0);
  16. if (error != ERROR_SUCCESS) {
  17. *key = 0;
  18. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENKEY_FAILED, registry, error_string(GetLastError()), 0);
  19. return error;
  20. }
  21. }
  22. else {
  23. error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, registry, 0, sam, key);
  24. if (error != ERROR_SUCCESS) {
  25. *key = 0;
  26. if (error != ERROR_FILE_NOT_FOUND || must_exist) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENKEY_FAILED, registry, error_string(GetLastError()), 0);
  27. }
  28. }
  29. return error;
  30. }
  31. static HKEY open_registry_key(const TCHAR *registry, REGSAM sam, bool must_exist) {
  32. HKEY key;
  33. long error = open_registry_key(registry, sam, &key, must_exist);
  34. return key;
  35. }
  36. int create_messages() {
  37. HKEY key;
  38. TCHAR registry[KEY_LENGTH];
  39. if (_sntprintf_s(registry, _countof(registry), _TRUNCATE, _T("SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s"), NSSM) < 0) {
  40. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("eventlog registry"), _T("create_messages()"), 0);
  41. return 1;
  42. }
  43. if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, registry, 0, 0, REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &key, 0) != ERROR_SUCCESS) {
  44. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENKEY_FAILED, registry, error_string(GetLastError()), 0);
  45. return 2;
  46. }
  47. /* Get path of this program */
  48. const TCHAR *path = nssm_unquoted_imagepath();
  49. /* Try to register the module but don't worry so much on failure */
  50. RegSetValueEx(key, _T("EventMessageFile"), 0, REG_SZ, (const unsigned char *) path, (unsigned long) (_tcslen(path) + 1) * sizeof(TCHAR));
  51. unsigned long types = EVENTLOG_INFORMATION_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_ERROR_TYPE;
  52. RegSetValueEx(key, _T("TypesSupported"), 0, REG_DWORD, (const unsigned char *) &types, sizeof(types));
  53. return 0;
  54. }
  55. long enumerate_registry_values(HKEY key, unsigned long *index, TCHAR *name, unsigned long namelen) {
  56. unsigned long type;
  57. unsigned long datalen = namelen;
  58. long error = RegEnumValue(key, *index, name, &datalen, 0, &type, 0, 0);
  59. if (error == ERROR_SUCCESS) ++*index;
  60. return error;
  61. }
  62. int create_parameters(nssm_service_t *service, bool editing) {
  63. /* Try to open the registry */
  64. HKEY key = open_registry(service->name, KEY_WRITE);
  65. if (! key) return 1;
  66. /* Remember parameters in case we need to delete them. */
  67. TCHAR registry[KEY_LENGTH];
  68. int ret = service_registry_path(service->name, true, 0, registry, _countof(registry));
  69. /* Try to create the parameters */
  70. if (set_expand_string(key, NSSM_REG_EXE, service->exe)) {
  71. if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
  72. RegCloseKey(key);
  73. return 2;
  74. }
  75. if (set_expand_string(key, NSSM_REG_FLAGS, service->flags)) {
  76. if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
  77. RegCloseKey(key);
  78. return 3;
  79. }
  80. if (set_expand_string(key, NSSM_REG_DIR, service->dir)) {
  81. if (ret > 0) RegDeleteKey(HKEY_LOCAL_MACHINE, registry);
  82. RegCloseKey(key);
  83. return 4;
  84. }
  85. /* Other non-default parameters. May fail. */
  86. if (service->priority != NORMAL_PRIORITY_CLASS) set_number(key, NSSM_REG_PRIORITY, service->priority);
  87. else if (editing) RegDeleteValue(key, NSSM_REG_PRIORITY);
  88. if (service->affinity) {
  89. TCHAR *string;
  90. if (! affinity_mask_to_string(service->affinity, &string)) {
  91. if (RegSetValueEx(key, NSSM_REG_AFFINITY, 0, REG_SZ, (const unsigned char *) string, (unsigned long) (_tcslen(string) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) {
  92. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_AFFINITY, error_string(GetLastError()), 0);
  93. HeapFree(GetProcessHeap(), 0, string);
  94. return 5;
  95. }
  96. }
  97. if (string) HeapFree(GetProcessHeap(), 0, string);
  98. }
  99. else if (editing) RegDeleteValue(key, NSSM_REG_AFFINITY);
  100. unsigned long stop_method_skip = ~service->stop_method;
  101. if (stop_method_skip) set_number(key, NSSM_REG_STOP_METHOD_SKIP, stop_method_skip);
  102. else if (editing) RegDeleteValue(key, NSSM_REG_STOP_METHOD_SKIP);
  103. if (service->default_exit_action < NSSM_NUM_EXIT_ACTIONS) create_exit_action(service->name, exit_action_strings[service->default_exit_action], editing);
  104. if (service->restart_delay) set_number(key, NSSM_REG_RESTART_DELAY, service->restart_delay);
  105. else if (editing) RegDeleteValue(key, NSSM_REG_RESTART_DELAY);
  106. if (service->throttle_delay != NSSM_RESET_THROTTLE_RESTART) set_number(key, NSSM_REG_THROTTLE, service->throttle_delay);
  107. else if (editing) RegDeleteValue(key, NSSM_REG_THROTTLE);
  108. if (service->kill_console_delay != NSSM_KILL_CONSOLE_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD, service->kill_console_delay);
  109. else if (editing) RegDeleteValue(key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD);
  110. if (service->kill_window_delay != NSSM_KILL_WINDOW_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD, service->kill_window_delay);
  111. else if (editing) RegDeleteValue(key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD);
  112. if (service->kill_threads_delay != NSSM_KILL_THREADS_GRACE_PERIOD) set_number(key, NSSM_REG_KILL_THREADS_GRACE_PERIOD, service->kill_threads_delay);
  113. else if (editing) RegDeleteValue(key, NSSM_REG_KILL_THREADS_GRACE_PERIOD);
  114. if (! service->kill_process_tree) set_number(key, NSSM_REG_KILL_PROCESS_TREE, 0);
  115. else if (editing) RegDeleteValue(key, NSSM_REG_KILL_PROCESS_TREE);
  116. if (service->stdin_path[0] || editing) {
  117. if (service->stdin_path[0]) set_expand_string(key, NSSM_REG_STDIN, service->stdin_path);
  118. else if (editing) RegDeleteValue(key, NSSM_REG_STDIN);
  119. if (service->stdin_sharing != NSSM_STDIN_SHARING) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_SHARING, service->stdin_sharing);
  120. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_SHARING);
  121. if (service->stdin_disposition != NSSM_STDIN_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_DISPOSITION, service->stdin_disposition);
  122. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_DISPOSITION);
  123. if (service->stdin_flags != NSSM_STDIN_FLAGS) set_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_FLAGS, service->stdin_flags);
  124. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDIN, NSSM_REG_STDIO_FLAGS);
  125. }
  126. if (service->stdout_path[0] || editing) {
  127. if (service->stdout_path[0]) set_expand_string(key, NSSM_REG_STDOUT, service->stdout_path);
  128. else if (editing) RegDeleteValue(key, NSSM_REG_STDOUT);
  129. if (service->stdout_sharing != NSSM_STDOUT_SHARING) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_SHARING, service->stdout_sharing);
  130. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_SHARING);
  131. if (service->stdout_disposition != NSSM_STDOUT_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_DISPOSITION, service->stdout_disposition);
  132. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_DISPOSITION);
  133. if (service->stdout_flags != NSSM_STDOUT_FLAGS) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_FLAGS, service->stdout_flags);
  134. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_FLAGS);
  135. if (service->stdout_copy_and_truncate) set_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_COPY_AND_TRUNCATE, 1);
  136. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDOUT, NSSM_REG_STDIO_COPY_AND_TRUNCATE);
  137. }
  138. if (service->stderr_path[0] || editing) {
  139. if (service->stderr_path[0]) set_expand_string(key, NSSM_REG_STDERR, service->stderr_path);
  140. else if (editing) RegDeleteValue(key, NSSM_REG_STDERR);
  141. if (service->stderr_sharing != NSSM_STDERR_SHARING) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_SHARING, service->stderr_sharing);
  142. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_SHARING);
  143. if (service->stderr_disposition != NSSM_STDERR_DISPOSITION) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_DISPOSITION, service->stderr_disposition);
  144. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_DISPOSITION);
  145. if (service->stderr_flags != NSSM_STDERR_FLAGS) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_FLAGS, service->stderr_flags);
  146. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_FLAGS);
  147. if (service->stderr_copy_and_truncate) set_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_COPY_AND_TRUNCATE, 1);
  148. else if (editing) delete_createfile_parameter(key, NSSM_REG_STDERR, NSSM_REG_STDIO_COPY_AND_TRUNCATE);
  149. }
  150. if (service->timestamp_log) set_number(key, NSSM_REG_TIMESTAMP_LOG, 1);
  151. else if (editing) RegDeleteValue(key, NSSM_REG_TIMESTAMP_LOG);
  152. if (service->hook_share_output_handles) set_number(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES, 1);
  153. else if (editing) RegDeleteValue(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES);
  154. if (service->rotate_files) set_number(key, NSSM_REG_ROTATE, 1);
  155. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE);
  156. if (service->rotate_stdout_online) set_number(key, NSSM_REG_ROTATE_ONLINE, 1);
  157. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_ONLINE);
  158. if (service->rotate_seconds) set_number(key, NSSM_REG_ROTATE_SECONDS, service->rotate_seconds);
  159. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_SECONDS);
  160. if (service->rotate_bytes_low) set_number(key, NSSM_REG_ROTATE_BYTES_LOW, service->rotate_bytes_low);
  161. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_BYTES_LOW);
  162. if (service->rotate_bytes_high) set_number(key, NSSM_REG_ROTATE_BYTES_HIGH, service->rotate_bytes_high);
  163. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_BYTES_HIGH);
  164. if (service->rotate_delay != NSSM_ROTATE_DELAY) set_number(key, NSSM_REG_ROTATE_DELAY, service->rotate_delay);
  165. else if (editing) RegDeleteValue(key, NSSM_REG_ROTATE_DELAY);
  166. if (service->no_console) set_number(key, NSSM_REG_NO_CONSOLE, 1);
  167. else if (editing) RegDeleteValue(key, NSSM_REG_NO_CONSOLE);
  168. /* Environment */
  169. if (service->env) {
  170. if (RegSetValueEx(key, NSSM_REG_ENV, 0, REG_MULTI_SZ, (const unsigned char *) service->env, (unsigned long) service->envlen * sizeof(TCHAR)) != ERROR_SUCCESS) {
  171. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_ENV, error_string(GetLastError()), 0);
  172. }
  173. }
  174. else if (editing) RegDeleteValue(key, NSSM_REG_ENV);
  175. if (service->env_extra) {
  176. if (RegSetValueEx(key, NSSM_REG_ENV_EXTRA, 0, REG_MULTI_SZ, (const unsigned char *) service->env_extra, (unsigned long) service->env_extralen * sizeof(TCHAR)) != ERROR_SUCCESS) {
  177. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_ENV_EXTRA, error_string(GetLastError()), 0);
  178. }
  179. }
  180. else if (editing) RegDeleteValue(key, NSSM_REG_ENV_EXTRA);
  181. /* Close registry. */
  182. RegCloseKey(key);
  183. return 0;
  184. }
  185. int create_exit_action(TCHAR *service_name, const TCHAR *action_string, bool editing) {
  186. /* Get registry */
  187. TCHAR registry[KEY_LENGTH];
  188. if (service_registry_path(service_name, true, NSSM_REG_EXIT, registry, _countof(registry)) < 0) {
  189. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("NSSM_REG_EXIT"), _T("create_exit_action()"), 0);
  190. return 1;
  191. }
  192. /* Try to open the registry */
  193. HKEY key;
  194. unsigned long disposition;
  195. if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, registry, 0, 0, REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &key, &disposition) != ERROR_SUCCESS) {
  196. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OPENKEY_FAILED, registry, error_string(GetLastError()), 0);
  197. return 2;
  198. }
  199. /* Do nothing if the key already existed */
  200. if (disposition == REG_OPENED_EXISTING_KEY && ! editing) {
  201. RegCloseKey(key);
  202. return 0;
  203. }
  204. /* Create the default value */
  205. if (RegSetValueEx(key, 0, 0, REG_SZ, (const unsigned char *) action_string, (unsigned long) (_tcslen(action_string) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) {
  206. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, NSSM_REG_EXIT, error_string(GetLastError()), 0);
  207. RegCloseKey(key);
  208. return 3;
  209. }
  210. /* Close registry */
  211. RegCloseKey(key);
  212. return 0;
  213. }
  214. int get_environment(TCHAR *service_name, HKEY key, TCHAR *value, TCHAR **env, unsigned long *envlen) {
  215. unsigned long type = REG_MULTI_SZ;
  216. unsigned long envsize;
  217. *envlen = 0;
  218. /* Dummy test to find buffer size */
  219. unsigned long ret = RegQueryValueEx(key, value, 0, &type, NULL, &envsize);
  220. if (ret != ERROR_SUCCESS) {
  221. *env = 0;
  222. /* The service probably doesn't have any environment configured */
  223. if (ret == ERROR_FILE_NOT_FOUND) return 0;
  224. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, value, error_string(ret), 0);
  225. return 1;
  226. }
  227. if (type != REG_MULTI_SZ) {
  228. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_INVALID_ENVIRONMENT_STRING_TYPE, value, service_name, 0);
  229. *env = 0;
  230. return 2;
  231. }
  232. /* Minimum usable environment would be A= NULL NULL. */
  233. if (envsize < 4 * sizeof(TCHAR)) {
  234. *env = 0;
  235. return 3;
  236. }
  237. /* Previously initialised? */
  238. if (*env) HeapFree(GetProcessHeap(), 0, *env);
  239. *env = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, envsize);
  240. if (! *env) {
  241. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, value, _T("get_environment()"), 0);
  242. return 4;
  243. }
  244. /* Actually get the strings. */
  245. ret = RegQueryValueEx(key, value, 0, &type, (unsigned char *) *env, &envsize);
  246. if (ret != ERROR_SUCCESS) {
  247. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, value, error_string(ret), 0);
  248. HeapFree(GetProcessHeap(), 0, *env);
  249. *env = 0;
  250. return 5;
  251. }
  252. /* Value retrieved by RegQueryValueEx() is SIZE not COUNT. */
  253. *envlen = (unsigned long) environment_length(*env);
  254. return 0;
  255. }
  256. int get_string(HKEY key, TCHAR *value, TCHAR *data, unsigned long datalen, bool expand, bool sanitise, bool must_exist) {
  257. TCHAR *buffer = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, datalen);
  258. if (! buffer) {
  259. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, value, _T("get_string()"), 0);
  260. return 1;
  261. }
  262. ZeroMemory(data, datalen);
  263. unsigned long type = REG_EXPAND_SZ;
  264. unsigned long buflen = datalen;
  265. unsigned long ret = RegQueryValueEx(key, value, 0, &type, (unsigned char *) buffer, &buflen);
  266. if (ret != ERROR_SUCCESS) {
  267. HeapFree(GetProcessHeap(), 0, buffer);
  268. if (ret == ERROR_FILE_NOT_FOUND) {
  269. if (! must_exist) return 0;
  270. }
  271. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, value, error_string(ret), 0);
  272. return 2;
  273. }
  274. /* Paths aren't allowed to contain quotes. */
  275. if (sanitise) PathUnquoteSpaces(buffer);
  276. /* Do we want to expand the string? */
  277. if (! expand) {
  278. if (type == REG_EXPAND_SZ) type = REG_SZ;
  279. }
  280. /* Technically we shouldn't expand environment strings from REG_SZ values */
  281. if (type != REG_EXPAND_SZ) {
  282. memmove(data, buffer, buflen);
  283. HeapFree(GetProcessHeap(), 0, buffer);
  284. return 0;
  285. }
  286. ret = ExpandEnvironmentStrings((TCHAR *) buffer, data, datalen);
  287. if (! ret || ret > datalen) {
  288. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_EXPANDENVIRONMENTSTRINGS_FAILED, buffer, error_string(GetLastError()), 0);
  289. HeapFree(GetProcessHeap(), 0, buffer);
  290. return 3;
  291. }
  292. HeapFree(GetProcessHeap(), 0, buffer);
  293. return 0;
  294. }
  295. int get_string(HKEY key, TCHAR *value, TCHAR *data, unsigned long datalen, bool sanitise) {
  296. return get_string(key, value, data, datalen, false, sanitise, true);
  297. }
  298. int expand_parameter(HKEY key, TCHAR *value, TCHAR *data, unsigned long datalen, bool sanitise, bool must_exist) {
  299. return get_string(key, value, data, datalen, true, sanitise, must_exist);
  300. }
  301. int expand_parameter(HKEY key, TCHAR *value, TCHAR *data, unsigned long datalen, bool sanitise) {
  302. return expand_parameter(key, value, data, datalen, sanitise, true);
  303. }
  304. /*
  305. Sets a string in the registry.
  306. Returns: 0 if it was set.
  307. 1 on error.
  308. */
  309. int set_string(HKEY key, TCHAR *value, TCHAR *string, bool expand) {
  310. unsigned long type = expand ? REG_EXPAND_SZ : REG_SZ;
  311. if (RegSetValueEx(key, value, 0, type, (const unsigned char *) string, (unsigned long) (_tcslen(string) + 1) * sizeof(TCHAR)) == ERROR_SUCCESS) return 0;
  312. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, value, error_string(GetLastError()), 0);
  313. return 1;
  314. }
  315. int set_string(HKEY key, TCHAR *value, TCHAR *string) {
  316. return set_string(key, value, string, false);
  317. }
  318. int set_expand_string(HKEY key, TCHAR *value, TCHAR *string) {
  319. return set_string(key, value, string, true);
  320. }
  321. /*
  322. Set an unsigned long in the registry.
  323. Returns: 0 if it was set.
  324. 1 on error.
  325. */
  326. int set_number(HKEY key, TCHAR *value, unsigned long number) {
  327. if (RegSetValueEx(key, value, 0, REG_DWORD, (const unsigned char *) &number, sizeof(number)) == ERROR_SUCCESS) return 0;
  328. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_SETVALUE_FAILED, value, error_string(GetLastError()), 0);
  329. return 1;
  330. }
  331. /*
  332. Query an unsigned long from the registry.
  333. Returns: 1 if a number was retrieved.
  334. 0 if none was found and must_exist is false.
  335. -1 if none was found and must_exist is true.
  336. -2 otherwise.
  337. */
  338. int get_number(HKEY key, TCHAR *value, unsigned long *number, bool must_exist) {
  339. unsigned long type = REG_DWORD;
  340. unsigned long number_len = sizeof(unsigned long);
  341. int ret = RegQueryValueEx(key, value, 0, &type, (unsigned char *) number, &number_len);
  342. if (ret == ERROR_SUCCESS) return 1;
  343. if (ret == ERROR_FILE_NOT_FOUND) {
  344. if (! must_exist) return 0;
  345. }
  346. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, value, error_string(ret), 0);
  347. if (ret == ERROR_FILE_NOT_FOUND) return -1;
  348. return -2;
  349. }
  350. int get_number(HKEY key, TCHAR *value, unsigned long *number) {
  351. return get_number(key, value, number, true);
  352. }
  353. /* Replace NULL with CRLF. Leave NULL NULL as the end marker. */
  354. int format_double_null(TCHAR *dn, unsigned long dnlen, TCHAR **formatted, unsigned long *newlen) {
  355. unsigned long i, j;
  356. *newlen = dnlen;
  357. if (! *newlen) {
  358. *formatted = 0;
  359. return 0;
  360. }
  361. for (i = 0; i < dnlen; i++) if (! dn[i] && dn[i + 1]) ++*newlen;
  362. *formatted = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *newlen * sizeof(TCHAR));
  363. if (! *formatted) {
  364. *newlen = 0;
  365. return 1;
  366. }
  367. for (i = 0, j = 0; i < dnlen; i++) {
  368. (*formatted)[j] = dn[i];
  369. if (! dn[i]) {
  370. if (dn[i + 1]) {
  371. (*formatted)[j] = _T('\r');
  372. (*formatted)[++j] = _T('\n');
  373. }
  374. }
  375. j++;
  376. }
  377. return 0;
  378. }
  379. /* Strip CR and replace LF with NULL. */
  380. int unformat_double_null(TCHAR *formatted, unsigned long formattedlen, TCHAR **dn, unsigned long *newlen) {
  381. unsigned long i, j;
  382. *newlen = 0;
  383. /* Don't count trailing NULLs. */
  384. for (i = 0; i < formattedlen; i++) {
  385. if (! formatted[i]) {
  386. formattedlen = i;
  387. break;
  388. }
  389. }
  390. if (! formattedlen) {
  391. *dn = 0;
  392. return 0;
  393. }
  394. for (i = 0; i < formattedlen; i++) if (formatted[i] != _T('\r')) ++*newlen;
  395. /* Skip blank lines. */
  396. for (i = 0; i < formattedlen; i++) {
  397. if (formatted[i] == _T('\r') && formatted[i + 1] == _T('\n')) {
  398. /* This is the last CRLF. */
  399. if (i >= formattedlen - 2) break;
  400. /*
  401. Strip at the start of the block or if the next characters are
  402. CRLF too.
  403. */
  404. if (! i || (formatted[i + 2] == _T('\r') && formatted[i + 3] == _T('\n'))) {
  405. for (j = i + 2; j < formattedlen; j++) formatted[j - 2] = formatted[j];
  406. formatted[formattedlen--] = _T('\0');
  407. formatted[formattedlen--] = _T('\0');
  408. i--;
  409. --*newlen;
  410. }
  411. }
  412. }
  413. /* Must end with two NULLs. */
  414. *newlen += 2;
  415. *dn = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, *newlen * sizeof(TCHAR));
  416. if (! *dn) return 1;
  417. for (i = 0, j = 0; i < formattedlen; i++) {
  418. if (formatted[i] == _T('\r')) continue;
  419. if (formatted[i] == _T('\n')) (*dn)[j] = _T('\0');
  420. else (*dn)[j] = formatted[i];
  421. j++;
  422. }
  423. return 0;
  424. }
  425. /* Copy a block. */
  426. int copy_double_null(TCHAR *dn, unsigned long dnlen, TCHAR **newdn) {
  427. if (! newdn) return 1;
  428. *newdn = 0;
  429. if (! dn) return 0;
  430. *newdn = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, dnlen * sizeof(TCHAR));
  431. if (! *newdn) {
  432. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("dn"), _T("copy_double_null()"), 0);
  433. return 2;
  434. }
  435. memmove(*newdn, dn, dnlen * sizeof(TCHAR));
  436. return 0;
  437. }
  438. /*
  439. Create a new block with all the strings of the first block plus a new string.
  440. The new string may be specified as <key> <delimiter> <value> and the keylen
  441. gives the offset into the string to compare against existing entries.
  442. If the key is already present its value will be overwritten in place.
  443. If the key is blank or empty the new block will still be allocated and have
  444. non-zero length.
  445. */
  446. int append_to_double_null(TCHAR *dn, unsigned long dnlen, TCHAR **newdn, unsigned long *newlen, TCHAR *append, size_t keylen, bool case_sensitive) {
  447. if (! append || ! append[0]) return copy_double_null(dn, dnlen, newdn);
  448. size_t appendlen = _tcslen(append);
  449. int (*fn)(const TCHAR *, const TCHAR *, size_t) = (case_sensitive) ? _tcsncmp : _tcsnicmp;
  450. /* Identify the key, if any, or treat the whole string as the key. */
  451. TCHAR *key = 0;
  452. if (! keylen || keylen > appendlen) keylen = appendlen;
  453. key = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (keylen + 1) * sizeof(TCHAR));
  454. if (! key) {
  455. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("key"), _T("append_to_double_null()"), 0);
  456. return 1;
  457. }
  458. memmove(key, append, keylen * sizeof(TCHAR));
  459. key[keylen] = _T('\0');
  460. /* Find the length of the block not including any existing key. */
  461. size_t len = 0;
  462. TCHAR *s;
  463. for (s = dn; *s; s++) {
  464. if (fn(s, key, keylen)) len += _tcslen(s) + 1;
  465. for ( ; *s; s++);
  466. }
  467. /* Account for new entry. */
  468. len += _tcslen(append) + 1;
  469. /* Account for trailing NULL. */
  470. len++;
  471. /* Allocate a new block. */
  472. *newdn = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR));
  473. if (! *newdn) {
  474. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("newdn"), _T("append_to_double_null()"), 0);
  475. HeapFree(GetProcessHeap(), 0, key);
  476. return 2;
  477. }
  478. /* Copy existing entries.*/
  479. *newlen = (unsigned long) len;
  480. TCHAR *t = *newdn;
  481. TCHAR *u;
  482. bool replaced = false;
  483. for (s = dn; *s; s++) {
  484. if (fn(s, key, keylen)) u = s;
  485. else {
  486. u = append;
  487. replaced = true;
  488. }
  489. len = _tcslen(u) + 1;
  490. memmove(t, u, len * sizeof(TCHAR));
  491. t += len;
  492. for ( ; *s; s++);
  493. }
  494. /* Add the entry if it wasn't already replaced. The buffer was zeroed. */
  495. if (! replaced) memmove(t, append, _tcslen(append) * sizeof(TCHAR));
  496. HeapFree(GetProcessHeap(), 0, key);
  497. return 0;
  498. }
  499. /*
  500. Create a new block with all the string of the first block minus the given
  501. string.
  502. The keylen parameter gives the offset into the string to compare against
  503. existing entries. If a substring of existing value matches the string to
  504. the given length it will be removed.
  505. If the last entry is removed the new block will still be allocated and
  506. have non-zero length.
  507. */
  508. int remove_from_double_null(TCHAR *dn, unsigned long dnlen, TCHAR **newdn, unsigned long *newlen, TCHAR *remove, size_t keylen, bool case_sensitive) {
  509. if (! remove || !remove[0]) return copy_double_null(dn, dnlen, newdn);
  510. size_t removelen = _tcslen(remove);
  511. int (*fn)(const TCHAR *, const TCHAR *, size_t) = (case_sensitive) ? _tcsncmp : _tcsnicmp;
  512. /* Identify the key, if any, or treat the whole string as the key. */
  513. TCHAR *key = 0;
  514. if (! keylen || keylen > removelen) keylen = removelen;
  515. key = (TCHAR *) HeapAlloc(GetProcessHeap(), 0, (keylen + 1) * sizeof(TCHAR));
  516. if (! key) {
  517. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("key"), _T("remove_from_double_null()"), 0);
  518. return 1;
  519. }
  520. memmove(key, remove, keylen * sizeof(TCHAR));
  521. key[keylen] = _T('\0');
  522. /* Find the length of the block not including any existing key. */
  523. size_t len = 0;
  524. TCHAR *s;
  525. for (s = dn; *s; s++) {
  526. if (fn(s, key, keylen)) len += _tcslen(s) + 1;
  527. for ( ; *s; s++);
  528. }
  529. /* Account for trailing NULL. */
  530. if (++len < 2) len = 2;
  531. /* Allocate a new block. */
  532. *newdn = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof(TCHAR));
  533. if (! *newdn) {
  534. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("newdn"), _T("remove_from_double_null()"), 0);
  535. HeapFree(GetProcessHeap(), 0, key);
  536. return 2;
  537. }
  538. /* Copy existing entries.*/
  539. *newlen = (unsigned long) len;
  540. TCHAR *t = *newdn;
  541. for (s = dn; *s; s++) {
  542. if (fn(s, key, keylen)) {
  543. len = _tcslen(s) + 1;
  544. memmove(t, s, len * sizeof(TCHAR));
  545. t += len;
  546. }
  547. for ( ; *s; s++);
  548. }
  549. HeapFree(GetProcessHeap(), 0, key);
  550. return 0;
  551. }
  552. void override_milliseconds(TCHAR *service_name, HKEY key, TCHAR *value, unsigned long *buffer, unsigned long default_value, unsigned long event) {
  553. unsigned long type = REG_DWORD;
  554. unsigned long buflen = sizeof(unsigned long);
  555. bool ok = false;
  556. unsigned long ret = RegQueryValueEx(key, value, 0, &type, (unsigned char *) buffer, &buflen);
  557. if (ret != ERROR_SUCCESS) {
  558. if (ret != ERROR_FILE_NOT_FOUND) {
  559. if (type != REG_DWORD) {
  560. TCHAR milliseconds[16];
  561. _sntprintf_s(milliseconds, _countof(milliseconds), _TRUNCATE, _T("%lu"), default_value);
  562. log_event(EVENTLOG_WARNING_TYPE, event, service_name, value, milliseconds, 0);
  563. }
  564. else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, value, error_string(ret), 0);
  565. }
  566. }
  567. else ok = true;
  568. if (! ok) *buffer = default_value;
  569. }
  570. /* Open the key of the service itself Services\<service_name>. */
  571. HKEY open_service_registry(const TCHAR *service_name, REGSAM sam, bool must_exist) {
  572. /* Get registry */
  573. TCHAR registry[KEY_LENGTH];
  574. if (service_registry_path(service_name, false, 0, registry, _countof(registry)) < 0) {
  575. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REGISTRY, _T("open_service_registry()"), 0);
  576. return 0;
  577. }
  578. return open_registry_key(registry, sam, must_exist);
  579. }
  580. /* Open a subkey of the service Services\<service_name>\<sub>. */
  581. long open_registry(const TCHAR *service_name, const TCHAR *sub, REGSAM sam, HKEY *key, bool must_exist) {
  582. /* Get registry */
  583. TCHAR registry[KEY_LENGTH];
  584. if (service_registry_path(service_name, true, sub, registry, _countof(registry)) < 0) {
  585. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REGISTRY, _T("open_registry()"), 0);
  586. return 0;
  587. }
  588. return open_registry_key(registry, sam, key, must_exist);
  589. }
  590. HKEY open_registry(const TCHAR *service_name, const TCHAR *sub, REGSAM sam, bool must_exist) {
  591. HKEY key;
  592. long error = open_registry(service_name, sub, sam, &key, must_exist);
  593. return key;
  594. }
  595. HKEY open_registry(const TCHAR *service_name, const TCHAR *sub, REGSAM sam) {
  596. return open_registry(service_name, sub, sam, true);
  597. }
  598. HKEY open_registry(const TCHAR *service_name, REGSAM sam) {
  599. return open_registry(service_name, 0, sam, true);
  600. }
  601. int get_io_parameters(nssm_service_t *service, HKEY key) {
  602. /* stdin */
  603. if (get_createfile_parameters(key, NSSM_REG_STDIN, service->stdin_path, &service->stdin_sharing, NSSM_STDIN_SHARING, &service->stdin_disposition, NSSM_STDIN_DISPOSITION, &service->stdin_flags, NSSM_STDIN_FLAGS, 0)) {
  604. service->stdin_sharing = service->stdin_disposition = service->stdin_flags = 0;
  605. ZeroMemory(service->stdin_path, _countof(service->stdin_path) * sizeof(TCHAR));
  606. return 1;
  607. }
  608. /* stdout */
  609. if (get_createfile_parameters(key, NSSM_REG_STDOUT, service->stdout_path, &service->stdout_sharing, NSSM_STDOUT_SHARING, &service->stdout_disposition, NSSM_STDOUT_DISPOSITION, &service->stdout_flags, NSSM_STDOUT_FLAGS, &service->stdout_copy_and_truncate)) {
  610. service->stdout_sharing = service->stdout_disposition = service->stdout_flags = 0;
  611. ZeroMemory(service->stdout_path, _countof(service->stdout_path) * sizeof(TCHAR));
  612. return 2;
  613. }
  614. /* stderr */
  615. if (get_createfile_parameters(key, NSSM_REG_STDERR, service->stderr_path, &service->stderr_sharing, NSSM_STDERR_SHARING, &service->stderr_disposition, NSSM_STDERR_DISPOSITION, &service->stderr_flags, NSSM_STDERR_FLAGS, &service->stderr_copy_and_truncate)) {
  616. service->stderr_sharing = service->stderr_disposition = service->stderr_flags = 0;
  617. ZeroMemory(service->stderr_path, _countof(service->stderr_path) * sizeof(TCHAR));
  618. return 3;
  619. }
  620. return 0;
  621. }
  622. int get_parameters(nssm_service_t *service, STARTUPINFO *si) {
  623. unsigned long ret;
  624. /* Try to open the registry */
  625. HKEY key = open_registry(service->name, KEY_READ);
  626. if (! key) return 1;
  627. /* Don't expand parameters when retrieving for the GUI. */
  628. bool expand = si ? true : false;
  629. /* Try to get environment variables - may fail */
  630. get_environment(service->name, key, NSSM_REG_ENV, &service->env, &service->envlen);
  631. /* Environment variables to add to existing rather than replace - may fail. */
  632. get_environment(service->name, key, NSSM_REG_ENV_EXTRA, &service->env_extra, &service->env_extralen);
  633. /* Set environment if we are starting the service. */
  634. if (si) set_service_environment(service);
  635. /* Try to get executable file - MUST succeed */
  636. if (get_string(key, NSSM_REG_EXE, service->exe, sizeof(service->exe), expand, false, true)) {
  637. RegCloseKey(key);
  638. return 3;
  639. }
  640. /* Try to get flags - may fail and we don't care */
  641. if (get_string(key, NSSM_REG_FLAGS, service->flags, sizeof(service->flags), expand, false, true)) {
  642. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_NO_FLAGS, NSSM_REG_FLAGS, service->name, service->exe, 0);
  643. ZeroMemory(service->flags, sizeof(service->flags));
  644. }
  645. /* Try to get startup directory - may fail and we fall back to a default */
  646. if (get_string(key, NSSM_REG_DIR, service->dir, sizeof(service->dir), expand, true, true) || ! service->dir[0]) {
  647. _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
  648. strip_basename(service->dir);
  649. if (service->dir[0] == _T('\0')) {
  650. /* Help! */
  651. ret = GetWindowsDirectory(service->dir, sizeof(service->dir));
  652. if (! ret || ret > sizeof(service->dir)) {
  653. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_NO_DIR_AND_NO_FALLBACK, NSSM_REG_DIR, service->name, 0);
  654. RegCloseKey(key);
  655. return 4;
  656. }
  657. }
  658. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_NO_DIR, NSSM_REG_DIR, service->name, service->dir, 0);
  659. }
  660. /* Try to get processor affinity - may fail. */
  661. TCHAR buffer[512];
  662. if (get_string(key, NSSM_REG_AFFINITY, buffer, sizeof(buffer), false, false, false) || ! buffer[0]) service->affinity = 0LL;
  663. else if (affinity_string_to_mask(buffer, &service->affinity)) {
  664. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_AFFINITY_MASK, service->name, buffer);
  665. service->affinity = 0LL;
  666. }
  667. else {
  668. DWORD_PTR affinity, system_affinity;
  669. if (GetProcessAffinityMask(GetCurrentProcess(), &affinity, &system_affinity)) {
  670. _int64 effective_affinity = service->affinity & system_affinity;
  671. if (effective_affinity != service->affinity) {
  672. TCHAR *system = 0;
  673. if (! affinity_mask_to_string(system_affinity, &system)) {
  674. TCHAR *effective = 0;
  675. if (! affinity_mask_to_string(effective_affinity, &effective)) {
  676. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_EFFECTIVE_AFFINITY_MASK, service->name, buffer, system, effective, 0);
  677. }
  678. HeapFree(GetProcessHeap(), 0, effective);
  679. }
  680. HeapFree(GetProcessHeap(), 0, system);
  681. }
  682. }
  683. }
  684. /* Try to get priority - may fail. */
  685. unsigned long priority;
  686. if (get_number(key, NSSM_REG_PRIORITY, &priority, false) == 1) {
  687. if (priority == (priority & priority_mask())) service->priority = priority;
  688. else log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_PRIORITY, service->name, NSSM_REG_PRIORITY, 0);
  689. }
  690. /* Try to get hook I/O sharing - may fail. */
  691. unsigned long hook_share_output_handles;
  692. if (get_number(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES, &hook_share_output_handles, false) == 1) {
  693. if (hook_share_output_handles) service->hook_share_output_handles = true;
  694. else service->hook_share_output_handles = false;
  695. }
  696. else hook_share_output_handles = false;
  697. /* Try to get file rotation settings - may fail. */
  698. unsigned long rotate_files;
  699. if (get_number(key, NSSM_REG_ROTATE, &rotate_files, false) == 1) {
  700. if (rotate_files) service->rotate_files = true;
  701. else service->rotate_files = false;
  702. }
  703. else service->rotate_files = false;
  704. if (get_number(key, NSSM_REG_ROTATE_ONLINE, &rotate_files, false) == 1) {
  705. if (rotate_files) service->rotate_stdout_online = service->rotate_stderr_online = true;
  706. else service->rotate_stdout_online = service->rotate_stderr_online = false;
  707. }
  708. else service->rotate_stdout_online = service->rotate_stderr_online = false;
  709. /* Log timestamping requires a logging thread.*/
  710. unsigned long timestamp_log;
  711. if (get_number(key, NSSM_REG_TIMESTAMP_LOG, &timestamp_log, false) == 1) {
  712. if (timestamp_log) service->timestamp_log = true;
  713. else service->timestamp_log = false;
  714. }
  715. else service->timestamp_log = false;
  716. /* Hook I/O sharing and online rotation need a pipe. */
  717. service->use_stdout_pipe = service->rotate_stdout_online || service->timestamp_log || hook_share_output_handles;
  718. service->use_stderr_pipe = service->rotate_stderr_online || service->timestamp_log || hook_share_output_handles;
  719. if (get_number(key, NSSM_REG_ROTATE_SECONDS, &service->rotate_seconds, false) != 1) service->rotate_seconds = 0;
  720. if (get_number(key, NSSM_REG_ROTATE_BYTES_LOW, &service->rotate_bytes_low, false) != 1) service->rotate_bytes_low = 0;
  721. if (get_number(key, NSSM_REG_ROTATE_BYTES_HIGH, &service->rotate_bytes_high, false) != 1) service->rotate_bytes_high = 0;
  722. override_milliseconds(service->name, key, NSSM_REG_ROTATE_DELAY, &service->rotate_delay, NSSM_ROTATE_DELAY, NSSM_EVENT_BOGUS_THROTTLE);
  723. /* Try to get force new console setting - may fail. */
  724. if (get_number(key, NSSM_REG_NO_CONSOLE, &service->no_console, false) != 1) service->no_console = 0;
  725. /* Change to startup directory in case stdout/stderr are relative paths. */
  726. TCHAR cwd[PATH_LENGTH];
  727. GetCurrentDirectory(_countof(cwd), cwd);
  728. SetCurrentDirectory(service->dir);
  729. /* Try to get stdout and stderr */
  730. if (get_io_parameters(service, key)) {
  731. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_OUTPUT_HANDLES_FAILED, service->name, 0);
  732. RegCloseKey(key);
  733. SetCurrentDirectory(cwd);
  734. return 5;
  735. }
  736. /* Change back in case the startup directory needs to be deleted. */
  737. SetCurrentDirectory(cwd);
  738. /* Try to get mandatory restart delay */
  739. override_milliseconds(service->name, key, NSSM_REG_RESTART_DELAY, &service->restart_delay, 0, NSSM_EVENT_BOGUS_RESTART_DELAY);
  740. /* Try to get throttle restart delay */
  741. override_milliseconds(service->name, key, NSSM_REG_THROTTLE, &service->throttle_delay, NSSM_RESET_THROTTLE_RESTART, NSSM_EVENT_BOGUS_THROTTLE);
  742. /* Try to get service stop flags. */
  743. unsigned long type = REG_DWORD;
  744. unsigned long stop_method_skip;
  745. unsigned long buflen = sizeof(stop_method_skip);
  746. bool stop_ok = false;
  747. ret = RegQueryValueEx(key, NSSM_REG_STOP_METHOD_SKIP, 0, &type, (unsigned char *) &stop_method_skip, &buflen);
  748. if (ret != ERROR_SUCCESS) {
  749. if (ret != ERROR_FILE_NOT_FOUND) {
  750. if (type != REG_DWORD) {
  751. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_STOP_METHOD_SKIP, service->name, NSSM_REG_STOP_METHOD_SKIP, NSSM, 0);
  752. }
  753. else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, NSSM_REG_STOP_METHOD_SKIP, error_string(ret), 0);
  754. }
  755. }
  756. else stop_ok = true;
  757. /* Try all methods except those requested to be skipped. */
  758. service->stop_method = ~0;
  759. if (stop_ok) service->stop_method &= ~stop_method_skip;
  760. /* Try to get kill delays - may fail. */
  761. override_milliseconds(service->name, key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD, &service->kill_console_delay, NSSM_KILL_CONSOLE_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_CONSOLE_GRACE_PERIOD);
  762. override_milliseconds(service->name, key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD, &service->kill_window_delay, NSSM_KILL_WINDOW_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_WINDOW_GRACE_PERIOD);
  763. override_milliseconds(service->name, key, NSSM_REG_KILL_THREADS_GRACE_PERIOD, &service->kill_threads_delay, NSSM_KILL_THREADS_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_THREADS_GRACE_PERIOD);
  764. /* Try to get process tree settings - may fail. */
  765. unsigned long kill_process_tree;
  766. if (get_number(key, NSSM_REG_KILL_PROCESS_TREE, &kill_process_tree, false) == 1) {
  767. if (kill_process_tree) service->kill_process_tree = true;
  768. else service->kill_process_tree = false;
  769. }
  770. else service->kill_process_tree = true;
  771. /* Try to get default exit action. */
  772. bool default_action;
  773. service->default_exit_action = NSSM_EXIT_RESTART;
  774. TCHAR action_string[ACTION_LEN];
  775. if (! get_exit_action(service->name, 0, action_string, &default_action)) {
  776. for (int i = 0; exit_action_strings[i]; i++) {
  777. if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
  778. service->default_exit_action = i;
  779. break;
  780. }
  781. }
  782. }
  783. /* Close registry */
  784. RegCloseKey(key);
  785. return 0;
  786. }
  787. /*
  788. Sets the string for the exit action corresponding to the exit code.
  789. ret is a pointer to an unsigned long containing the exit code.
  790. If ret is NULL, we retrieve the default exit action unconditionally.
  791. action is a buffer which receives the string.
  792. default_action is a pointer to a bool which is set to false if there
  793. was an explicit string for the given exit code, or true if we are
  794. returning the default action.
  795. Returns: 0 on success.
  796. 1 on error.
  797. */
  798. int get_exit_action(const TCHAR *service_name, unsigned long *ret, TCHAR *action, bool *default_action) {
  799. /* Are we returning the default action or a status-specific one? */
  800. *default_action = ! ret;
  801. /* Try to open the registry */
  802. HKEY key = open_registry(service_name, NSSM_REG_EXIT, KEY_READ);
  803. if (! key) return 1;
  804. unsigned long type = REG_SZ;
  805. unsigned long action_len = ACTION_LEN;
  806. TCHAR code[16];
  807. if (! ret) code[0] = _T('\0');
  808. else if (_sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), *ret) < 0) {
  809. RegCloseKey(key);
  810. return get_exit_action(service_name, 0, action, default_action);
  811. }
  812. if (RegQueryValueEx(key, code, 0, &type, (unsigned char *) action, &action_len) != ERROR_SUCCESS) {
  813. RegCloseKey(key);
  814. /* Try again with * as the key if an exit code was defined */
  815. if (ret) return get_exit_action(service_name, 0, action, default_action);
  816. return 0;
  817. }
  818. /* Close registry */
  819. RegCloseKey(key);
  820. return 0;
  821. }
  822. int set_hook(const TCHAR *service_name, const TCHAR *hook_event, const TCHAR *hook_action, TCHAR *cmd) {
  823. /* Try to open the registry */
  824. TCHAR registry[KEY_LENGTH];
  825. if (_sntprintf_s(registry, _countof(registry), _TRUNCATE, _T("%s\\%s"), NSSM_REG_HOOK, hook_event) < 0) {
  826. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook registry"), _T("set_hook()"), 0);
  827. return 1;
  828. }
  829. HKEY key;
  830. long error;
  831. /* Don't create keys needlessly. */
  832. if (! _tcslen(cmd)) {
  833. key = open_registry(service_name, registry, KEY_READ, false);
  834. if (! key) return 0;
  835. error = RegQueryValueEx(key, hook_action, 0, 0, 0, 0);
  836. RegCloseKey(key);
  837. if (error == ERROR_FILE_NOT_FOUND) return 0;
  838. }
  839. key = open_registry(service_name, registry, KEY_WRITE);
  840. if (! key) return 1;
  841. int ret = 1;
  842. if (_tcslen(cmd)) ret = set_string(key, (TCHAR *) hook_action, cmd, true);
  843. else {
  844. error = RegDeleteValue(key, hook_action);
  845. if (error == ERROR_SUCCESS || error == ERROR_FILE_NOT_FOUND) ret = 0;
  846. }
  847. /* Close registry */
  848. RegCloseKey(key);
  849. return ret;
  850. }
  851. int get_hook(const TCHAR *service_name, const TCHAR *hook_event, const TCHAR *hook_action, TCHAR *buffer, unsigned long buflen) {
  852. /* Try to open the registry */
  853. TCHAR registry[KEY_LENGTH];
  854. if (_sntprintf_s(registry, _countof(registry), _TRUNCATE, _T("%s\\%s"), NSSM_REG_HOOK, hook_event) < 0) {
  855. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook registry"), _T("get_hook()"), 0);
  856. return 1;
  857. }
  858. HKEY key;
  859. long error = open_registry(service_name, registry, KEY_READ, &key, false);
  860. if (! key) {
  861. if (error == ERROR_FILE_NOT_FOUND) {
  862. ZeroMemory(buffer, buflen);
  863. return 0;
  864. }
  865. return 1;
  866. }
  867. int ret = expand_parameter(key, (TCHAR *) hook_action, buffer, buflen, true, false);
  868. /* Close registry */
  869. RegCloseKey(key);
  870. return ret;
  871. }