io.cpp 28 KB

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