Use TimeHires core module for main loop interupting.
[people/stevee/guardian.git] / guardian
CommitLineData
88d9af2c
SS
1#!/usr/bin/perl
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
5# Copyright (C) 2015 IPFire Development Team #
6# #
7# This program is free software: you can redistribute it and/or modify #
8# it under the terms of the GNU General Public License as published by #
9# the Free Software Foundation, either version 3 of the License, or #
10# (at your option) any later version. #
11# #
12# This program is distributed in the hope that it will be useful, #
13# but WITHOUT ANY WARRANTY; without even the implied warranty of #
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15# GNU General Public License for more details. #
16# #
17# You should have received a copy of the GNU General Public License #
18# along with this program. If not, see <http://www.gnu.org/licenses/>. #
19# #
20###############################################################################
21
22use strict;
23use threads;
24use threads::shared;
45bf2a03 25use Getopt::Long;
88d9af2c
SS
26use Thread::Queue;
27use Linux::Inotify2;
01147a7e 28use Time::HiRes qw[ time sleep ];
88d9af2c 29
45bf2a03 30require Guardian::Config;
88d9af2c 31require Guardian::Parser;
6abac3d4 32require Guardian::Socket;
88d9af2c 33
45bf2a03
SS
34# Define version.
35my $version ="2.0";
36
88d9af2c
SS
37# Array to store the monitored logfiles.
38my @monitored_files = (
39 "/var/log/snort/alert",
40);
41
45bf2a03
SS
42# Get and store the given command line arguments in a hash.
43my %cmdargs = ();
44
45&GetOptions (\%cmdargs,
46 'foreground|f',
47 'config|c=s',
48 'help|h',
49 'version|v',
50);
51
52# Show help / version information.
53if (defined($cmdargs{"help"})) {
54 print "Guardian $version \n";
55 print "Usage: guardian <optional arguments>\n";
56 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
57 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
58 print " -h, --help\t\tshows this help\n";
59 print " -v, --version\t\tdisplay programm version and exit.\n";
60 exit;
61} elsif (defined($cmdargs{"version"})) {
62 print "Guardian $version \n";
63 exit;
64}
65
66# Read-in the configuration file and store the settings.
67# Push the may be given config file argument.
68my %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
69
88d9af2c
SS
70# Create the main queue. It is used to store and process all events which are
71# reported and enqueued by the worker threads.
72my $queue :shared = new Thread::Queue or die "Could not create new, empty queue. $!\n";;
73
74# Call Init function to initzialize guardian.
75&Init();
76
77# Infinite main loop, which processes all queued events.
78while(1) {
79 # Get the amount of elements in our queue.
80 # "undef" will be returned if it is empty.
81 my $current_events = $queue->pending();
82
83 # If there is at least one element enqued
84 if($current_events > 0) {
85 # Grab the data of the top enqueued event.
86 my $event = $queue->peek();
87
88 print "Got event: $event\n";
89
90 # Drop processed event from queue.
91 $queue->dequeue();
92 }
93
01147a7e
SS
94 # Sleep 10ms to reduce the load of the main process.
95 sleep(0.01);
88d9af2c
SS
96}
97
98#
99## Init function.
100#
101## This function contains code which has to be executed while guardian
102## is starting.
103#
104sub Init () {
915d9f45
SS
105 # Setup signal handler.
106 &SignalHandler();
107
6abac3d4
SS
108 # Setup IPC mechanism via Socket in an own thread.
109 threads->create(\&Socket);
110
88d9af2c
SS
111 # Loop through the array of which files should be monitored and
112 # create a worker thread for each single one.
113 foreach my $monitored_file (@monitored_files) {
114 # Check if the file exists and is readable.
115 if (-r "$monitored_file") {
116 # Create worker thread for the file.
117 threads->create(\&Worker,$monitored_file);
118 }
119 }
120}
121
122#
123## Worker function.
124#
125## This function is responsible for monitoring modifications of the given logfile,
126## read them and pass them to the message parser.
127#
128## To get file modifications the inotify subsystem of the linux kernel is used.
129#
130## In order to prevent from permanently read and keep files opened, or dealing
131## with huge logfiles, at initialization time of the worker process, the file will
132## be opened once and the cursor position of the end of file (EOF) get stored. When
133## reading any newly added lines from the file, we directly can jump to the last
134## known position and get these lines. Afterwards, we store the current curser position
135## again, so we can do it in this way over and over again.
136#
137## All read lines get stored in an array, which will be passed to the Parser.
138#
139## If any response (action) from the parser get recieved, it will be put into the
140## shared event queue.
141#
142sub Worker ($) {
143 my $file = @_[0];
144
145 # Get the fileposition.
146 my $fileposition = &Init_fileposition("$file");
147
148 # Create inotify watcher.
149 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!\n";
150
151 # Monitor the specified file.
152 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!\n";
153
154 # Get all notifications.
155 while ($watcher->read) {
156 my @message = ();
157
158 # Open the file.
159 open (FILE, $file) or die "Could not open $file. $!\n";
160
161 # Seek to the last known position.
162 seek (FILE, $fileposition, 0);
163
164 # Get the log message.
165 while (my $line = <FILE>) {
166 # Remove any newlines.
167 chomp $line;
168
169 # Add all lines to the message array.
170 push (@message, $line);
171 }
172
173 # Update fileposition.
174 $fileposition = tell(FILE);
175
176 # Close file.
177 close(FILE);
178
179 # Send filename and message to the parser,
180 # which will return if an action has to be performed.
181 my @action = &Guardian::Parser::Parser("$file", @message);
182
183 # Send the action to the main process and put it into
184 # the queue.
185 if (@action) {
186 # Lock the queue.
187 lock($queue);
188
189 # Put the required action into the queue.
190 $queue->enqueue(@action);
191 }
192 }
193}
194
6abac3d4
SS
195#
196## Socket function.
197#
198## This function uses the Socket module to create and listen to an UNIX socket.
199## It automatically accepts all incomming connections and pass the recieved
200## data messages to the the Message_Parser function which is also part of the
201## socket module.
202#
203## If a valid command has been sent through the socket, the corresponding event
204## will be enqueued into the shared event queue.
205#
206sub Socket () {
207 # Create the Server socket by calling the responsible function.
208 my $server = &Guardian::Socket::Server();
209
210 # Accept incomming connections from the socket.
211 while (my $connection = $server->accept()) {
212 # Autoflush the socket after the data
213 # has been recieved.
214 $connection->autoflush(1);
215
216 # Gather all data from the connection.
217 while (my $message = <$connection>) {
218 # Remove any newlines.
219 chomp($message);
220
221 # Send the recieved data message to the
222 # socket parser.
223 my $action = &Guardian::Socket::Message_Parser($message);
224
225 # If the parser returns to perform an action,
226 # add it to the main event queue.
227 if ($action) {
228 # Lock the queue.
229 lock($queue);
230
231 # Enqueue the returned action.
232 $queue->enqueue($action);
233 }
234 }
235 }
236}
237
88d9af2c
SS
238#
239## Function for fileposition initialization.
240#
241## This function is used to get the cursor position of the end of file (EOF) of
242## a specified file.
243#
244## In order to prevent from permanently read and keep files opened, or dealing
245## with huge logfiles, at initialization time of the worker processes, the file will
246## be opened once and the cursor position of the end of file (EOF) get stored.
247#
248sub Init_fileposition ($) {
249 my $file = $_[0];
250
251 # Open the file.
252 open(FILE, $file) or die "Could not open $file. $!\n";
253
254 # Just seek to the end of the file (EOF).
255 seek(FILE, 0, 2);
256
257 # Get and store the position.
258 my $position = tell(FILE),
259
260 # Close the file again.
261 close(FILE);
262
263 # Return the position.
264 return $position;
265}
915d9f45
SS
266
267#
268## Function for capturing process signals.
269#
270## This function captures any sent process signals and will call various
271## actions, basend on the captured signal.
272#
273sub SignalHandler {
274 $SIG{INT} = \&Shutdown;
275 $SIG{TERM} = \&Shutdown;
276 $SIG{QUIT} = \&Shutdown;
277}
278
279#
280## Shutdown function.
281#
282## This function is used to do a clean shutdown of guardian. It will be called
283## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
284#
285sub Shutdown () {
286 # Remove socket file on exit.
287 &Guardian::Socket::RemoveSocketFile();
288
289 # Exit guardian.
290 exit;
291}