io.cpp 23 KB

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