]> git.ipfire.org Git - people/stevee/guardian.git/blame - guardian
Set default FirewallEngine to "none".
[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
3111df62 30require Guardian::Base;
45bf2a03 31require Guardian::Config;
ccf4f8e1 32require Guardian::Daemon;
e8528a98 33require Guardian::Events;
c95dfa5b 34require Guardian::Logger;
88d9af2c 35require Guardian::Parser;
6abac3d4 36require Guardian::Socket;
88d9af2c 37
5c694317
SS
38use warnings;
39
e02ed027
SS
40# Disable warnings of unjoinded threads when stopping guardian.
41no warnings 'threads';
42
45bf2a03
SS
43# Define version.
44my $version ="2.0";
45
45bf2a03
SS
46# Get and store the given command line arguments in a hash.
47my %cmdargs = ();
48
49&GetOptions (\%cmdargs,
50 'foreground|f',
51 'config|c=s',
52 'help|h',
53 'version|v',
54);
55
56# Show help / version information.
57if (defined($cmdargs{"help"})) {
58 print "Guardian $version \n";
59 print "Usage: guardian <optional arguments>\n";
60 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
61 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
62 print " -h, --help\t\tshows this help\n";
63 print " -v, --version\t\tdisplay programm version and exit.\n";
64 exit;
65} elsif (defined($cmdargs{"version"})) {
66 print "Guardian $version \n";
67 exit;
68}
69
624876cf
SS
70# Check if another instance of guardian is allready running.
71if (&Guardian::Daemon::IsRunning()) {
72 die "Another instance of Guardian is allready running...\n";
73}
74
45bf2a03
SS
75# Read-in the configuration file and store the settings.
76# Push the may be given config file argument.
77my %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
78
c95dfa5b 79# Initialize Logger.
aab61123 80my $logger = Guardian::Logger->Init(%mainsettings);
c95dfa5b
SS
81$logger->Log("debug", "Logger successfully initialized...");
82
fc555263
SS
83# Add the logger object to the mainsettings for passing
84# it to the modules.
85$mainsettings{Logger} = $logger;
86
0815025a
SS
87# Redirect perls "die" messages to the logger before exiting.
88$SIG{__DIE__} = sub { $logger->Log("err", "@_"); };
89
e8528a98
SS
90# Initialize the event handler.
91my $events = Guardian::Events->Init(%mainsettings);
92
3111df62
SS
93# Shared hash between the main process and all threads. It will store all
94# monitored files and their current file position.
95my %monitored_files :shared = ();
96
88d9af2c
SS
97# Create the main queue. It is used to store and process all events which are
98# reported and enqueued by the worker threads.
c0a59a63 99my $queue :shared = new Thread::Queue or die "Could not create new, empty queue. $!";;
88d9af2c 100
9c74e9bb
SS
101# Array to store all currently running worker objects.
102# (Does not include the socket thread)
103my @running_workers;
104
ccf4f8e1
SS
105# Check if guardian should be daemonized or keep in the foreground.
106unless (defined($cmdargs{"foreground"})) {
107 # Fork into background.
108 &Guardian::Daemon::Daemonize();
109} else {
110 # Write PID (process-id).
111 &Guardian::Daemon::WritePID();
112}
113
88d9af2c
SS
114# Call Init function to initzialize guardian.
115&Init();
116
117# Infinite main loop, which processes all queued events.
118while(1) {
119 # Get the amount of elements in our queue.
120 # "undef" will be returned if it is empty.
121 my $current_events = $queue->pending();
122
123 # If there is at least one element enqued
124 if($current_events > 0) {
125 # Grab the data of the top enqueued event.
126 my $event = $queue->peek();
127
c95dfa5b
SS
128 # Log processed event.
129 $logger->Log("debug", "QUEUE - Processed event: $event");
88d9af2c 130
e8528a98
SS
131 # Send event data to the events parser to determine
132 # if any action is required.
133 $events->CheckAction($event);
134
88d9af2c
SS
135 # Drop processed event from queue.
136 $queue->dequeue();
137 }
138
e8528a98
SS
139 # Call RemoveBlocks routine from the Events module to check
140 # if items from the block list can be dropped.
141 $events->RemoveBlocks();
142
01147a7e
SS
143 # Sleep 10ms to reduce the load of the main process.
144 sleep(0.01);
88d9af2c
SS
145}
146
147#
148## Init function.
149#
150## This function contains code which has to be executed while guardian
151## is starting.
152#
153sub Init () {
915d9f45
SS
154 # Setup signal handler.
155 &SignalHandler();
156
6abac3d4
SS
157 # Setup IPC mechanism via Socket in an own thread.
158 threads->create(\&Socket);
159
3111df62
SS
160 # Generate hash of monitored files.
161 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
162
9c74e9bb
SS
163 # Start worker threads.
164 &StartWorkers();
88d9af2c
SS
165}
166
167#
168## Worker function.
169#
170## This function is responsible for monitoring modifications of the given logfile,
171## read them and pass them to the message parser.
172#
173## To get file modifications the inotify subsystem of the linux kernel is used.
174#
175## In order to prevent from permanently read and keep files opened, or dealing
176## with huge logfiles, at initialization time of the worker process, the file will
177## be opened once and the cursor position of the end of file (EOF) get stored. When
178## reading any newly added lines from the file, we directly can jump to the last
179## known position and get these lines. Afterwards, we store the current curser position
180## again, so we can do it in this way over and over again.
181#
182## All read lines get stored in an array, which will be passed to the Parser.
183#
184## If any response (action) from the parser get recieved, it will be put into the
185## shared event queue.
186#
187sub Worker ($) {
9c74e9bb
SS
188 my $file = $_[0];
189
190 # Signal handler to kill worker.
191 $SIG{'KILL'} = sub { threads->exit(); };
88d9af2c 192
88d9af2c 193 # Create inotify watcher.
c0a59a63 194 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!";
88d9af2c
SS
195
196 # Monitor the specified file.
c0a59a63 197 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!";
88d9af2c 198
9c74e9bb
SS
199 # Switch watcher into non-blocking mode.
200 $watcher->blocking(0);
88d9af2c 201
c95dfa5b
SS
202 # Log successfully spawned worker.
203 $logger->Log("debug", "Spawned worker thread for: $file");
204
9c74e9bb
SS
205 # Infinite loop.
206 while(1) {
207 # Check for any events and perform them, if there
208 # is a least one.
209 if ($watcher->read) {
210 my @message = ();
88d9af2c 211
3111df62
SS
212 # Obtain fileposition from hash.
213 my $fileposition = $monitored_files{$file};
214
9c74e9bb 215 # Open the file.
c0a59a63 216 open (FILE, $file) or die "Could not open $file. $!";
88d9af2c 217
9c74e9bb
SS
218 # Seek to the last known position.
219 seek (FILE, $fileposition, 0);
88d9af2c 220
9c74e9bb
SS
221 # Get the log message.
222 while (my $line = <FILE>) {
223 # Remove any newlines.
224 chomp $line;
88d9af2c 225
9c74e9bb
SS
226 # Add all lines to the message array.
227 push (@message, $line);
228 }
88d9af2c 229
3111df62
SS
230 {
231 # Lock shared hash.
232 lock(%monitored_files);
233
234 # Update fileposition.
235 $monitored_files{$file} = tell(FILE);
236 }
88d9af2c 237
9c74e9bb
SS
238 # Close file.
239 close(FILE);
88d9af2c 240
9c74e9bb
SS
241 # Send filename and message to the parser,
242 # which will return if an action has to be performed.
243 my @action = &Guardian::Parser::Parser("$file", @message);
88d9af2c 244
9c74e9bb
SS
245 # Send the action to the main process and put it into
246 # the queue.
247 if (@action) {
248 # Lock the queue.
249 lock($queue);
250
251 # Put the required action into the queue.
252 $queue->enqueue(@action);
253 }
254 } else {
255 # Sleep for 10ms until the next round of the loop will start.
256 sleep(0.01);
88d9af2c
SS
257 }
258 }
259}
260
6abac3d4
SS
261#
262## Socket function.
263#
264## This function uses the Socket module to create and listen to an UNIX socket.
265## It automatically accepts all incomming connections and pass the recieved
266## data messages to the the Message_Parser function which is also part of the
267## socket module.
268#
269## If a valid command has been sent through the socket, the corresponding event
270## will be enqueued into the shared event queue.
271#
272sub Socket () {
273 # Create the Server socket by calling the responsible function.
274 my $server = &Guardian::Socket::Server();
275
c95dfa5b
SS
276 # Log successfull creation of socket.
277 $logger->Log("debug", "Listening to Socket...");
278
6abac3d4
SS
279 # Accept incomming connections from the socket.
280 while (my $connection = $server->accept()) {
281 # Autoflush the socket after the data
282 # has been recieved.
283 $connection->autoflush(1);
284
285 # Gather all data from the connection.
286 while (my $message = <$connection>) {
287 # Remove any newlines.
288 chomp($message);
289
c95dfa5b
SS
290 # Log recieved socket command.
291 $logger->Log("debug", "Socket - Recieved message: $message");
292
6abac3d4
SS
293 # Send the recieved data message to the
294 # socket parser.
295 my $action = &Guardian::Socket::Message_Parser($message);
296
297 # If the parser returns to perform an action,
298 # add it to the main event queue.
299 if ($action) {
300 # Lock the queue.
301 lock($queue);
302
303 # Enqueue the returned action.
304 $queue->enqueue($action);
305 }
306 }
307 }
308}
309
915d9f45
SS
310#
311## Function for capturing process signals.
312#
313## This function captures any sent process signals and will call various
314## actions, basend on the captured signal.
315#
316sub SignalHandler {
317 $SIG{INT} = \&Shutdown;
318 $SIG{TERM} = \&Shutdown;
319 $SIG{QUIT} = \&Shutdown;
ba734c53 320 $SIG{HUP} = \&Reload;
915d9f45
SS
321}
322
9c74e9bb
SS
323#
324## Function to start the workers (threads) for all monitored files.
325#
3111df62 326## This function will loop through the hash of monitored files and will
9c74e9bb
SS
327## spawn an own thread based worker for each file. Every created worker will
328## be added to the array of running workers.
329#
330sub StartWorkers () {
3111df62
SS
331 # Loop through the hash which contains the monitored files and start
332 # a worker thread for each single one.
333 foreach my $file (keys %monitored_files) {
c95dfa5b 334 $logger->Log("debug", "Starting worker thread for $file");
3111df62
SS
335 # Create worker thread for the file.
336 push @running_workers, threads->create(\&Worker,$file);
9c74e9bb
SS
337 }
338}
339
340#
341## Function to stop all running workers.
342#
343## This function is used to stop all currently running workers and will be
344## called when reloading or shutting down guardian.
345#
346sub StopWorkers () {
347 # Loop through all running workers.
348 foreach my $worker (@running_workers) {
349 # Send the worker the "KILL" signal and detach the
350 # thread so perl can do an automatically clean-up.
4d19939e 351 $worker->kill('KILL');
9c74e9bb 352 }
c95dfa5b 353 $logger->Log("debug", "All workers are stopped now...");
9c74e9bb
SS
354}
355
ba734c53
SS
356#
357## Reload function.
358#
359## This function will get called if the signal handler recieves a "SIGHUP" signal,
360## or the reload command will be sent via socket connection. It is responsible for
361## reloading all configure options and stopping/starting the worker threads.
362#
363sub Reload () {
c95dfa5b
SS
364 # Log reload.
365 $logger->Log("info", "Reload configuration...");
366
ba734c53
SS
367 # Stop all running workers.
368 &StopWorkers();
369
370 # Re-read configuration file.
371 %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
372
fc555263 373 # Update Logger settings.
aab61123 374 $logger = Guardian::Logger->Init(%mainsettings);
fc555263
SS
375
376 # Update logger object in mainsettings hash.
377 $mainsettings{Logger} = $logger;
378
ba734c53
SS
379 # Re-generate hash of monitored files.
380 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
381
382 # Restart the worker threads.
383 &StartWorkers();
384}
385
915d9f45
SS
386#
387## Shutdown function.
388#
389## This function is used to do a clean shutdown of guardian. It will be called
390## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
391#
392sub Shutdown () {
c95dfa5b
SS
393 # Log shutdown.
394 $logger->Log("info", "Shutting down...");
395
9c74e9bb
SS
396 # Stop all workers.
397 &StopWorkers();
398
915d9f45
SS
399 # Remove socket file on exit.
400 &Guardian::Socket::RemoveSocketFile();
401
0eb86493
SS
402 # Remove pid file on exit.
403 &Guardian::Daemon::RemovePIDFile();
404
a9ef502c
SS
405 # Sleep for one second to give perl some
406 # time to proper clean up everything before
407 # exiting.
408 sleep(1);
409
c95dfa5b
SS
410 # Log good bye message.
411 $logger->Log("debug", "Good Bye!");
412
915d9f45
SS
413 # Exit guardian.
414 exit;
415}