]> git.ipfire.org Git - people/stevee/guardian.git/blame - guardian
Drop function for fileposition initialization.
[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
5c694317
SS
34use warnings;
35
45bf2a03
SS
36# Define version.
37my $version ="2.0";
38
88d9af2c
SS
39# Array to store the monitored logfiles.
40my @monitored_files = (
41 "/var/log/snort/alert",
42);
43
45bf2a03
SS
44# Get and store the given command line arguments in a hash.
45my %cmdargs = ();
46
47&GetOptions (\%cmdargs,
48 'foreground|f',
49 'config|c=s',
50 'help|h',
51 'version|v',
52);
53
54# Show help / version information.
55if (defined($cmdargs{"help"})) {
56 print "Guardian $version \n";
57 print "Usage: guardian <optional arguments>\n";
58 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
59 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
60 print " -h, --help\t\tshows this help\n";
61 print " -v, --version\t\tdisplay programm version and exit.\n";
62 exit;
63} elsif (defined($cmdargs{"version"})) {
64 print "Guardian $version \n";
65 exit;
66}
67
68# Read-in the configuration file and store the settings.
69# Push the may be given config file argument.
70my %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
71
88d9af2c
SS
72# Create the main queue. It is used to store and process all events which are
73# reported and enqueued by the worker threads.
74my $queue :shared = new Thread::Queue or die "Could not create new, empty queue. $!\n";;
75
9c74e9bb
SS
76# Array to store all currently running worker objects.
77# (Does not include the socket thread)
78my @running_workers;
79
88d9af2c
SS
80# Call Init function to initzialize guardian.
81&Init();
82
83# Infinite main loop, which processes all queued events.
84while(1) {
85 # Get the amount of elements in our queue.
86 # "undef" will be returned if it is empty.
87 my $current_events = $queue->pending();
88
89 # If there is at least one element enqued
90 if($current_events > 0) {
91 # Grab the data of the top enqueued event.
92 my $event = $queue->peek();
93
94 print "Got event: $event\n";
95
96 # Drop processed event from queue.
97 $queue->dequeue();
98 }
99
01147a7e
SS
100 # Sleep 10ms to reduce the load of the main process.
101 sleep(0.01);
88d9af2c
SS
102}
103
104#
105## Init function.
106#
107## This function contains code which has to be executed while guardian
108## is starting.
109#
110sub Init () {
915d9f45
SS
111 # Setup signal handler.
112 &SignalHandler();
113
6abac3d4
SS
114 # Setup IPC mechanism via Socket in an own thread.
115 threads->create(\&Socket);
116
9c74e9bb
SS
117 # Start worker threads.
118 &StartWorkers();
88d9af2c
SS
119}
120
121#
122## Worker function.
123#
124## This function is responsible for monitoring modifications of the given logfile,
125## read them and pass them to the message parser.
126#
127## To get file modifications the inotify subsystem of the linux kernel is used.
128#
129## In order to prevent from permanently read and keep files opened, or dealing
130## with huge logfiles, at initialization time of the worker process, the file will
131## be opened once and the cursor position of the end of file (EOF) get stored. When
132## reading any newly added lines from the file, we directly can jump to the last
133## known position and get these lines. Afterwards, we store the current curser position
134## again, so we can do it in this way over and over again.
135#
136## All read lines get stored in an array, which will be passed to the Parser.
137#
138## If any response (action) from the parser get recieved, it will be put into the
139## shared event queue.
140#
141sub Worker ($) {
9c74e9bb
SS
142 my $file = $_[0];
143
144 # Signal handler to kill worker.
145 $SIG{'KILL'} = sub { threads->exit(); };
88d9af2c
SS
146
147 # Get the fileposition.
148 my $fileposition = &Init_fileposition("$file");
149
150 # Create inotify watcher.
151 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!\n";
152
153 # Monitor the specified file.
154 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!\n";
155
9c74e9bb
SS
156 # Switch watcher into non-blocking mode.
157 $watcher->blocking(0);
88d9af2c 158
9c74e9bb
SS
159 # Infinite loop.
160 while(1) {
161 # Check for any events and perform them, if there
162 # is a least one.
163 if ($watcher->read) {
164 my @message = ();
88d9af2c 165
9c74e9bb
SS
166 # Open the file.
167 open (FILE, $file) or die "Could not open $file. $!\n";
88d9af2c 168
9c74e9bb
SS
169 # Seek to the last known position.
170 seek (FILE, $fileposition, 0);
88d9af2c 171
9c74e9bb
SS
172 # Get the log message.
173 while (my $line = <FILE>) {
174 # Remove any newlines.
175 chomp $line;
88d9af2c 176
9c74e9bb
SS
177 # Add all lines to the message array.
178 push (@message, $line);
179 }
88d9af2c 180
9c74e9bb
SS
181 # Update fileposition.
182 $fileposition = tell(FILE);
88d9af2c 183
9c74e9bb
SS
184 # Close file.
185 close(FILE);
88d9af2c 186
9c74e9bb
SS
187 # Send filename and message to the parser,
188 # which will return if an action has to be performed.
189 my @action = &Guardian::Parser::Parser("$file", @message);
88d9af2c 190
9c74e9bb
SS
191 # Send the action to the main process and put it into
192 # the queue.
193 if (@action) {
194 # Lock the queue.
195 lock($queue);
196
197 # Put the required action into the queue.
198 $queue->enqueue(@action);
199 }
200 } else {
201 # Sleep for 10ms until the next round of the loop will start.
202 sleep(0.01);
88d9af2c
SS
203 }
204 }
205}
206
6abac3d4
SS
207#
208## Socket function.
209#
210## This function uses the Socket module to create and listen to an UNIX socket.
211## It automatically accepts all incomming connections and pass the recieved
212## data messages to the the Message_Parser function which is also part of the
213## socket module.
214#
215## If a valid command has been sent through the socket, the corresponding event
216## will be enqueued into the shared event queue.
217#
218sub Socket () {
219 # Create the Server socket by calling the responsible function.
220 my $server = &Guardian::Socket::Server();
221
222 # Accept incomming connections from the socket.
223 while (my $connection = $server->accept()) {
224 # Autoflush the socket after the data
225 # has been recieved.
226 $connection->autoflush(1);
227
228 # Gather all data from the connection.
229 while (my $message = <$connection>) {
230 # Remove any newlines.
231 chomp($message);
232
233 # Send the recieved data message to the
234 # socket parser.
235 my $action = &Guardian::Socket::Message_Parser($message);
236
237 # If the parser returns to perform an action,
238 # add it to the main event queue.
239 if ($action) {
240 # Lock the queue.
241 lock($queue);
242
243 # Enqueue the returned action.
244 $queue->enqueue($action);
245 }
246 }
247 }
248}
249
915d9f45
SS
250#
251## Function for capturing process signals.
252#
253## This function captures any sent process signals and will call various
254## actions, basend on the captured signal.
255#
256sub SignalHandler {
257 $SIG{INT} = \&Shutdown;
258 $SIG{TERM} = \&Shutdown;
259 $SIG{QUIT} = \&Shutdown;
260}
261
9c74e9bb
SS
262#
263## Function to start the workers (threads) for all monitored files.
264#
265## This function will loop through the array of monitored files and will
266## spawn an own thread based worker for each file. Every created worker will
267## be added to the array of running workers.
268#
269sub StartWorkers () {
270 # Loop through the array of which files should be monitored and
271 # create a worker thread for each single one.
272 foreach my $monitored_file (@monitored_files) {
273 # Check if the file exists and is readable.
274 if (-r "$monitored_file") {
275 # Create worker thread for the file.
276 push @running_workers, threads->create(\&Worker,$monitored_file);
277 }
278 }
279}
280
281#
282## Function to stop all running workers.
283#
284## This function is used to stop all currently running workers and will be
285## called when reloading or shutting down guardian.
286#
287sub StopWorkers () {
288 # Loop through all running workers.
289 foreach my $worker (@running_workers) {
290 # Send the worker the "KILL" signal and detach the
291 # thread so perl can do an automatically clean-up.
292 $worker->kill('KILL')->detach();
293 }
294}
295
915d9f45
SS
296#
297## Shutdown function.
298#
299## This function is used to do a clean shutdown of guardian. It will be called
300## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
301#
302sub Shutdown () {
9c74e9bb
SS
303 # Stop all workers.
304 &StopWorkers();
305
915d9f45
SS
306 # Remove socket file on exit.
307 &Guardian::Socket::RemoveSocketFile();
308
309 # Exit guardian.
310 exit;
311}