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