]> git.proxmox.com Git - mirror_smartmontools-debian.git/blame - os_win32/syslog_win32.cpp
import smartmontools 7.0
[mirror_smartmontools-debian.git] / os_win32 / syslog_win32.cpp
CommitLineData
832b75ed 1/*
4d59bff9 2 * os_win32/syslog_win32.cpp
832b75ed 3 *
6b80b4d2 4 * Home page of code is: http://www.smartmontools.org
832b75ed 5 *
6b80b4d2 6 * Copyright (C) 2004-15 Christian Franke
832b75ed 7 *
ff28b140 8 * SPDX-License-Identifier: GPL-2.0-or-later
832b75ed
GG
9 */
10
11// Win32 Emulation of syslog() for smartd
12// Writes to windows event log on NT4/2000/XP
13// (Register syslogevt.exe as event message file)
832b75ed
GG
14// If facility is set to LOG_LOCAL[0-7], log is written to
15// file "<ident>.log", stdout, stderr, "<ident>[1-5].log".
16
17
18#include "syslog.h"
19
20#include <stdlib.h>
21#include <stdio.h>
22#include <time.h>
23#include <errno.h>
24#include <process.h> // getpid()
25
26#define WIN32_LEAN_AND_MEAN
27#include <windows.h> // RegisterEventSourceA(), ReportEventA(), ...
28
ff28b140 29const char *syslog_win32_cpp_cvsid = "$Id: syslog_win32.cpp 4760 2018-08-19 18:45:53Z chrfranke $"
ee38a438 30 SYSLOG_H_CVSID;
832b75ed
GG
31
32#ifdef _MSC_VER
33// MSVC
34#define snprintf _snprintf
35#define vsnprintf _vsnprintf
36#endif
37
38#define ARGUSED(x) ((void)(x))
39
40
41#ifndef _MT
42//MT runtime not necessary, because thread uses no unsafe lib functions
43//#error Program must be linked with multithreaded runtime library
44#endif
45
46
47#ifdef TESTEVT
48// Redirect event log to stdout for testing
49
50static BOOL Test_ReportEventA(HANDLE h, WORD type, WORD cat, DWORD id, PSID usid,
51 WORD nstrings, WORD datasize, LPCTSTR * strings, LPVOID data)
52{
53 int i;
54 printf("%u %lu:%s", type, id, nstrings != 1?"\n":"");
55 for (i = 0; i < nstrings; i++)
56 printf(" \"%s\"\n", strings[i]);
57 fflush(stdout);
58 return TRUE;
59}
60
61HANDLE Test_RegisterEventSourceA(LPCTSTR server, LPCTSTR source)
62{
63 return (HANDLE)42;
64}
65
66#define ReportEventA Test_ReportEventA
67#define RegisterEventSourceA Test_RegisterEventSourceA
68#endif // TESTEVT
69
70
71// Event message ids,
72// should be identical to MSG_SYSLOG* in "syslogevt.h"
73// (generated by "mc" from "syslogevt.mc")
74#define MSG_SYSLOG 0x00000000L
75#define MSG_SYSLOG_01 0x00000001L
76// ...
77#define MSG_SYSLOG_10 0x0000000AL
78
79static char sl_ident[100];
80static char sl_logpath[sizeof(sl_ident) + sizeof("0.log")-1];
81static FILE * sl_logfile;
82static char sl_pidstr[16];
83static HANDLE sl_hevtsrc;
84
85
86// Ring buffer for event log output via thread
87#define MAXLINES 10
88#define LINELEN 200
89
90static HANDLE evt_hthread;
91static char evt_lines[MAXLINES][LINELEN+1];
92static int evt_priorities[MAXLINES];
93static volatile int evt_timeout;
94static int evt_index_in, evt_index_out;
95static HANDLE evt_wait_in, evt_wait_out;
96
97
98// Map syslog priority to event type
99
100static WORD pri2evtype(int priority)
101{
102 switch (priority) {
103 default:
104 case LOG_EMERG: case LOG_ALERT:
105 case LOG_CRIT: case LOG_ERR:
106 return EVENTLOG_ERROR_TYPE;
107 case LOG_WARNING:
108 return EVENTLOG_WARNING_TYPE;
109 case LOG_NOTICE: case LOG_INFO:
110 case LOG_DEBUG:
111 return EVENTLOG_INFORMATION_TYPE;
112 }
113}
114
115
116// Map syslog priority to string
117
118static const char * pri2text(int priority)
119{
120 switch (priority) {
121 case LOG_EMERG: return "EMERG";
122 case LOG_ALERT: return "ALERT";
123 case LOG_CRIT: return "CRIT";
124 default:
125 case LOG_ERR: return "ERROR";
126 case LOG_WARNING: return "Warn";
127 case LOG_NOTICE: return "Note";
128 case LOG_INFO: return "Info";
129 case LOG_DEBUG: return "Debug";
130 }
131}
132
133
134// Output cnt events from ring buffer
135
136static void report_events(int cnt)
137{
138 const char * msgs[3+MAXLINES];
139
140 int i, pri;
141 if (cnt <= 0)
142 return;
143 if (cnt > MAXLINES)
144 cnt = MAXLINES;
145
146 pri = evt_priorities[evt_index_out];
147
148 msgs[0] = sl_ident;
149 msgs[1] = sl_pidstr;
150 msgs[2] = pri2text(pri);
151 for (i = 0; i < cnt; i++) {
152 //assert(evt_priorities[evt_index_out] == pri);
153 msgs[3+i] = evt_lines[evt_index_out];
154 if (++evt_index_out >= MAXLINES)
155 evt_index_out = 0;
156 }
157 ReportEventA(sl_hevtsrc,
158 pri2evtype(pri), // type
159 0, MSG_SYSLOG+cnt, // category, message id
160 NULL, // no security id
161 (WORD)(3+cnt), 0, // 3+cnt strings, ...
162 msgs, NULL); // ... , no data
163}
164
165
166// Thread to combine several syslog lines into one event log entry
167
168static ULONG WINAPI event_logger_thread(LPVOID arg)
169{
170 int cnt;
171 ARGUSED(arg);
172
173 cnt = 0;
174 for (;;) {
175 // Wait for first line ...
176 int prior, i, rest;
177 if (cnt == 0) {
178 if (WaitForSingleObject(evt_wait_out, (evt_timeout? INFINITE : 0)) != WAIT_OBJECT_0)
179 break;
180 cnt = 1;
181 }
182
183 // ... wait some time for more lines with same prior
184 i = evt_index_out;
185 prior = evt_priorities[i];
186 rest = 0;
187 while (cnt < MAXLINES) {
188 long timeout =
189 evt_timeout * ((1000L * (MAXLINES-cnt+1))/MAXLINES);
190 if (WaitForSingleObject(evt_wait_out, timeout) != WAIT_OBJECT_0)
191 break;
192 if (++i >= MAXLINES)
193 i = 0;
194 if (evt_priorities[i] != prior) {
195 rest = 1;
196 break;
197 }
198 cnt++;
199 }
200
201 // Output all in one event log entry
202 report_events(cnt);
203
204 // Signal space
205 if (!ReleaseSemaphore(evt_wait_in, cnt, NULL))
206 break;
207 cnt = rest;
208 }
209 return 0;
210}
211
212
213static void on_exit_event_logger(void)
214{
215 // Output lines immediate if exiting
216 evt_timeout = 0;
217 // Wait for thread to finish
218 WaitForSingleObject(evt_hthread, 1000L);
219 CloseHandle(evt_hthread);
220#if 0
221 if (sl_hevtsrc) {
222 DeregisterEventSource(sl_hevtsrc); sl_hevtsrc = 0;
223 }
224#else
225 // Leave event message source open to prevent losing messages during shutdown
226#endif
227}
228
229
230static int start_event_logger()
231{
232 DWORD tid;
233 evt_timeout = 1;
234 if ( !(evt_wait_in = CreateSemaphore(NULL, MAXLINES, MAXLINES, NULL))
235 || !(evt_wait_out = CreateSemaphore(NULL, 0, MAXLINES, NULL))) {
236 fprintf(stderr,"CreateSemaphore failed, Error=%ld\n", GetLastError());
237 return -1;
238 }
239 if (!(evt_hthread = CreateThread(NULL, 0, event_logger_thread, NULL, 0, &tid))) {
240 fprintf(stderr,"CreateThread failed, Error=%ld\n", GetLastError());
241 return -1;
242 }
243 atexit(on_exit_event_logger);
244 return 0;
245}
246
247
248// Write lines to event log ring buffer
249
250static void write_event_log(int priority, const char * lines)
251{
252 int cnt = 0;
253 int i;
254 for (i = 0; lines[i]; i++) {
255 int len = 0;
256 while (lines[i+len] && lines[i+len] != '\n')
257 len++;
258 ;
259 if (len > 0) {
260 // Wait for space
261 if (WaitForSingleObject(evt_wait_in, INFINITE) != WAIT_OBJECT_0)
262 return;
263 // Copy line
264 evt_priorities[evt_index_in] = priority;
265 memcpy(evt_lines[evt_index_in], lines+i, (len < LINELEN ? len : LINELEN));
266 if (len < LINELEN)
267 evt_lines[evt_index_in][len] = 0;
268 if (++evt_index_in >= MAXLINES)
269 evt_index_in = 0;
270 // Signal avail if ring buffer full
271 if (++cnt >= MAXLINES) {
272 ReleaseSemaphore(evt_wait_out, cnt, NULL);
273 cnt = 0;
274 }
275 i += len;
276 }
277 if (!lines[i])
278 break;
279 }
280
281 // Signal avail
282 if (cnt > 0)
283 ReleaseSemaphore(evt_wait_out, cnt, NULL);
284 Sleep(1);
285}
286
287
288// Write lines to logfile
289
290static void write_logfile(FILE * f, int priority, const char * lines)
291{
292 time_t now; char stamp[sizeof("2004-04-04 10:00:00")+13];
293 int i;
294
295 now = time((time_t*)0);
296 if (!strftime(stamp, sizeof(stamp)-1, "%Y-%m-%d %H:%M:%S", localtime(&now)))
297 strcpy(stamp,"?");
298
299 for (i = 0; lines[i]; i++) {
300 int len = 0;
301 while (lines[i+len] && lines[i+len] != '\n')
302 len++;
303 if (len > 0) {
304 fprintf(f, "%s %s[%s]: %-5s: ",
305 stamp, sl_ident, sl_pidstr, pri2text(priority));
306 fwrite(lines+i, len, 1, f);
307 fputc('\n', f);
308 i += len;
309 }
310 if (!lines[i])
311 break;
312 }
313}
314
315
316void openlog(const char *ident, int logopt, int facility)
317{
318 int pid;
319 if (sl_logpath[0] || sl_logfile || sl_hevtsrc)
320 return; // Already open
321
322 strncpy(sl_ident, ident, sizeof(sl_ident)-1);
323 // logopt==LOG_PID assumed
324 ARGUSED(logopt);
325 pid = getpid();
326 if (snprintf(sl_pidstr, sizeof(sl_pidstr)-1, (pid >= 0 ? "%d" : "0x%X"), pid) < 0)
327 strcpy(sl_pidstr,"?");
328
329 if (facility == LOG_LOCAL0) // "ident.log"
330 strcat(strcpy(sl_logpath, sl_ident), ".log");
331 else if (facility == LOG_LOCAL1) // stdout
332 sl_logfile = stdout;
333 else if (facility == LOG_LOCAL2) // stderr
334 sl_logfile = stderr;
335 else if (LOG_LOCAL2 < facility && facility <= LOG_LOCAL7) { // "ident[1-5].log"
336 snprintf(sl_logpath, sizeof(sl_logpath)-1, "%s%d.log",
337 sl_ident, LOG_FAC(facility)-LOG_FAC(LOG_LOCAL2));
338 }
339 else // Assume LOG_DAEMON, use event log if possible, else "ident.log"
340 if (!(sl_hevtsrc = RegisterEventSourceA(NULL/*localhost*/, sl_ident))) {
341 // Cannot open => Use logfile
342 long err = GetLastError();
343 strcat(strcpy(sl_logpath, sl_ident), ".log");
ee38a438
GI
344 fprintf(stderr, "%s: Cannot register event source (Error=%ld), writing to %s\n",
345 sl_ident, err, sl_logpath);
832b75ed
GG
346 }
347 else {
348 // Start event log thread
349 start_event_logger();
350 }
351 //assert(sl_logpath[0] || sl_logfile || sl_hevtsrc);
352
353}
354
355
356void closelog()
357{
358}
359
360
361void vsyslog(int priority, const char * message, va_list args)
362{
363 char buffer[1000];
364
365 // Translation of %m to error text not supported yet
366 if (strstr(message, "%m"))
367 message = "Internal error: \"%%m\" in log message";
368
369 // Format message
370 if (vsnprintf(buffer, sizeof(buffer)-1, message, args) < 0)
371 strcpy(buffer, "Internal Error: buffer overflow");
372
373 if (sl_hevtsrc) {
374 // Write to event log
375 write_event_log(priority, buffer);
376 }
377 else if (sl_logfile) {
378 // Write to stdout/err
379 write_logfile(sl_logfile, priority, buffer);
380 fflush(sl_logfile);
381 }
382 else if (sl_logpath[0]) {
383 // Append to logfile
384 FILE * f;
385 if (!(f = fopen(sl_logpath, "a")))
386 return;
387 write_logfile(f, priority, buffer);
388 fclose(f);
389 }
390}
391
392
393#ifdef TEST
394// Test program
395
396void syslog(int priority, const char *message, ...)
397{
398 va_list args;
399 va_start(args, message);
400 vsyslog(priority, message, args);
401 va_end(args);
402}
403
404int main(int argc, char* argv[])
405{
406 int i;
407 openlog(argc < 2 ? "test" : argv[1], LOG_PID, (argc < 3 ? LOG_DAEMON : LOG_LOCAL1));
408 syslog(LOG_INFO, "Info\n");
409 syslog(LOG_WARNING, "Warning %d\n\n", 42);
410 syslog(LOG_ERR, "Error %s", "Fatal");
411 for (i = 0; i < 100; i++) {
412 char buf[LINELEN];
413 if (i % 13 == 0)
414 Sleep(1000L);
415 sprintf(buf, "Log Line %d\n", i);
6b80b4d2 416 syslog((i % 17) ? LOG_INFO : LOG_ERR, buf);
832b75ed
GG
417 }
418 closelog();
419 return 0;
420}
421
422#endif