]> git.ipfire.org Git - people/stevee/guardian.git/blame - guardian.in
guardian: Some typo fixes.
[people/stevee/guardian.git] / guardian.in
CommitLineData
88d9af2c
SS
1#!/usr/bin/perl
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
ab7c10eb 5# Copyright (C) 2015-2016 IPFire Development Team #
88d9af2c
SS
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
a2f46a64 40# Disable warnings of unjoined threads when stopping guardian.
e02ed027
SS
41no warnings 'threads';
42
45bf2a03 43# Define version.
72ab6e2a 44my $version ="@PACKAGE_VERSION@";
45bf2a03 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";
a2f46a64 61 print " -f, --foreground\turn in the foreground (doesn't fork, any output goes to STDOUT)\n";
45bf2a03
SS
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()) {
a2f46a64 72 die "Another instance of Guardian is already running...\n";
624876cf
SS
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
cfe5a220
SS
93# Hash to store the currently monitored files and their configured
94# parsers.
95my %monitored_files = ();
96
97# Shared hash between the main process and all threads. It will store the
3111df62 98# monitored files and their current file position.
cfe5a220 99my %file_positions :shared = ();
3111df62 100
88d9af2c
SS
101# Create the main queue. It is used to store and process all events which are
102# reported and enqueued by the worker threads.
c0a59a63 103my $queue :shared = new Thread::Queue or die "Could not create new, empty queue. $!";;
88d9af2c 104
bac2d500 105# Hash to store all currently running worker objects and their corresponding files.
9c74e9bb 106# (Does not include the socket thread)
bac2d500
SS
107my %running_workers;
108
109# Variable to store if the workers should pause or compute.
110my $workers_pause :shared = 0;
9c74e9bb 111
ccf4f8e1
SS
112# Check if guardian should be daemonized or keep in the foreground.
113unless (defined($cmdargs{"foreground"})) {
114 # Fork into background.
115 &Guardian::Daemon::Daemonize();
116} else {
117 # Write PID (process-id).
118 &Guardian::Daemon::WritePID();
119}
120
88d9af2c
SS
121# Call Init function to initzialize guardian.
122&Init();
123
124# Infinite main loop, which processes all queued events.
125while(1) {
126 # Get the amount of elements in our queue.
127 # "undef" will be returned if it is empty.
128 my $current_events = $queue->pending();
129
130 # If there is at least one element enqued
131 if($current_events > 0) {
132 # Grab the data of the top enqueued event.
133 my $event = $queue->peek();
134
c95dfa5b
SS
135 # Log processed event.
136 $logger->Log("debug", "QUEUE - Processed event: $event");
88d9af2c 137
e8528a98
SS
138 # Send event data to the events parser to determine
139 # if any action is required.
140 $events->CheckAction($event);
141
88d9af2c
SS
142 # Drop processed event from queue.
143 $queue->dequeue();
144 }
145
e8528a98
SS
146 # Call RemoveBlocks routine from the Events module to check
147 # if items from the block list can be dropped.
148 $events->RemoveBlocks();
149
01147a7e
SS
150 # Sleep 10ms to reduce the load of the main process.
151 sleep(0.01);
88d9af2c
SS
152}
153
154#
155## Init function.
156#
157## This function contains code which has to be executed while guardian
158## is starting.
159#
160sub Init () {
915d9f45
SS
161 # Setup signal handler.
162 &SignalHandler();
163
6abac3d4
SS
164 # Setup IPC mechanism via Socket in an own thread.
165 threads->create(\&Socket);
166
3111df62
SS
167 # Generate hash of monitored files.
168 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
169
9c74e9bb
SS
170 # Start worker threads.
171 &StartWorkers();
88d9af2c
SS
172}
173
174#
175## Worker function.
176#
177## This function is responsible for monitoring modifications of the given logfile,
178## read them and pass them to the message parser.
179#
180## To get file modifications the inotify subsystem of the linux kernel is used.
181#
182## In order to prevent from permanently read and keep files opened, or dealing
183## with huge logfiles, at initialization time of the worker process, the file will
184## be opened once and the cursor position of the end of file (EOF) get stored. When
185## reading any newly added lines from the file, we directly can jump to the last
a2f46a64 186## known position and get these lines. Afterwards, we store the current cursor position
88d9af2c
SS
187## again, so we can do it in this way over and over again.
188#
189## All read lines get stored in an array, which will be passed to the Parser.
190#
a2f46a64 191## If any response (action) from the parser is received, it will be put into the
88d9af2c
SS
192## shared event queue.
193#
194sub Worker ($) {
9c74e9bb
SS
195 my $file = $_[0];
196
a2f46a64 197 # Obtain the parser name which should be used to parse any
cfe5a220
SS
198 # messages of this file.
199 my $parser = $monitored_files{$file};
200
9c74e9bb
SS
201 # Signal handler to kill worker.
202 $SIG{'KILL'} = sub { threads->exit(); };
88d9af2c 203
88d9af2c 204 # Create inotify watcher.
c0a59a63 205 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!";
88d9af2c
SS
206
207 # Monitor the specified file.
c0a59a63 208 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!";
88d9af2c 209
9c74e9bb
SS
210 # Switch watcher into non-blocking mode.
211 $watcher->blocking(0);
88d9af2c 212
c95dfa5b
SS
213 # Log successfully spawned worker.
214 $logger->Log("debug", "Spawned worker thread for: $file");
215
9c74e9bb
SS
216 # Infinite loop.
217 while(1) {
a2f46a64 218 # Check if the workers should pause or perform their desired work.
bac2d500
SS
219 if ($workers_pause) {
220 # Wait 1 second until the next check.
221 sleep(1);
222 } else {
223 # Check for any events and perform them, if there
224 # is a least one.
225 if ($watcher->read) {
226 my @message = ();
88d9af2c 227
bac2d500
SS
228 # Obtain fileposition from hash.
229 my $fileposition = $file_positions{$file};
88d9af2c 230
bac2d500
SS
231 # Open the file.
232 open (FILE, $file) or die "Could not open $file. $!";
88d9af2c 233
bac2d500
SS
234 # Seek to the last known position.
235 seek (FILE, $fileposition, 0);
88d9af2c 236
bac2d500
SS
237 # Get the log message.
238 while (my $line = <FILE>) {
239 # Remove any newlines.
240 chomp $line;
3111df62 241
bac2d500
SS
242 # Add all lines to the message array.
243 push (@message, $line);
244 }
88d9af2c 245
bac2d500
SS
246 {
247 # Lock shared hash.
248 lock(%file_positions);
88d9af2c 249
bac2d500
SS
250 # Update fileposition.
251 $file_positions{$file} = tell(FILE);
252 }
9c74e9bb 253
bac2d500
SS
254 # Close file.
255 close(FILE);
256
257 # Send filename and message to the parser,
258 # which will return if any actions have to be performed.
259 my @actions = &Guardian::Parser::Parser("$parser", @message);
260
261 # Send the action to the main process and put it into
262 # the queue.
263 if (@actions) {
264 # Lock the queue.
265 lock($queue);
266
267 # Loop through the actions array, and perform
268 # every single action.
269 foreach my $action (@actions) {
270 # Prevent from enqueuing empty actions.
271 if (defined($action)) {
272 # Put the required action into the queue.
273 $queue->enqueue($action);
274 }
43fdb161
SS
275 }
276 }
bac2d500
SS
277 } else {
278 # Sleep for 10ms until the next round of the loop will start.
279 sleep(0.01);
9c74e9bb 280 }
88d9af2c
SS
281 }
282 }
283}
284
6abac3d4
SS
285#
286## Socket function.
287#
288## This function uses the Socket module to create and listen to an UNIX socket.
a2f46a64 289## It automatically accepts all incoming connections and pass the received
6abac3d4
SS
290## data messages to the the Message_Parser function which is also part of the
291## socket module.
292#
293## If a valid command has been sent through the socket, the corresponding event
294## will be enqueued into the shared event queue.
295#
296sub Socket () {
297 # Create the Server socket by calling the responsible function.
6bd7c588 298 my $server = &Guardian::Socket::Server($mainsettings{SocketOwner});
6abac3d4 299
c95dfa5b
SS
300 # Log successfull creation of socket.
301 $logger->Log("debug", "Listening to Socket...");
302
a2f46a64 303 # Accept incoming connections from the socket.
6abac3d4
SS
304 while (my $connection = $server->accept()) {
305 # Autoflush the socket after the data
a2f46a64 306 # has been received.
6abac3d4
SS
307 $connection->autoflush(1);
308
309 # Gather all data from the connection.
310 while (my $message = <$connection>) {
311 # Remove any newlines.
312 chomp($message);
313
a2f46a64 314 # Log received socket command.
c95dfa5b
SS
315 $logger->Log("debug", "Socket - Recieved message: $message");
316
a2f46a64 317 # Send the received data message to the
6abac3d4
SS
318 # socket parser.
319 my $action = &Guardian::Socket::Message_Parser($message);
320
321 # If the parser returns to perform an action,
322 # add it to the main event queue.
323 if ($action) {
324 # Lock the queue.
325 lock($queue);
326
327 # Enqueue the returned action.
328 $queue->enqueue($action);
329 }
330 }
331 }
332}
333
915d9f45
SS
334#
335## Function for capturing process signals.
336#
337## This function captures any sent process signals and will call various
a2f46a64 338## actions, based on the captured signal.
915d9f45
SS
339#
340sub SignalHandler {
341 $SIG{INT} = \&Shutdown;
342 $SIG{TERM} = \&Shutdown;
343 $SIG{QUIT} = \&Shutdown;
ba734c53 344 $SIG{HUP} = \&Reload;
ab7c10eb 345 $SIG{USR1} = \&ReloadIgnoreList;
915d9f45
SS
346}
347
9c74e9bb
SS
348#
349## Function to start the workers (threads) for all monitored files.
350#
3111df62 351## This function will loop through the hash of monitored files and will
9c74e9bb
SS
352## spawn an own thread based worker for each file. Every created worker will
353## be added to the array of running workers.
354#
355sub StartWorkers () {
cfe5a220
SS
356 # Init/Update hash which contains the cursor position of EOF.
357 %file_positions = &Guardian::Base::FilePositions(\%monitored_files, \%file_positions);
358
3111df62
SS
359 # Loop through the hash which contains the monitored files and start
360 # a worker thread for each single one.
361 foreach my $file (keys %monitored_files) {
a2f46a64 362 # Check if an worker is already running for this file.
bac2d500
SS
363 # If not, start the worker.
364 unless (exists($running_workers{$file})) {
365 $logger->Log("debug", "Starting worker thread for $file");
366
367 # Create worker thread for the file.
368 $running_workers{$file} = threads->create(\&Worker,$file);
369 }
9c74e9bb
SS
370 }
371}
372
373#
374## Function to stop all running workers.
375#
376## This function is used to stop all currently running workers and will be
377## called when reloading or shutting down guardian.
378#
379sub StopWorkers () {
380 # Loop through all running workers.
bac2d500
SS
381 foreach my $worker (keys %running_workers) {
382 # Determine if the worker should be stopped.
a2f46a64 383 # This happens if the file should not be longer monitored.
bac2d500
SS
384 unless(exists($monitored_files{$worker})) {
385 $logger->Log("debug", "Stopping worker thread for $worker");
386
387 # Send a "KILL" signal to the worker.
388 $running_workers{$worker}->kill('KILL');
389
390 # Remove worker from hash of running workers.
391 delete($running_workers{$worker});
392 }
9c74e9bb 393 }
bac2d500
SS
394
395 # Get amount of currently running worker threads.
396 if (! keys(%running_workers)) {
397 $logger->Log("debug", "All workers have been stopped...");
398 }
399
400 # Return nothing.
401 return;
402}
403
404#
405## Function to pause all running workers.
406#
407## This function is used to pause all currently running workers.
408#
409sub PauseWorkers() {
410 # Set workers_pause variable to "1".
a2f46a64 411 # All workers will sleep until the variable has been set to "0".
bac2d500
SS
412 $workers_pause = 1;
413
414 # Log paused workers.
415 $logger->Log("debug", "All workers have been paused...");
416
417 # Return nothing.
418 return;
419}
420
421#
422## Function to continue all running workers.
423#
424## This function is used to continue all paused workers.
425#
426sub ResumeWorkers() {
427 # Set workers_suspend variable to "0" - they will continue their work
428 # again.
429 $workers_pause = 0;
430
431 # Log continued workers.
432 $logger->Log("debug", "All workers are working again...");
433
434 # Return nothing.
435 return;
9c74e9bb
SS
436}
437
ba734c53
SS
438#
439## Reload function.
440#
a2f46a64 441## This function will get called if the signal handler receives a "SIGHUP" signal,
ba734c53
SS
442## or the reload command will be sent via socket connection. It is responsible for
443## reloading all configure options and stopping/starting the worker threads.
444#
445sub Reload () {
c95dfa5b
SS
446 # Log reload.
447 $logger->Log("info", "Reload configuration...");
448
bac2d500
SS
449 # Pause all running workers.
450 &PauseWorkers();
ba734c53
SS
451
452 # Re-read configuration file.
453 %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
454
fc555263 455 # Update Logger settings.
aab61123 456 $logger = Guardian::Logger->Init(%mainsettings);
fc555263
SS
457
458 # Update logger object in mainsettings hash.
459 $mainsettings{Logger} = $logger;
460
10442560
SS
461 # Update Event handler.
462 $events->Update(\%mainsettings);
463
ab7c10eb
SS
464 # Update ignore list.
465 &ReloadIgnoreList();
57dc4265 466
ba734c53
SS
467 # Re-generate hash of monitored files.
468 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
469
bac2d500
SS
470 # Stop workers if they are not needed anymore.
471 &StopWorkers();
472
473 # Start new worker threads if required.
ba734c53 474 &StartWorkers();
bac2d500
SS
475
476 # Resume workers.
477 &ResumeWorkers();
478
479 # Return nothing.
480 return;
ba734c53
SS
481}
482
ab7c10eb
SS
483#
484## ReloadIgnoreList function.
485#
a2f46a64 486## This function will be called if the signal handler receives a "SIGUSR1" signal,
ab7c10eb
SS
487## or the reload-ignore-list command will be sent via the socket connection. It just
488## performs a simple check if an ignore file has been configured and calls the responsible
489## function on the events module.
490#
491sub ReloadIgnoreList () {
492 # Update ignore list, if an ignorefile has been specified.
493 if (exists($mainsettings{IgnoreFile})) {
494 # Log reload of the ignore list.
495 $logger->Log("info", "Reloading ignore list...");
496
497 # Call responsible function from the events module.
498 &Guardian::Events::GenerateIgnoreList($mainsettings{IgnoreFile});
499 }
500}
501
648ca493
SS
502#
503## Logrotate function.
504#
505## This function only get called when the logrotate command will be sent via
506## the socket connection. It is responsible for validating and altering the current
a2f46a64 507## cursor positions of the monitored files and stopping/starting the worker threads.
648ca493
SS
508#
509sub Logrotate () {
510 # Stop all running workers.
bac2d500 511 &PauseWorkers();
648ca493
SS
512
513 {
514 # Lock shared hash.
515 lock(%file_positions);
516
517 # Loop through the hash which contains the current
518 # file positions.
519 foreach my $file (keys(%file_positions)) {
520 # Obtain stored value from hash.
521 my $stored_position = $file_positions{$file};
522
523 # Call function to get the current position.
524 my $current_position = &Guardian::Base::GetFileposition($file);
525
526 # Compare if the current position still matches
527 # the stored one.
528 if ($current_position ne $stored_position) {
529 # Update to the new position, because
530 # they has changed during file rotation.
531 $file_positions{$file} = $current_position;
532
533 # Log notice about rotated file.
534 $logger->Log("debug", "$file have been rotated - Using new file position.");
535 }
536 }
537
538 # After this bracket, the lock of the hash will be released.
539 }
540
541 # Restart all worker threads.
bac2d500
SS
542 &ResumeWorkers();
543
544 # Return nothing.
545 return;
648ca493
SS
546}
547
915d9f45
SS
548#
549## Shutdown function.
550#
551## This function is used to do a clean shutdown of guardian. It will be called
a2f46a64 552## by the signal handler when receiving INT (2), QUIT (3) and TERM (15) signals.
915d9f45
SS
553#
554sub Shutdown () {
c95dfa5b
SS
555 # Log shutdown.
556 $logger->Log("info", "Shutting down...");
557
bac2d500
SS
558 # Reset hash of monitored files.
559 %monitored_files = ();
560
9c74e9bb
SS
561 # Stop all workers.
562 &StopWorkers();
563
24f500ae
SS
564 # Unblock all blocked hosts.
565 &Guardian::Events::CallFlush();
566
915d9f45
SS
567 # Remove socket file on exit.
568 &Guardian::Socket::RemoveSocketFile();
569
0eb86493
SS
570 # Remove pid file on exit.
571 &Guardian::Daemon::RemovePIDFile();
572
a9ef502c
SS
573 # Sleep for one second to give perl some
574 # time to proper clean up everything before
575 # exiting.
576 sleep(1);
577
c95dfa5b
SS
578 # Log good bye message.
579 $logger->Log("debug", "Good Bye!");
580
915d9f45
SS
581 # Exit guardian.
582 exit;
583}