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