io.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. #include "nssm.h"
  2. #define COMPLAINED_READ (1 << 0)
  3. #define COMPLAINED_WRITE (1 << 1)
  4. #define COMPLAINED_ROTATE (1 << 2)
  5. static int dup_handle(HANDLE source_handle, HANDLE *dest_handle_ptr, TCHAR *source_description, TCHAR *dest_description, unsigned long flags) {
  6. if (! dest_handle_ptr) return 1;
  7. if (! DuplicateHandle(GetCurrentProcess(), source_handle, GetCurrentProcess(), dest_handle_ptr, 0, true, flags)) {
  8. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_DUPLICATEHANDLE_FAILED, source_description, dest_description, error_string(GetLastError()), 0);
  9. return 2;
  10. }
  11. return 0;
  12. }
  13. static int dup_handle(HANDLE source_handle, HANDLE *dest_handle_ptr, TCHAR *source_description, TCHAR *dest_description) {
  14. return dup_handle(source_handle, dest_handle_ptr, source_description, dest_description, DUPLICATE_SAME_ACCESS);
  15. }
  16. /*
  17. read_handle: read from application
  18. pipe_handle: stdout of application
  19. write_handle: to file
  20. */
  21. static HANDLE create_logging_thread(TCHAR *service_name, TCHAR *path, unsigned long sharing, unsigned long disposition, unsigned long flags, HANDLE *read_handle_ptr, HANDLE *pipe_handle_ptr, HANDLE *write_handle_ptr, unsigned long rotate_bytes_low, unsigned long rotate_bytes_high, unsigned long rotate_delay, unsigned long *tid_ptr, unsigned long *rotate_online, bool copy_and_truncate) {
  22. *tid_ptr = 0;
  23. /* Pipe between application's stdout/stderr and our logging handle. */
  24. if (read_handle_ptr && ! *read_handle_ptr) {
  25. if (pipe_handle_ptr && ! *pipe_handle_ptr) {
  26. if (CreatePipe(read_handle_ptr, pipe_handle_ptr, 0, 0)) {
  27. SetHandleInformation(*pipe_handle_ptr, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
  28. }
  29. else {
  30. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEPIPE_FAILED, service_name, path, error_string(GetLastError()));
  31. return (HANDLE) 0;
  32. }
  33. }
  34. }
  35. logger_t *logger = (logger_t *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(logger_t));
  36. if (! logger) {
  37. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("logger"), _T("create_logging_thread()"), 0);
  38. return (HANDLE) 0;
  39. }
  40. ULARGE_INTEGER size;
  41. size.LowPart = rotate_bytes_low;
  42. size.HighPart = rotate_bytes_high;
  43. logger->service_name = service_name;
  44. logger->path = path;
  45. logger->sharing = sharing;
  46. logger->disposition = disposition;
  47. logger->flags = flags;
  48. logger->read_handle = *read_handle_ptr;
  49. logger->write_handle = *write_handle_ptr;
  50. logger->size = (__int64) size.QuadPart;
  51. logger->tid_ptr = tid_ptr;
  52. logger->rotate_online = rotate_online;
  53. logger->rotate_delay = rotate_delay;
  54. logger->copy_and_truncate = copy_and_truncate;
  55. HANDLE thread_handle = CreateThread(NULL, 0, log_and_rotate, (void *) logger, 0, logger->tid_ptr);
  56. if (! thread_handle) {
  57. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATETHREAD_FAILED, error_string(GetLastError()), 0);
  58. HeapFree(GetProcessHeap(), 0, logger);
  59. }
  60. return thread_handle;
  61. }
  62. static inline unsigned long guess_charsize(void *address, unsigned long bufsize) {
  63. if (IsTextUnicode(address, bufsize, 0)) return (unsigned long) sizeof(wchar_t);
  64. else return (unsigned long) sizeof(char);
  65. }
  66. static inline void write_bom(logger_t *logger, unsigned long *out) {
  67. wchar_t bom = L'\ufeff';
  68. if (! WriteFile(logger->write_handle, (void *) &bom, sizeof(bom), out, 0)) {
  69. log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_SOMEBODY_SET_UP_US_THE_BOM, logger->service_name, logger->path, error_string(GetLastError()), 0);
  70. }
  71. }
  72. void close_handle(HANDLE *handle, HANDLE *remember) {
  73. if (remember) *remember = INVALID_HANDLE_VALUE;
  74. if (! handle) return;
  75. if (! *handle) return;
  76. CloseHandle(*handle);
  77. if (remember) *remember = *handle;
  78. *handle = 0;
  79. }
  80. void close_handle(HANDLE *handle) {
  81. close_handle(handle, NULL);
  82. }
  83. /* Get path, share mode, creation disposition and flags for a stream. */
  84. int get_createfile_parameters(HKEY key, TCHAR *prefix, TCHAR *path, unsigned long *sharing, unsigned long default_sharing, unsigned long *disposition, unsigned long default_disposition, unsigned long *flags, unsigned long default_flags, bool *copy_and_truncate) {
  85. TCHAR value[NSSM_STDIO_LENGTH];
  86. /* Path. */
  87. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s"), prefix) < 0) {
  88. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, prefix, _T("get_createfile_parameters()"), 0);
  89. return 1;
  90. }
  91. switch (expand_parameter(key, value, path, PATH_LENGTH, true, false)) {
  92. case 0: if (! path[0]) return 0; break; /* OK. */
  93. default: return 2; /* Error. */
  94. }
  95. /* ShareMode. */
  96. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, NSSM_REG_STDIO_SHARING) < 0) {
  97. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REG_STDIO_SHARING, _T("get_createfile_parameters()"), 0);
  98. return 3;
  99. }
  100. switch (get_number(key, value, sharing, false)) {
  101. case 0: *sharing = default_sharing; break; /* Missing. */
  102. case 1: break; /* Found. */
  103. case -2: return 4; /* Error. */
  104. }
  105. /* CreationDisposition. */
  106. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, NSSM_REG_STDIO_DISPOSITION) < 0) {
  107. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REG_STDIO_DISPOSITION, _T("get_createfile_parameters()"), 0);
  108. return 5;
  109. }
  110. switch (get_number(key, value, disposition, false)) {
  111. case 0: *disposition = default_disposition; break; /* Missing. */
  112. case 1: break; /* Found. */
  113. case -2: return 6; /* Error. */
  114. }
  115. /* Flags. */
  116. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, NSSM_REG_STDIO_FLAGS) < 0) {
  117. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REG_STDIO_FLAGS, _T("get_createfile_parameters()"), 0);
  118. return 7;
  119. }
  120. switch (get_number(key, value, flags, false)) {
  121. case 0: *flags = default_flags; break; /* Missing. */
  122. case 1: break; /* Found. */
  123. case -2: return 8; /* Error. */
  124. }
  125. /* Rotate with CopyFile() and SetEndOfFile(). */
  126. if (copy_and_truncate) {
  127. unsigned long data;
  128. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, NSSM_REG_STDIO_COPY_AND_TRUNCATE) < 0) {
  129. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, NSSM_REG_STDIO_COPY_AND_TRUNCATE, _T("get_createfile_parameters()"), 0);
  130. return 9;
  131. }
  132. switch (get_number(key, value, &data, false)) {
  133. case 0: *copy_and_truncate = false; break; /* Missing. */
  134. case 1: /* Found. */
  135. if (data) *copy_and_truncate = true;
  136. else *copy_and_truncate = false;
  137. break;
  138. case -2: return 9; /* Error. */
  139. }
  140. }
  141. return 0;
  142. }
  143. int set_createfile_parameter(HKEY key, TCHAR *prefix, TCHAR *suffix, unsigned long number) {
  144. TCHAR value[NSSM_STDIO_LENGTH];
  145. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, suffix) < 0) {
  146. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, suffix, _T("set_createfile_parameter()"), 0);
  147. return 1;
  148. }
  149. return set_number(key, value, number);
  150. }
  151. int delete_createfile_parameter(HKEY key, TCHAR *prefix, TCHAR *suffix) {
  152. TCHAR value[NSSM_STDIO_LENGTH];
  153. if (_sntprintf_s(value, _countof(value), _TRUNCATE, _T("%s%s"), prefix, suffix) < 0) {
  154. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, suffix, _T("delete_createfile_parameter()"), 0);
  155. return 1;
  156. }
  157. if (RegDeleteValue(key, value)) return 0;
  158. return 1;
  159. }
  160. HANDLE write_to_file(TCHAR *path, unsigned long sharing, SECURITY_ATTRIBUTES *attributes, unsigned long disposition, unsigned long flags) {
  161. static LARGE_INTEGER offset = { 0 };
  162. HANDLE ret = CreateFile(path, FILE_WRITE_DATA, sharing, attributes, disposition, flags, 0);
  163. if (ret != INVALID_HANDLE_VALUE) {
  164. if (SetFilePointerEx(ret, offset, 0, FILE_END)) SetEndOfFile(ret);
  165. return ret;
  166. }
  167. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEFILE_FAILED, path, error_string(GetLastError()), 0);
  168. return ret;
  169. }
  170. static void rotated_filename(TCHAR *path, TCHAR *rotated, unsigned long rotated_len, SYSTEMTIME *st) {
  171. if (! st) {
  172. SYSTEMTIME now;
  173. st = &now;
  174. GetSystemTime(st);
  175. }
  176. TCHAR buffer[PATH_LENGTH];
  177. memmove(buffer, path, sizeof(buffer));
  178. TCHAR *ext = PathFindExtension(buffer);
  179. TCHAR extension[PATH_LENGTH];
  180. _sntprintf_s(extension, _countof(extension), _TRUNCATE, _T("-%04u%02u%02uT%02u%02u%02u.%03u%s"), st->wYear, st->wMonth, st->wDay, st->wHour, st->wMinute, st->wSecond, st->wMilliseconds, ext);
  181. *ext = _T('\0');
  182. _sntprintf_s(rotated, rotated_len, _TRUNCATE, _T("%s%s"), buffer, extension);
  183. }
  184. void rotate_file(TCHAR *service_name, TCHAR *path, unsigned long seconds, unsigned long delay, unsigned long low, unsigned long high, bool copy_and_truncate) {
  185. unsigned long error;
  186. /* Now. */
  187. SYSTEMTIME st;
  188. GetSystemTime(&st);
  189. BY_HANDLE_FILE_INFORMATION info;
  190. /* Try to open the file to check if it exists and to get attributes. */
  191. HANDLE file = CreateFile(path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  192. if (file != INVALID_HANDLE_VALUE) {
  193. /* Get file attributes. */
  194. if (! GetFileInformationByHandle(file, &info)) {
  195. /* Reuse current time for rotation timestamp. */
  196. seconds = low = high = 0;
  197. SystemTimeToFileTime(&st, &info.ftLastWriteTime);
  198. }
  199. CloseHandle(file);
  200. }
  201. else {
  202. error = GetLastError();
  203. if (error == ERROR_FILE_NOT_FOUND) return;
  204. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_ROTATE_FILE_FAILED, service_name, path, _T("CreateFile()"), path, error_string(error), 0);
  205. /* Reuse current time for rotation timestamp. */
  206. seconds = low = high = 0;
  207. SystemTimeToFileTime(&st, &info.ftLastWriteTime);
  208. }
  209. /* Check file age. */
  210. if (seconds) {
  211. FILETIME ft;
  212. SystemTimeToFileTime(&st, &ft);
  213. ULARGE_INTEGER s;
  214. s.LowPart = ft.dwLowDateTime;
  215. s.HighPart = ft.dwHighDateTime;
  216. s.QuadPart -= seconds * 10000000LL;
  217. ft.dwLowDateTime = s.LowPart;
  218. ft.dwHighDateTime = s.HighPart;
  219. if (CompareFileTime(&info.ftLastWriteTime, &ft) > 0) return;
  220. }
  221. /* Check file size. */
  222. if (low || high) {
  223. if (info.nFileSizeHigh < high) return;
  224. if (info.nFileSizeHigh == high && info.nFileSizeLow < low) return;
  225. }
  226. /* Get new filename. */
  227. FileTimeToSystemTime(&info.ftLastWriteTime, &st);
  228. TCHAR rotated[PATH_LENGTH];
  229. rotated_filename(path, rotated, _countof(rotated), &st);
  230. /* Rotate. */
  231. bool ok = true;
  232. TCHAR *function;
  233. if (copy_and_truncate) {
  234. function = _T("CopyFile()");
  235. if (CopyFile(path, rotated, TRUE)) {
  236. file = write_to_file(path, NSSM_STDOUT_SHARING, 0, NSSM_STDOUT_DISPOSITION, NSSM_STDOUT_FLAGS);
  237. Sleep(delay);
  238. SetFilePointer(file, 0, 0, FILE_BEGIN);
  239. SetEndOfFile(file);
  240. CloseHandle(file);
  241. }
  242. else ok = false;
  243. }
  244. else {
  245. function = _T("MoveFile()");
  246. if (! MoveFile(path, rotated)) ok = false;
  247. }
  248. if (ok) {
  249. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ROTATED, service_name, path, rotated, 0);
  250. return;
  251. }
  252. error = GetLastError();
  253. if (error == ERROR_FILE_NOT_FOUND) return;
  254. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_ROTATE_FILE_FAILED, service_name, path, function, rotated, error_string(error), 0);
  255. return;
  256. }
  257. int get_output_handles(nssm_service_t *service, STARTUPINFO *si) {
  258. if (! si) return 1;
  259. /* Allocate a new console so we get a fresh stdin, stdout and stderr. */
  260. alloc_console(service);
  261. /* stdin */
  262. if (service->stdin_path[0]) {
  263. si->hStdInput = CreateFile(service->stdin_path, FILE_READ_DATA, service->stdin_sharing, 0, service->stdin_disposition, service->stdin_flags, 0);
  264. if (si->hStdInput == INVALID_HANDLE_VALUE) {
  265. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEFILE_FAILED, service->stdin_path, error_string(GetLastError()), 0);
  266. return 2;
  267. }
  268. }
  269. /* stdout */
  270. if (service->stdout_path[0]) {
  271. if (service->rotate_files) rotate_file(service->name, service->stdout_path, service->rotate_seconds, service->rotate_bytes_low, service->rotate_bytes_high, service->rotate_delay, service->stdout_copy_and_truncate);
  272. HANDLE stdout_handle = write_to_file(service->stdout_path, service->stdout_sharing, 0, service->stdout_disposition, service->stdout_flags);
  273. if (stdout_handle == INVALID_HANDLE_VALUE) return 4;
  274. service->stdout_si = 0;
  275. if (service->use_stdout_pipe) {
  276. service->stdout_pipe = si->hStdOutput = 0;
  277. service->stdout_thread = create_logging_thread(service->name, service->stdout_path, service->stdout_sharing, service->stdout_disposition, service->stdout_flags, &service->stdout_pipe, &service->stdout_si, &stdout_handle, service->rotate_bytes_low, service->rotate_bytes_high, service->rotate_delay, &service->stdout_tid, &service->rotate_stdout_online, service->stdout_copy_and_truncate);
  278. if (! service->stdout_thread) {
  279. CloseHandle(service->stdout_pipe);
  280. CloseHandle(service->stdout_si);
  281. }
  282. }
  283. else service->stdout_thread = 0;
  284. if (! service->stdout_thread) {
  285. if (dup_handle(stdout_handle, &service->stdout_si, NSSM_REG_STDOUT, _T("stdout"), DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) return 4;
  286. service->rotate_stdout_online = NSSM_ROTATE_OFFLINE;
  287. }
  288. if (dup_handle(service->stdout_si, &si->hStdOutput, _T("stdout_si"), _T("stdout"))) close_handle(&service->stdout_thread);
  289. }
  290. /* stderr */
  291. if (service->stderr_path[0]) {
  292. /* Same as stdout? */
  293. if (str_equiv(service->stderr_path, service->stdout_path)) {
  294. service->stderr_sharing = service->stdout_sharing;
  295. service->stderr_disposition = service->stdout_disposition;
  296. service->stderr_flags = service->stdout_flags;
  297. service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  298. /* Two handles to the same file will create a race. */
  299. /* XXX: Here we assume that either both or neither handle must be a pipe. */
  300. if (dup_handle(service->stdout_si, &service->stderr_si, _T("stdout"), _T("stderr"))) return 6;
  301. }
  302. else {
  303. if (service->rotate_files) rotate_file(service->name, service->stderr_path, service->rotate_seconds, service->rotate_bytes_low, service->rotate_bytes_high, service->rotate_delay, service->stderr_copy_and_truncate);
  304. HANDLE stderr_handle = write_to_file(service->stderr_path, service->stderr_sharing, 0, service->stderr_disposition, service->stderr_flags);
  305. if (stderr_handle == INVALID_HANDLE_VALUE) return 7;
  306. service->stderr_si = 0;
  307. if (service->use_stderr_pipe) {
  308. service->stderr_pipe = si->hStdError = 0;
  309. service->stderr_thread = create_logging_thread(service->name, service->stderr_path, service->stderr_sharing, service->stderr_disposition, service->stderr_flags, &service->stderr_pipe, &service->stderr_si, &stderr_handle, service->rotate_bytes_low, service->rotate_bytes_high, service->rotate_delay, &service->stderr_tid, &service->rotate_stderr_online, service->stderr_copy_and_truncate);
  310. if (! service->stderr_thread) {
  311. CloseHandle(service->stderr_pipe);
  312. CloseHandle(service->stderr_si);
  313. }
  314. }
  315. else service->stderr_thread = 0;
  316. if (! service->stderr_thread) {
  317. if (dup_handle(stderr_handle, &service->stderr_si, NSSM_REG_STDERR, _T("stderr"), DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) return 7;
  318. service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  319. }
  320. }
  321. if (dup_handle(service->stderr_si, &si->hStdError, _T("stderr_si"), _T("stderr"))) close_handle(&service->stderr_thread);
  322. }
  323. /*
  324. We need to set the startup_info flags to make the new handles
  325. inheritable by the new process.
  326. */
  327. si->dwFlags |= STARTF_USESTDHANDLES;
  328. if (service->no_console) return 0;
  329. /* Redirect other handles. */
  330. if (! si->hStdInput) {
  331. if (dup_handle(GetStdHandle(STD_INPUT_HANDLE), &si->hStdInput, _T("STD_INPUT_HANDLE"), _T("stdin"))) return 8;
  332. }
  333. if (! si->hStdOutput) {
  334. if (dup_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si->hStdOutput, _T("STD_OUTPUT_HANDLE"), _T("stdout"))) return 9;
  335. }
  336. if (! si->hStdError) {
  337. if (dup_handle(GetStdHandle(STD_ERROR_HANDLE), &si->hStdError, _T("STD_ERROR_HANDLE"), _T("stderr"))) return 10;
  338. }
  339. return 0;
  340. }
  341. /* Reuse output handles for a hook. */
  342. int use_output_handles(nssm_service_t *service, STARTUPINFO *si) {
  343. si->dwFlags &= ~STARTF_USESTDHANDLES;
  344. if (service->stdout_si) {
  345. if (dup_handle(service->stdout_si, &si->hStdOutput, _T("stdout_pipe"), _T("hStdOutput"))) return 1;
  346. si->dwFlags |= STARTF_USESTDHANDLES;
  347. }
  348. if (service->stderr_si) {
  349. if (dup_handle(service->stderr_si, &si->hStdError, _T("stderr_pipe"), _T("hStdError"))) {
  350. if (si->hStdOutput) {
  351. si->dwFlags &= ~STARTF_USESTDHANDLES;
  352. CloseHandle(si->hStdOutput);
  353. }
  354. return 2;
  355. }
  356. si->dwFlags |= STARTF_USESTDHANDLES;
  357. }
  358. return 0;
  359. }
  360. void close_output_handles(STARTUPINFO *si) {
  361. if (si->hStdInput) CloseHandle(si->hStdInput);
  362. if (si->hStdOutput) CloseHandle(si->hStdOutput);
  363. if (si->hStdError) CloseHandle(si->hStdError);
  364. }
  365. void cleanup_loggers(nssm_service_t *service) {
  366. unsigned long interval = NSSM_CLEANUP_LOGGERS_DEADLINE;
  367. HANDLE thread_handle = INVALID_HANDLE_VALUE;
  368. close_handle(&service->stdout_thread, &thread_handle);
  369. /* Close write end of the data pipe so logging thread can finalise read. */
  370. close_handle(&service->stdout_si);
  371. /* Await logging thread then close read end. */
  372. if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);
  373. close_handle(&service->stdout_pipe);
  374. thread_handle = INVALID_HANDLE_VALUE;
  375. close_handle(&service->stderr_thread, &thread_handle);
  376. close_handle(&service->stderr_si);
  377. if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);
  378. close_handle(&service->stderr_pipe);
  379. }
  380. /*
  381. Try multiple times to read from a file.
  382. Returns: 0 on success.
  383. 1 on non-fatal error.
  384. -1 on fatal error.
  385. */
  386. static int try_read(logger_t *logger, void *address, unsigned long bufsize, unsigned long *in, int *complained) {
  387. int ret = 1;
  388. unsigned long error;
  389. for (int tries = 0; tries < 5; tries++) {
  390. if (ReadFile(logger->read_handle, address, bufsize, in, 0)) return 0;
  391. error = GetLastError();
  392. switch (error) {
  393. /* Other end closed the pipe. */
  394. case ERROR_BROKEN_PIPE:
  395. ret = -1;
  396. goto complain_read;
  397. /* Couldn't lock the buffer. */
  398. case ERROR_NOT_ENOUGH_QUOTA:
  399. Sleep(2000 + tries * 3000);
  400. ret = 1;
  401. continue;
  402. /* Write was cancelled by the other end. */
  403. case ERROR_OPERATION_ABORTED:
  404. ret = 1;
  405. goto complain_read;
  406. default:
  407. ret = -1;
  408. }
  409. }
  410. complain_read:
  411. /* Ignore the error if we've been requested to exit anyway. */
  412. if (*logger->rotate_online != NSSM_ROTATE_ONLINE) return ret;
  413. if (! (*complained & COMPLAINED_READ)) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_READFILE_FAILED, logger->service_name, logger->path, error_string(error), 0);
  414. *complained |= COMPLAINED_READ;
  415. return ret;
  416. }
  417. /*
  418. Try multiple times to write to a file.
  419. Returns: 0 on success.
  420. 1 on non-fatal error.
  421. -1 on fatal error.
  422. */
  423. static int try_write(logger_t *logger, void *address, unsigned long bufsize, unsigned long *out, int *complained) {
  424. int ret = 1;
  425. unsigned long error;
  426. for (int tries = 0; tries < 5; tries++) {
  427. if (WriteFile(logger->write_handle, address, bufsize, out, 0)) return 0;
  428. error = GetLastError();
  429. if (error == ERROR_IO_PENDING) {
  430. /* Operation was successful pending flush to disk. */
  431. return 0;
  432. }
  433. switch (error) {
  434. /* Other end closed the pipe. */
  435. case ERROR_BROKEN_PIPE:
  436. ret = -1;
  437. goto complain_write;
  438. /* Couldn't lock the buffer. */
  439. case ERROR_NOT_ENOUGH_QUOTA:
  440. /* Out of disk space. */
  441. case ERROR_DISK_FULL:
  442. Sleep(2000 + tries * 3000);
  443. ret = 1;
  444. continue;
  445. default:
  446. /* We'll lose this line but try to read and write subsequent ones. */
  447. ret = 1;
  448. }
  449. }
  450. complain_write:
  451. if (! (*complained & COMPLAINED_WRITE)) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_WRITEFILE_FAILED, logger->service_name, logger->path, error_string(error), 0);
  452. *complained |= COMPLAINED_WRITE;
  453. return ret;
  454. }
  455. /* Wrapper to be called in a new thread for logging. */
  456. unsigned long WINAPI log_and_rotate(void *arg) {
  457. logger_t *logger = (logger_t *) arg;
  458. if (! logger) return 1;
  459. __int64 size;
  460. BY_HANDLE_FILE_INFORMATION info;
  461. /* Find initial file size. */
  462. if (! GetFileInformationByHandle(logger->write_handle, &info)) logger->size = 0LL;
  463. else {
  464. ULARGE_INTEGER l;
  465. l.HighPart = info.nFileSizeHigh;
  466. l.LowPart = info.nFileSizeLow;
  467. size = l.QuadPart;
  468. }
  469. char buffer[1024];
  470. void *address;
  471. unsigned long in, out;
  472. unsigned long charsize = 0;
  473. unsigned long error;
  474. int ret;
  475. int complained = 0;
  476. while (true) {
  477. /* Read data from the pipe. */
  478. address = &buffer;
  479. ret = try_read(logger, address, sizeof(buffer), &in, &complained);
  480. if (ret < 0) {
  481. close_handle(&logger->read_handle);
  482. close_handle(&logger->write_handle);
  483. HeapFree(GetProcessHeap(), 0, logger);
  484. return 2;
  485. }
  486. else if (ret) continue;
  487. if (*logger->rotate_online == NSSM_ROTATE_ONLINE_ASAP || (logger->size && size + (__int64) in >= logger->size)) {
  488. /* Look for newline. */
  489. unsigned long i;
  490. for (i = 0; i < in; i++) {
  491. if (buffer[i] == '\n') {
  492. if (! charsize) charsize = guess_charsize(address, in);
  493. i += charsize;
  494. /* Write up to the newline. */
  495. ret = try_write(logger, address, i, &out, &complained);
  496. if (ret < 0) {
  497. close_handle(&logger->read_handle);
  498. close_handle(&logger->write_handle);
  499. HeapFree(GetProcessHeap(), 0, logger);
  500. return 3;
  501. }
  502. size += (__int64) out;
  503. /* Rotate. */
  504. *logger->rotate_online = NSSM_ROTATE_ONLINE;
  505. TCHAR rotated[PATH_LENGTH];
  506. rotated_filename(logger->path, rotated, _countof(rotated), 0);
  507. /*
  508. Ideally we'd try the rename first then close the handle but
  509. MoveFile() will fail if the handle is still open so we must
  510. risk losing everything.
  511. */
  512. if (logger->copy_and_truncate) FlushFileBuffers(logger->write_handle);
  513. close_handle(&logger->write_handle);
  514. bool ok = true;
  515. TCHAR *function;
  516. if (logger->copy_and_truncate) {
  517. function = _T("CopyFile()");
  518. if (CopyFile(logger->path, rotated, TRUE)) {
  519. HANDLE file = write_to_file(logger->path, NSSM_STDOUT_SHARING, 0, NSSM_STDOUT_DISPOSITION, NSSM_STDOUT_FLAGS);
  520. Sleep(logger->rotate_delay);
  521. SetFilePointer(file, 0, 0, FILE_BEGIN);
  522. SetEndOfFile(file);
  523. CloseHandle(file);
  524. }
  525. else ok = false;
  526. }
  527. else {
  528. function = _T("MoveFile()");
  529. if (! MoveFile(logger->path, rotated)) ok = false;
  530. }
  531. if (ok) {
  532. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ROTATED, logger->service_name, logger->path, rotated, 0);
  533. size = 0LL;
  534. }
  535. else {
  536. error = GetLastError();
  537. if (error != ERROR_FILE_NOT_FOUND) {
  538. if (! (complained & COMPLAINED_ROTATE)) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_ROTATE_FILE_FAILED, logger->service_name, logger->path, function, rotated, error_string(error), 0);
  539. complained |= COMPLAINED_ROTATE;
  540. /* We can at least try to re-open the existing file. */
  541. logger->disposition = OPEN_ALWAYS;
  542. }
  543. }
  544. /* Reopen. */
  545. logger->write_handle = write_to_file(logger->path, logger->sharing, 0, logger->disposition, logger->flags);
  546. if (logger->write_handle == INVALID_HANDLE_VALUE) {
  547. error = GetLastError();
  548. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEFILE_FAILED, logger->path, error_string(error), 0);
  549. /* Oh dear. Now we can't log anything further. */
  550. close_handle(&logger->read_handle);
  551. close_handle(&logger->write_handle);
  552. HeapFree(GetProcessHeap(), 0, logger);
  553. return 4;
  554. }
  555. /* Resume writing after the newline. */
  556. address = (void *) ((char *) address + i);
  557. in -= i;
  558. }
  559. }
  560. }
  561. if (! size) {
  562. /* Write a BOM to the new file. */
  563. if (! charsize) charsize = guess_charsize(address, in);
  564. if (charsize == sizeof(wchar_t)) write_bom(logger, &out);
  565. size += (__int64) out;
  566. }
  567. /* Write the data, if any. */
  568. if (! in) continue;
  569. ret = try_write(logger, address, in, &out, &complained);
  570. size += (__int64) out;
  571. if (ret < 0) {
  572. close_handle(&logger->read_handle);
  573. close_handle(&logger->write_handle);
  574. HeapFree(GetProcessHeap(), 0, logger);
  575. return 3;
  576. }
  577. }
  578. close_handle(&logger->read_handle);
  579. close_handle(&logger->write_handle);
  580. HeapFree(GetProcessHeap(), 0, logger);
  581. return 0;
  582. }