Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

471 lines
13 KiB

  1. #
  2. # EventLog.pm
  3. #
  4. # Creates an object oriented interface to the Windows NT Evenlog
  5. # Written by Jesse Dougherty
  6. #
  7. package Win32::EventLog;
  8. use strict;
  9. use vars qw($VERSION $AUTOLOAD @ISA @EXPORT $GetMessageText);
  10. $VERSION = '0.072';
  11. require Exporter;
  12. require DynaLoader;
  13. die "The Win32::Eventlog module works only on Windows NT"
  14. unless Win32::IsWinNT();
  15. @ISA= qw(Exporter DynaLoader);
  16. @EXPORT = qw(
  17. EVENTLOG_AUDIT_FAILURE
  18. EVENTLOG_AUDIT_SUCCESS
  19. EVENTLOG_BACKWARDS_READ
  20. EVENTLOG_END_ALL_PAIRED_EVENTS
  21. EVENTLOG_END_PAIRED_EVENT
  22. EVENTLOG_ERROR_TYPE
  23. EVENTLOG_FORWARDS_READ
  24. EVENTLOG_INFORMATION_TYPE
  25. EVENTLOG_PAIRED_EVENT_ACTIVE
  26. EVENTLOG_PAIRED_EVENT_INACTIVE
  27. EVENTLOG_SEEK_READ
  28. EVENTLOG_SEQUENTIAL_READ
  29. EVENTLOG_START_PAIRED_EVENT
  30. EVENTLOG_SUCCESS
  31. EVENTLOG_WARNING_TYPE
  32. );
  33. $GetMessageText=0;
  34. sub AUTOLOAD {
  35. my($constname);
  36. ($constname = $AUTOLOAD) =~ s/.*:://;
  37. # reset $! to zero to reset any current errors.
  38. $!=0;
  39. my $val = constant($constname, @_ ? $_[0] : 0);
  40. if ($!) {
  41. if ($! =~ /Invalid/) {
  42. $AutoLoader::AUTOLOAD = $AUTOLOAD;
  43. goto &AutoLoader::AUTOLOAD;
  44. }
  45. else {
  46. my ($pack,$file,$line) = caller;
  47. die "Unknown Win32::EventLog macro $constname, at $file line $line.\n";
  48. }
  49. }
  50. eval "sub $AUTOLOAD { $val }";
  51. goto &$AUTOLOAD;
  52. }
  53. #
  54. # new()
  55. #
  56. # Win32::EventLog->new("source name", "ServerName");
  57. #
  58. sub new {
  59. die "usage: PACKAGE->new(SOURCENAME[, SERVERNAME])\n" unless @_ > 1;
  60. my ($class,$source,$server) = @_;
  61. my $handle;
  62. # Create new handle
  63. if ($source !~ /\\/) {
  64. OpenEventLog($handle, $server, $source);
  65. }
  66. else {
  67. OpenBackupEventLog($handle, $server, $source);
  68. }
  69. return bless {handle => $handle,
  70. Source => $source,
  71. Computer => $server} => $class;
  72. }
  73. sub DESTROY {shift->Close}
  74. #
  75. # Open (the rather braindead old way)
  76. # A variable initialized to empty must be supplied as the first
  77. # arg, followed by whatever new() takes
  78. #
  79. sub Open {
  80. $_[0] = Win32::EventLog->new($_[1],$_[2]);
  81. }
  82. sub OpenBackup {
  83. my ($class,$source,$server) = @_;
  84. OpenBackupEventLog(my $handle, $server, $source);
  85. return bless {handle => $handle,
  86. Source => $source,
  87. Computer => $server} => $class;
  88. }
  89. sub Backup {
  90. die " usage: OBJECT->Backup(FILENAME)\n" unless @_ == 2;
  91. my ($self,$file) = @_;
  92. return BackupEventLog($self->{handle}, $file);
  93. }
  94. sub Close {
  95. my $self = shift;
  96. CloseEventLog($self->{handle});
  97. $self->{handle} = 0;
  98. }
  99. # Read
  100. # Note: the EventInfo arguement requires a hash reference.
  101. sub Read {
  102. my $self = shift;
  103. die "usage: OBJECT->Read(FLAGS, RECORDOFFSET, HASHREF)\n" unless @_ == 3;
  104. my ($readflags,$recordoffset) = @_;
  105. # The following is stolen shamelessly from Wyt's tests for the registry.
  106. my $result = ReadEventLog($self->{handle}, $readflags, $recordoffset,
  107. my $header, my $source, my $computer, my $sid,
  108. my $data, my $strings);
  109. my ($length,
  110. $reserved,
  111. $recordnumber,
  112. $timegenerated,
  113. $timewritten,
  114. $eventid,
  115. $eventtype,
  116. $numstrings,
  117. $eventcategory,
  118. $reservedflags,
  119. $closingrecordnumber,
  120. $stringoffset,
  121. $usersidlength,
  122. $usersidoffset,
  123. $datalength,
  124. $dataoffset) = unpack('l6s4l6', $header);
  125. # make a hash out of the values returned from ReadEventLog.
  126. my %h = ( Source => $source,
  127. Computer => $computer,
  128. Length => $datalength,
  129. Category => $eventcategory,
  130. RecordNumber => $recordnumber,
  131. TimeGenerated => $timegenerated,
  132. Timewritten => $timewritten,
  133. EventID => $eventid,
  134. EventType => $eventtype,
  135. ClosingRecordNumber => $closingrecordnumber,
  136. User => $sid,
  137. Strings => $strings,
  138. Data => $data,
  139. );
  140. # get the text message here
  141. if ($result and $GetMessageText) {
  142. GetEventLogText($source, $eventid, $strings, $numstrings, my $message);
  143. $h{Message} = $message;
  144. }
  145. if (ref($_[2]) eq 'HASH') {
  146. %{$_[2]} = %h; # this needed for Read(...,\%foo) case
  147. }
  148. else {
  149. $_[2] = \%h;
  150. }
  151. return $result;
  152. }
  153. sub GetMessageText {
  154. my $self = shift;
  155. local $^W;
  156. GetEventLogText($self->{Source},
  157. $self->{EventID},
  158. $self->{Strings},
  159. $self->{Strings} =~ tr/\0/\0/,
  160. my $message);
  161. $self->{Message} = $message;
  162. return $message;
  163. }
  164. sub Report {
  165. die "usage: OBJECT->Report( HASHREF )\n" unless @_ == 2;
  166. my ($self,$EventInfo) = @_;
  167. die "Win32::EventLog::Report requires a hash reference as arg 2\n"
  168. unless ref($EventInfo) eq "HASH";
  169. my $computer = $EventInfo->{Computer} ? $EventInfo->{Computer}
  170. : $self->{Computer};
  171. my $source = exists($EventInfo->{Source}) ? $EventInfo->{Source}
  172. : $self->{Source};
  173. return WriteEventLog($computer, $source, $EventInfo->{EventType},
  174. $EventInfo->{Category}, $EventInfo->{EventID},
  175. $EventInfo->{Data}, split(/\0/, $EventInfo->{Strings}));
  176. }
  177. sub GetOldest {
  178. my $self = shift;
  179. die "usage: OBJECT->GetOldest( SCALAREF )\n" unless @_ == 1;
  180. return GetOldestEventLogRecord($self->{handle},$_[0]);
  181. }
  182. sub GetNumber {
  183. my $self = shift;
  184. die "usage: OBJECT->GetNumber( SCALARREF )\n" unless @_ == 1;
  185. return GetNumberOfEventLogRecords($self->{handle}, $_[0]);
  186. }
  187. sub Clear {
  188. my ($self,$file) = @_;
  189. die "usage: OBJECT->Clear( FILENAME )\n" unless @_ == 2;
  190. return ClearEventLog($self->{handle}, $file);
  191. }
  192. bootstrap Win32::EventLog;
  193. 1;
  194. __END__
  195. =head1 NAME
  196. Win32::EventLog - Process Win32 Event Logs from Perl
  197. =head1 SYNOPSIS
  198. use Win32::EventLog
  199. $handle=Win32::EventLog->new("Application");
  200. =head1 DESCRIPTION
  201. This module implements most of the functionality available from the
  202. Win32 API for accessing and manipulating Win32 Event Logs. The access
  203. to the EventLog routines is divided into those that relate to an
  204. EventLog object and its associated methods and those that relate other
  205. EventLog tasks (like adding an EventLog record).
  206. =head1 The EventLog Object and its Methods
  207. The following methods are available to open, read, close and backup
  208. EventLogs.
  209. =over 4
  210. =item Win32::EventLog->new(SOURCENAME [,SERVERNAME]);
  211. The new() method creates a new EventLog object and returns a handle
  212. to it. This hande is then used to call the methods below.
  213. The method is overloaded in that if the supplied SOURCENAME
  214. argument contains one or more literal '\' characters (an illegal
  215. character in a SOURCENAME), it assumes that you are trying to open
  216. a backup eventlog and uses SOURCENAME as the backup eventlog to
  217. open. Note that when opening a backup eventlog, the SERVERNAME
  218. argument is ignored (as it is in the underlying Win32 API). For
  219. EventLogs on remote machines, the SOURCENAME parameter must
  220. therefore be specified as a UNC path.
  221. =item $handle->Backup(FILENAME);
  222. The Backup() method backs up the EventLog represented by $handle. It
  223. takes a single arguemt, FILENAME. When $handle represents an
  224. EventLog on a remote machine, FILENAME is filename on the remote
  225. machine and cannot be a UNC path (i.e you must use F<C:\TEMP\App.EVT>).
  226. The method will fail if the log file already exists.
  227. =item $handle->Read(FLAGS, OFFSET, HASHREF);
  228. The Read() method read an EventLog entry from the EventLog represented
  229. by $handle.
  230. =item $handle->Close();
  231. The Close() method closes the EventLog represented by $handle. After
  232. Close() has been called, any further attempt to use the EventLog
  233. represented by $handle will fail.
  234. =item $handle->GetOldest(SCALARREF);
  235. The GetOldest() method number of the the oldest EventLog record in
  236. the EventLog represented by $handle. This is required to correctly
  237. compute the OFFSET required by the Read() method.
  238. =item $handle->GetNumber(SCALARREF);
  239. The GetNumber() method returns the number of EventLog records in
  240. the EventLog represented by $handle. The number of the most recent
  241. record in the EventLog is therefore computed by
  242. $handle->GetOldest($oldest);
  243. $handle->GetNumber($lastRec);
  244. $lastRecOffset=$oldest+$lastRec;
  245. =item $handle->Clear(FILENAME);
  246. The Clear() method clears the EventLog represented by $handle. If
  247. you provide a non-null FILENAME, the EventLog will be backed up
  248. into FILENAME before the EventLog is cleared. The method will fail
  249. if FILENAME is specified and the file refered to exists. Note also
  250. that FILENAME specifies a file local to the machine on which the
  251. EventLog resides and cannot be specified as a UNC name.
  252. =item $handle->Report(HASHREF);
  253. The Report() method generates an EventLog entry. The HASHREF should
  254. contain the following keys:
  255. =over 4
  256. =item C<Computer>
  257. The C<Computer> field specfies which computer you want the EventLog
  258. entry recorded. If this key doesn't exist, the server name used to
  259. create the $handle is used.
  260. =item C<Source>
  261. The C<Source> field specifies the source that generated the EventLog
  262. entry. If this key doesn't exist, the source name used to create the
  263. $handle is used.
  264. =item C<EventType>
  265. The C<EventType> field should be one of the constants
  266. =over 4
  267. =item C<EVENTLOG_ERROR_TYPE>
  268. An Error event is being logged.
  269. =item C<EVENTLOG_WARNING_TYPE>
  270. A Warning event is being logged.
  271. =item C<EVENTLOG_INFORMATION_TYPE>
  272. An Information event is being logged.
  273. =item C<EVENTLOG_AUDIT_SUCCESS>
  274. A Success Audit event is being logged (typically in the Security
  275. EventLog).
  276. =item C<EVENTLOG_AUDIT_FAILURE>
  277. A Failure Audit event is being logged (typically in the Security
  278. EventLog).
  279. =back
  280. These constants are exported into the main namespace by default.
  281. =item C<Category>
  282. The C<Category> field can have any value you want. It is specific to
  283. the particular Source.
  284. =item C<EventID>
  285. The C<EventID> field should contain the ID of the message that this
  286. event pertains too. This assumes that you have an associated message
  287. file (indirectly referenced by the field C<Source>).
  288. =item C<Data>
  289. The C<Data> field contains raw data associated with this event.
  290. =item C<Strings>
  291. The C<Strings> field contains the single string that itself contains
  292. NUL terminated sub-strings. This are used with the EventID to generate
  293. the message as seen from (for example) the Event Viewer application.
  294. =back
  295. =back
  296. =head1 Other Win32::EventLog functions.
  297. The following functions are part of the Win32::EventLog package but
  298. are not callable from an EventLog object.
  299. =over 4
  300. =item GetMessageText(HASHREF);
  301. The GetMessageText() function assumes that HASHREF was obtained by
  302. a call to C<$handle-E<gt>Read()>. It returns the formatted string that
  303. represents the fully resolved text of the EventLog message (such as
  304. would be seen in the Windows NT Event Viewer). For convenience, the
  305. key 'Message' in the supplied HASHREF is also set to the return value
  306. of this function.
  307. If you set the variable $Win32::EventLog::GetMessageText to 1 then
  308. each call to C<$handle-E<gt>Read()> will call this function automatically.
  309. =back
  310. =head1 Example 1
  311. The following example illustrates the way in which the EventLog module
  312. can be used. It opens the System EventLog and reads through it from
  313. oldest to newest records. For each record from the B<Source> EventLog
  314. it extracts the full text of the Entry and prints the EventLog message
  315. text out.
  316. use Win32::EventLog;
  317. $handle=Win32::EventLog->new("System", $ENV{ComputerName})
  318. or die "Can't open Application EventLog\n";
  319. $handle->GetNumber($recs)
  320. or die "Can't get number of EventLog records\n";
  321. $handle->GetOldest($base)
  322. or die "Can't get number of oldest EventLog record\n";
  323. while ($x < $recs) {
  324. $handle->Read(EVENTLOG_FORWARDS_READ|EVENTLOG_SEEK_READ,
  325. $base+$x,
  326. $hashRef)
  327. or die "Can't read EventLog entry #$x\n";
  328. if ($hashRef->{Source} eq "EventLog") {
  329. Win32::EventLog::GetMessageText($hashRef);
  330. print "Entry $x: $hashRef->{Message}\n";
  331. }
  332. $x++;
  333. }
  334. =head1 Example 2
  335. To backup and clear the EventLogs on a remote machine, do the following :-
  336. use Win32::EventLog;
  337. $myServer="\\\\my-server"; # your servername here.
  338. my($date)=join("-", ((split(/\s+/, scalar(localtime)))[0,1,2,4]));
  339. my($dest);
  340. for my $eventLog ("Application", "System", "Security") {
  341. $handle=Win32::EventLog->new($eventLog, $myServer)
  342. or die "Can't open Application EventLog on $myServer\n";
  343. $dest="C:\\BackupEventLogs\\$eventLog\\$date.evt";
  344. $handle->Backup($dest)
  345. or warn "Could not backup and clear the $eventLog EventLog on $myServer ($^E)\n";
  346. $handle->Close;
  347. }
  348. Note that only the Clear method is required. Note also that if the
  349. file $dest exists, the function will fail.
  350. =head1 BUGS
  351. None currently known.
  352. The test script for 'make test' should be re-written to use the
  353. EventLog object.
  354. =head1 AUTHOR
  355. Original code by Jesse Dougherty for HiP Communications. Additional
  356. fixes and updates attributed to Martin Pauley
  357. <[email protected]>) and Bret Giddings (bret@essex.ac.uk).