2 * os_win32/syslog_win32.cpp
4 * Home page of code is: http://www.smartmontools.org
6 * Copyright (C) 2004-15 Christian Franke
8 * SPDX-License-Identifier: GPL-2.0-or-later
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)
14 // If facility is set to LOG_LOCAL[0-7], log is written to
15 // file "<ident>.log", stdout, stderr, "<ident>[1-5].log".
24 #include <process.h> // getpid()
26 #define WIN32_LEAN_AND_MEAN
27 #include <windows.h> // RegisterEventSourceA(), ReportEventA(), ...
29 const char *syslog_win32_cpp_cvsid
= "$Id: syslog_win32.cpp 4760 2018-08-19 18:45:53Z chrfranke $"
34 #define snprintf _snprintf
35 #define vsnprintf _vsnprintf
38 #define ARGUSED(x) ((void)(x))
42 //MT runtime not necessary, because thread uses no unsafe lib functions
43 //#error Program must be linked with multithreaded runtime library
48 // Redirect event log to stdout for testing
50 static BOOL
Test_ReportEventA(HANDLE h
, WORD type
, WORD cat
, DWORD id
, PSID usid
,
51 WORD nstrings
, WORD datasize
, LPCTSTR
* strings
, LPVOID data
)
54 printf("%u %lu:%s", type
, id
, nstrings
!= 1?"\n":"");
55 for (i
= 0; i
< nstrings
; i
++)
56 printf(" \"%s\"\n", strings
[i
]);
61 HANDLE
Test_RegisterEventSourceA(LPCTSTR server
, LPCTSTR source
)
66 #define ReportEventA Test_ReportEventA
67 #define RegisterEventSourceA Test_RegisterEventSourceA
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
77 #define MSG_SYSLOG_10 0x0000000AL
79 static char sl_ident
[100];
80 static char sl_logpath
[sizeof(sl_ident
) + sizeof("0.log")-1];
81 static FILE * sl_logfile
;
82 static char sl_pidstr
[16];
83 static HANDLE sl_hevtsrc
;
86 // Ring buffer for event log output via thread
90 static HANDLE evt_hthread
;
91 static char evt_lines
[MAXLINES
][LINELEN
+1];
92 static int evt_priorities
[MAXLINES
];
93 static volatile int evt_timeout
;
94 static int evt_index_in
, evt_index_out
;
95 static HANDLE evt_wait_in
, evt_wait_out
;
98 // Map syslog priority to event type
100 static WORD
pri2evtype(int priority
)
104 case LOG_EMERG
: case LOG_ALERT
:
105 case LOG_CRIT
: case LOG_ERR
:
106 return EVENTLOG_ERROR_TYPE
;
108 return EVENTLOG_WARNING_TYPE
;
109 case LOG_NOTICE
: case LOG_INFO
:
111 return EVENTLOG_INFORMATION_TYPE
;
116 // Map syslog priority to string
118 static const char * pri2text(int priority
)
121 case LOG_EMERG
: return "EMERG";
122 case LOG_ALERT
: return "ALERT";
123 case LOG_CRIT
: return "CRIT";
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";
134 // Output cnt events from ring buffer
136 static void report_events(int cnt
)
138 const char * msgs
[3+MAXLINES
];
146 pri
= evt_priorities
[evt_index_out
];
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
)
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
166 // Thread to combine several syslog lines into one event log entry
168 static ULONG WINAPI
event_logger_thread(LPVOID arg
)
175 // Wait for first line ...
178 if (WaitForSingleObject(evt_wait_out
, (evt_timeout
? INFINITE
: 0)) != WAIT_OBJECT_0
)
183 // ... wait some time for more lines with same prior
185 prior
= evt_priorities
[i
];
187 while (cnt
< MAXLINES
) {
189 evt_timeout
* ((1000L * (MAXLINES
-cnt
+1))/MAXLINES
);
190 if (WaitForSingleObject(evt_wait_out
, timeout
) != WAIT_OBJECT_0
)
194 if (evt_priorities
[i
] != prior
) {
201 // Output all in one event log entry
205 if (!ReleaseSemaphore(evt_wait_in
, cnt
, NULL
))
213 static void on_exit_event_logger(void)
215 // Output lines immediate if exiting
217 // Wait for thread to finish
218 WaitForSingleObject(evt_hthread
, 1000L);
219 CloseHandle(evt_hthread
);
222 DeregisterEventSource(sl_hevtsrc
); sl_hevtsrc
= 0;
225 // Leave event message source open to prevent losing messages during shutdown
230 static int start_event_logger()
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());
239 if (!(evt_hthread
= CreateThread(NULL
, 0, event_logger_thread
, NULL
, 0, &tid
))) {
240 fprintf(stderr
,"CreateThread failed, Error=%ld\n", GetLastError());
243 atexit(on_exit_event_logger
);
248 // Write lines to event log ring buffer
250 static void write_event_log(int priority
, const char * lines
)
254 for (i
= 0; lines
[i
]; i
++) {
256 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
261 if (WaitForSingleObject(evt_wait_in
, INFINITE
) != WAIT_OBJECT_0
)
264 evt_priorities
[evt_index_in
] = priority
;
265 memcpy(evt_lines
[evt_index_in
], lines
+i
, (len
< LINELEN
? len
: LINELEN
));
267 evt_lines
[evt_index_in
][len
] = 0;
268 if (++evt_index_in
>= MAXLINES
)
270 // Signal avail if ring buffer full
271 if (++cnt
>= MAXLINES
) {
272 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
283 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
288 // Write lines to logfile
290 static void write_logfile(FILE * f
, int priority
, const char * lines
)
292 time_t now
; char stamp
[sizeof("2004-04-04 10:00:00")+13];
295 now
= time((time_t*)0);
296 if (!strftime(stamp
, sizeof(stamp
)-1, "%Y-%m-%d %H:%M:%S", localtime(&now
)))
299 for (i
= 0; lines
[i
]; i
++) {
301 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
304 fprintf(f
, "%s %s[%s]: %-5s: ",
305 stamp
, sl_ident
, sl_pidstr
, pri2text(priority
));
306 fwrite(lines
+i
, len
, 1, f
);
316 void openlog(const char *ident
, int logopt
, int facility
)
319 if (sl_logpath
[0] || sl_logfile
|| sl_hevtsrc
)
320 return; // Already open
322 strncpy(sl_ident
, ident
, sizeof(sl_ident
)-1);
323 // logopt==LOG_PID assumed
326 if (snprintf(sl_pidstr
, sizeof(sl_pidstr
)-1, (pid
>= 0 ? "%d" : "0x%X"), pid
) < 0)
327 strcpy(sl_pidstr
,"?");
329 if (facility
== LOG_LOCAL0
) // "ident.log"
330 strcat(strcpy(sl_logpath
, sl_ident
), ".log");
331 else if (facility
== LOG_LOCAL1
) // stdout
333 else if (facility
== LOG_LOCAL2
) // 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
));
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");
344 fprintf(stderr
, "%s: Cannot register event source (Error=%ld), writing to %s\n",
345 sl_ident
, err
, sl_logpath
);
348 // Start event log thread
349 start_event_logger();
351 //assert(sl_logpath[0] || sl_logfile || sl_hevtsrc);
361 void vsyslog(int priority
, const char * message
, va_list args
)
365 // Translation of %m to error text not supported yet
366 if (strstr(message
, "%m"))
367 message
= "Internal error: \"%%m\" in log message";
370 if (vsnprintf(buffer
, sizeof(buffer
)-1, message
, args
) < 0)
371 strcpy(buffer
, "Internal Error: buffer overflow");
374 // Write to event log
375 write_event_log(priority
, buffer
);
377 else if (sl_logfile
) {
378 // Write to stdout/err
379 write_logfile(sl_logfile
, priority
, buffer
);
382 else if (sl_logpath
[0]) {
385 if (!(f
= fopen(sl_logpath
, "a")))
387 write_logfile(f
, priority
, buffer
);
396 void syslog(int priority
, const char *message
, ...)
399 va_start(args
, message
);
400 vsyslog(priority
, message
, args
);
404 int main(int argc
, char* argv
[])
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
++) {
415 sprintf(buf
, "Log Line %d\n", i
);
416 syslog((i
% 17) ? LOG_INFO
: LOG_ERR
, buf
);