io.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. /* Allocate a new console so we get a fresh stdin, stdout and stderr. */
  264. alloc_console(service);
  265. /* stdin */
  266. if (service->stdin_path[0]) {
  267. si->hStdInput = CreateFile(service->stdin_path, FILE_READ_DATA, service->stdin_sharing, 0, service->stdin_disposition, service->stdin_flags, 0);
  268. if (si->hStdInput == INVALID_HANDLE_VALUE) {
  269. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEFILE_FAILED, service->stdin_path, error_string(GetLastError()), 0);
  270. return 2;
  271. }
  272. }
  273. /* stdout */
  274. if (service->stdout_path[0]) {
  275. 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);
  276. HANDLE stdout_handle = write_to_file(service->stdout_path, service->stdout_sharing, 0, service->stdout_disposition, service->stdout_flags);
  277. if (stdout_handle == INVALID_HANDLE_VALUE) return 4;
  278. service->stdout_si = 0;
  279. if (service->use_stdout_pipe) {
  280. service->stdout_pipe = si->hStdOutput = 0;
  281. 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);
  282. if (! service->stdout_thread) {
  283. CloseHandle(service->stdout_pipe);
  284. CloseHandle(service->stdout_si);
  285. }
  286. }
  287. else service->stdout_thread = 0;
  288. if (! service->stdout_thread) {
  289. if (dup_handle(stdout_handle, &service->stdout_si, NSSM_REG_STDOUT, _T("stdout"), DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) return 4;
  290. service->rotate_stdout_online = NSSM_ROTATE_OFFLINE;
  291. }
  292. if (dup_handle(service->stdout_si, &si->hStdOutput, _T("stdout_si"), _T("stdout"))) close_handle(&service->stdout_thread);
  293. }
  294. /* stderr */
  295. if (service->stderr_path[0]) {
  296. /* Same as stdout? */
  297. if (str_equiv(service->stderr_path, service->stdout_path)) {
  298. service->stderr_sharing = service->stdout_sharing;
  299. service->stderr_disposition = service->stdout_disposition;
  300. service->stderr_flags = service->stdout_flags;
  301. service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  302. /* Two handles to the same file will create a race. */
  303. /* XXX: Here we assume that either both or neither handle must be a pipe. */
  304. if (dup_handle(service->stdout_si, &service->stderr_si, _T("stdout"), _T("stderr"))) return 6;
  305. }
  306. else {
  307. 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);
  308. HANDLE stderr_handle = write_to_file(service->stderr_path, service->stderr_sharing, 0, service->stderr_disposition, service->stderr_flags);
  309. if (stderr_handle == INVALID_HANDLE_VALUE) return 7;
  310. service->stderr_si = 0;
  311. if (service->use_stderr_pipe) {
  312. service->stderr_pipe = si->hStdError = 0;
  313. 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);
  314. if (! service->stderr_thread) {
  315. CloseHandle(service->stderr_pipe);
  316. CloseHandle(service->stderr_si);
  317. }
  318. }
  319. else service->stderr_thread = 0;
  320. if (! service->stderr_thread) {
  321. if (dup_handle(stderr_handle, &service->stderr_si, NSSM_REG_STDERR, _T("stderr"), DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) return 7;
  322. service->rotate_stderr_online = NSSM_ROTATE_OFFLINE;
  323. }
  324. }
  325. if (dup_handle(service->stderr_si, &si->hStdError, _T("stderr_si"), _T("stderr"))) close_handle(&service->stderr_thread);
  326. }
  327. /*
  328. We need to set the startup_info flags to make the new handles
  329. inheritable by the new process.
  330. */
  331. si->dwFlags |= STARTF_USESTDHANDLES;
  332. if (service->no_console) return 0;
  333. /* Redirect other handles. */
  334. if (! si->hStdInput) {
  335. if (dup_handle(GetStdHandle(STD_INPUT_HANDLE), &si->hStdInput, _T("STD_INPUT_HANDLE"), _T("stdin"))) return 8;
  336. }
  337. if (! si->hStdOutput) {
  338. if (dup_handle(GetStdHandle(STD_OUTPUT_HANDLE), &si->hStdOutput, _T("STD_OUTPUT_HANDLE"), _T("stdout"))) return 9;
  339. }
  340. if (! si->hStdError) {
  341. if (dup_handle(GetStdHandle(STD_ERROR_HANDLE), &si->hStdError, _T("STD_ERROR_HANDLE"), _T("stderr"))) return 10;
  342. }
  343. return 0;
  344. }
  345. /* Reuse output handles for a hook. */
  346. int use_output_handles(nssm_service_t *service, STARTUPINFO *si) {
  347. si->dwFlags &= ~STARTF_USESTDHANDLES;
  348. if (service->stdout_si) {
  349. if (dup_handle(service->stdout_si, &si->hStdOutput, _T("stdout_pipe"), _T("hStdOutput"))) return 1;
  350. si->dwFlags |= STARTF_USESTDHANDLES;
  351. }
  352. if (service->stderr_si) {
  353. if (dup_handle(service->stderr_si, &si->hStdError, _T("stderr_pipe"), _T("hStdError"))) {
  354. if (si->hStdOutput) {
  355. si->dwFlags &= ~STARTF_USESTDHANDLES;
  356. CloseHandle(si->hStdOutput);
  357. }
  358. return 2;
  359. }
  360. si->dwFlags |= STARTF_USESTDHANDLES;
  361. }
  362. return 0;
  363. }
  364. void close_output_handles(STARTUPINFO *si) {
  365. if (si->hStdInput) CloseHandle(si->hStdInput);
  366. if (si->hStdOutput) CloseHandle(si->hStdOutput);
  367. if (si->hStdError) CloseHandle(si->hStdError);
  368. }
  369. void cleanup_loggers(nssm_service_t *service) {
  370. unsigned long interval = NSSM_CLEANUP_LOGGERS_DEADLINE;
  371. HANDLE thread_handle = INVALID_HANDLE_VALUE;
  372. close_handle(&service->stdout_thread, &thread_handle);
  373. /* Close write end of the data pipe so logging thread can finalise read. */
  374. close_handle(&service->stdout_si);
  375. /* Await logging thread then close read end. */
  376. if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);
  377. close_handle(&service->stdout_pipe);
  378. thread_handle = INVALID_HANDLE_VALUE;
  379. close_handle(&service->stderr_thread, &thread_handle);
  380. close_handle(&service->stderr_si);
  381. if (thread_handle != INVALID_HANDLE_VALUE) WaitForSingleObject(thread_handle, interval);
  382. close_handle(&service->stderr_pipe);
  383. }
  384. /*
  385. Try multiple times to read from a file.
  386. Returns: 0 on success.
  387. 1 on non-fatal error.
  388. -1 on fatal error.
  389. */
  390. static int try_read(logger_t *logger, void *address, unsigned long bufsize, unsigned long *in, int *complained) {
  391. int ret = 1;
  392. unsigned long error;
  393. for (int tries = 0; tries < 5; tries++) {
  394. if (ReadFile(logger->read_handle, address, bufsize, in, 0)) return 0;
  395. error = GetLastError();
  396. switch (error) {
  397. /* Other end closed the pipe. */
  398. case ERROR_BROKEN_PIPE:
  399. ret = -1;
  400. goto complain_read;
  401. /* Couldn't lock the buffer. */
  402. case ERROR_NOT_ENOUGH_QUOTA:
  403. Sleep(2000 + tries * 3000);
  404. ret = 1;
  405. continue;
  406. /* Write was cancelled by the other end. */
  407. case ERROR_OPERATION_ABORTED:
  408. ret = 1;
  409. goto complain_read;
  410. default:
  411. ret = -1;
  412. }
  413. }
  414. complain_read:
  415. /* Ignore the error if we've been requested to exit anyway. */
  416. if (*logger->rotate_online != NSSM_ROTATE_ONLINE) return ret;
  417. if (! (*complained & COMPLAINED_READ)) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_READFILE_FAILED, logger->service_name, logger->path, error_string(error), 0);
  418. *complained |= COMPLAINED_READ;
  419. return ret;
  420. }
  421. /*
  422. Try multiple times to write to a file.
  423. Returns: 0 on success.
  424. 1 on non-fatal error.
  425. -1 on fatal error.
  426. */
  427. static int try_write(logger_t *logger, void *address, unsigned long bufsize, unsigned long *out, int *complained) {
  428. int ret = 1;
  429. unsigned long error;
  430. for (int tries = 0; tries < 5; tries++) {
  431. if (WriteFile(logger->write_handle, address, bufsize, out, 0)) return 0;
  432. error = GetLastError();
  433. if (error == ERROR_IO_PENDING) {
  434. /* Operation was successful pending flush to disk. */
  435. return 0;
  436. }
  437. switch (error) {
  438. /* Other end closed the pipe. */
  439. case ERROR_BROKEN_PIPE:
  440. ret = -1;
  441. goto complain_write;
  442. /* Couldn't lock the buffer. */
  443. case ERROR_NOT_ENOUGH_QUOTA:
  444. /* Out of disk space. */
  445. case ERROR_DISK_FULL:
  446. Sleep(2000 + tries * 3000);
  447. ret = 1;
  448. continue;
  449. default:
  450. /* We'll lose this line but try to read and write subsequent ones. */
  451. ret = 1;
  452. }
  453. }
  454. complain_write:
  455. if (! (*complained & COMPLAINED_WRITE)) log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_WRITEFILE_FAILED, logger->service_name, logger->path, error_string(error), 0);
  456. *complained |= COMPLAINED_WRITE;
  457. return ret;
  458. }
  459. /* Note that the timestamp is created in UTF-8. */
  460. static inline int write_timestamp(logger_t *logger, unsigned long charsize, unsigned long *out, int *complained) {
  461. char timestamp[TIMESTAMP_LEN + 1];
  462. SYSTEMTIME now;
  463. GetSystemTime(&now);
  464. _snprintf_s(timestamp, _countof(timestamp), _TRUNCATE, TIMESTAMP_FORMAT, now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond, now.wMilliseconds);
  465. if (charsize == sizeof(char)) return try_write(logger, (void *) timestamp, TIMESTAMP_LEN, out, complained);
  466. wchar_t *utf16;
  467. unsigned long utf16len;
  468. if (to_utf16(timestamp, &utf16, &utf16len)) return -1;
  469. int ret = try_write(logger, (void *) *utf16, utf16len * sizeof(wchar_t), out, complained);
  470. HeapFree(GetProcessHeap(), 0, utf16);
  471. return ret;
  472. }
  473. static int write_with_timestamp(logger_t *logger, void *address, unsigned long bufsize, unsigned long *out, int *complained, unsigned long charsize) {
  474. if (logger->timestamp_log) {
  475. unsigned long log_out;
  476. int log_complained;
  477. unsigned long timestamp_out = 0;
  478. int timestamp_complained;
  479. if (! logger->line_length) {
  480. write_timestamp(logger, charsize, &timestamp_out, &timestamp_complained);
  481. logger->line_length += (__int64) timestamp_out;
  482. *out += timestamp_out;
  483. *complained |= timestamp_complained;
  484. }
  485. unsigned long i;
  486. void *line = address;
  487. unsigned long offset = 0;
  488. int ret;
  489. for (i = 0; i < bufsize; i++) {
  490. if (((char *) address)[i] == '\n') {
  491. ret = try_write(logger, line, i - offset + 1, &log_out, &log_complained);
  492. line = (void *) ((char *) line + i - offset + 1);
  493. logger->line_length = 0LL;
  494. *out += log_out;
  495. *complained |= log_complained;
  496. offset = i + 1;
  497. if (offset < bufsize) {
  498. write_timestamp(logger, charsize, &timestamp_out, &timestamp_complained);
  499. logger->line_length += (__int64) timestamp_out;
  500. *out += timestamp_out;
  501. *complained |= timestamp_complained;
  502. }
  503. }
  504. }
  505. if (offset < bufsize) {
  506. ret = try_write(logger, line, bufsize - offset, &log_out, &log_complained);
  507. *out += log_out;
  508. *complained |= log_complained;
  509. }
  510. return ret;
  511. }
  512. else return try_write(logger, address, bufsize, out, complained);
  513. }
  514. /* Wrapper to be called in a new thread for logging. */
  515. unsigned long WINAPI log_and_rotate(void *arg) {
  516. logger_t *logger = (logger_t *) arg;
  517. if (! logger) return 1;
  518. __int64 size;
  519. BY_HANDLE_FILE_INFORMATION info;
  520. /* Find initial file size. */
  521. if (! GetFileInformationByHandle(logger->write_handle, &info)) logger->size = 0LL;
  522. else {
  523. ULARGE_INTEGER l;
  524. l.HighPart = info.nFileSizeHigh;
  525. l.LowPart = info.nFileSizeLow;
  526. size = l.QuadPart;
  527. }
  528. char buffer[1024];
  529. void *address;
  530. unsigned long in, out;
  531. unsigned long charsize = 0;
  532. unsigned long error;
  533. int ret;
  534. int complained = 0;
  535. while (true) {
  536. /* Read data from the pipe. */
  537. address = &buffer;
  538. ret = try_read(logger, address, sizeof(buffer), &in, &complained);
  539. if (ret < 0) {
  540. close_handle(&logger->read_handle);
  541. close_handle(&logger->write_handle);
  542. HeapFree(GetProcessHeap(), 0, logger);
  543. return 2;
  544. }
  545. else if (ret) continue;
  546. if (*logger->rotate_online == NSSM_ROTATE_ONLINE_ASAP || (logger->size && size + (__int64) in >= logger->size)) {
  547. /* Look for newline. */
  548. unsigned long i;
  549. for (i = 0; i < in; i++) {
  550. if (buffer[i] == '\n') {
  551. if (! charsize) charsize = guess_charsize(address, in);
  552. i += charsize;
  553. /* Write up to the newline. */
  554. ret = try_write(logger, address, i, &out, &complained);
  555. if (ret < 0) {
  556. close_handle(&logger->read_handle);
  557. close_handle(&logger->write_handle);
  558. HeapFree(GetProcessHeap(), 0, logger);
  559. return 3;
  560. }
  561. size += (__int64) out;
  562. /* Rotate. */
  563. *logger->rotate_online = NSSM_ROTATE_ONLINE;
  564. TCHAR rotated[PATH_LENGTH];
  565. rotated_filename(logger->path, rotated, _countof(rotated), 0);
  566. /*
  567. Ideally we'd try the rename first then close the handle but
  568. MoveFile() will fail if the handle is still open so we must
  569. risk losing everything.
  570. */
  571. if (logger->copy_and_truncate) FlushFileBuffers(logger->write_handle);
  572. close_handle(&logger->write_handle);
  573. bool ok = true;
  574. TCHAR *function;
  575. if (logger->copy_and_truncate) {
  576. function = _T("CopyFile()");
  577. if (CopyFile(logger->path, rotated, TRUE)) {
  578. HANDLE file = write_to_file(logger->path, NSSM_STDOUT_SHARING, 0, NSSM_STDOUT_DISPOSITION, NSSM_STDOUT_FLAGS);
  579. Sleep(logger->rotate_delay);
  580. SetFilePointer(file, 0, 0, FILE_BEGIN);
  581. SetEndOfFile(file);
  582. CloseHandle(file);
  583. }
  584. else ok = false;
  585. }
  586. else {
  587. function = _T("MoveFile()");
  588. if (! MoveFile(logger->path, rotated)) ok = false;
  589. }
  590. if (ok) {
  591. log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_ROTATED, logger->service_name, logger->path, rotated, 0);
  592. size = 0LL;
  593. }
  594. else {
  595. error = GetLastError();
  596. if (error != ERROR_FILE_NOT_FOUND) {
  597. 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);
  598. complained |= COMPLAINED_ROTATE;
  599. /* We can at least try to re-open the existing file. */
  600. logger->disposition = OPEN_ALWAYS;
  601. }
  602. }
  603. /* Reopen. */
  604. logger->write_handle = write_to_file(logger->path, logger->sharing, 0, logger->disposition, logger->flags);
  605. if (logger->write_handle == INVALID_HANDLE_VALUE) {
  606. error = GetLastError();
  607. log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_CREATEFILE_FAILED, logger->path, error_string(error), 0);
  608. /* Oh dear. Now we can't log anything further. */
  609. close_handle(&logger->read_handle);
  610. close_handle(&logger->write_handle);
  611. HeapFree(GetProcessHeap(), 0, logger);
  612. return 4;
  613. }
  614. /* Resume writing after the newline. */
  615. address = (void *) ((char *) address + i);
  616. in -= i;
  617. }
  618. }
  619. }
  620. if (! size || logger->timestamp_log) if (! charsize) charsize = guess_charsize(address, in);
  621. if (! size) {
  622. /* Write a BOM to the new file. */
  623. if (charsize == sizeof(wchar_t)) write_bom(logger, &out);
  624. size += (__int64) out;
  625. }
  626. /* Write the data, if any. */
  627. if (! in) continue;
  628. ret = write_with_timestamp(logger, address, in, &out, &complained, charsize);
  629. size += (__int64) out;
  630. if (ret < 0) {
  631. close_handle(&logger->read_handle);
  632. close_handle(&logger->write_handle);
  633. HeapFree(GetProcessHeap(), 0, logger);
  634. return 3;
  635. }
  636. }
  637. close_handle(&logger->read_handle);
  638. close_handle(&logger->write_handle);
  639. HeapFree(GetProcessHeap(), 0, logger);
  640. return 0;
  641. }