io.cpp 24 KB

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