io.cpp 24 KB

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