]>
git.ipfire.org Git - people/stevee/guardian.git/blob - guardian
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2015 IPFire Development Team #
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. #
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. #
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/>. #
20 ###############################################################################
28 use Time
::HiRes qw
[ time sleep ];
30 require Guardian
::Base
;
31 require Guardian
::Config
;
32 require Guardian
::Parser
;
33 require Guardian
::Socket
;
37 # Disable warnings of unjoinded threads when stopping guardian.
38 no warnings
'threads';
43 # Get and store the given command line arguments in a hash.
46 &GetOptions
(\
%cmdargs,
53 # Show help / version information.
54 if (defined($cmdargs{"help"})) {
55 print "Guardian $version \n";
56 print "Usage: guardian <optional arguments>\n";
57 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
58 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
59 print " -h, --help\t\tshows this help\n";
60 print " -v, --version\t\tdisplay programm version and exit.\n";
62 } elsif (defined($cmdargs{"version"})) {
63 print "Guardian $version \n";
67 # Read-in the configuration file and store the settings.
68 # Push the may be given config file argument.
69 my %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
71 # Shared hash between the main process and all threads. It will store all
72 # monitored files and their current file position.
73 my %monitored_files :shared
= ();
75 # Create the main queue. It is used to store and process all events which are
76 # reported and enqueued by the worker threads.
77 my $queue :shared
= new Thread
::Queue
or die "Could not create new, empty queue. $!\n";;
79 # Array to store all currently running worker objects.
80 # (Does not include the socket thread)
83 # Call Init function to initzialize guardian.
86 # Infinite main loop, which processes all queued events.
88 # Get the amount of elements in our queue.
89 # "undef" will be returned if it is empty.
90 my $current_events = $queue->pending();
92 # If there is at least one element enqued
93 if($current_events > 0) {
94 # Grab the data of the top enqueued event.
95 my $event = $queue->peek();
97 print "Got event: $event\n";
99 # Drop processed event from queue.
103 # Sleep 10ms to reduce the load of the main process.
110 ## This function contains code which has to be executed while guardian
114 # Setup signal handler.
117 # Setup IPC mechanism via Socket in an own thread.
118 threads
->create(\
&Socket
);
120 # Generate hash of monitored files.
121 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
123 # Start worker threads.
130 ## This function is responsible for monitoring modifications of the given logfile,
131 ## read them and pass them to the message parser.
133 ## To get file modifications the inotify subsystem of the linux kernel is used.
135 ## In order to prevent from permanently read and keep files opened, or dealing
136 ## with huge logfiles, at initialization time of the worker process, the file will
137 ## be opened once and the cursor position of the end of file (EOF) get stored. When
138 ## reading any newly added lines from the file, we directly can jump to the last
139 ## known position and get these lines. Afterwards, we store the current curser position
140 ## again, so we can do it in this way over and over again.
142 ## All read lines get stored in an array, which will be passed to the Parser.
144 ## If any response (action) from the parser get recieved, it will be put into the
145 ## shared event queue.
150 # Signal handler to kill worker.
151 $SIG{'KILL'} = sub { threads
->exit(); };
153 # Create inotify watcher.
154 my $watcher = new Linux
::Inotify2
or die "Could not use inotify. $!\n";
156 # Monitor the specified file.
157 $watcher->watch("$file", IN_MODIFY
) or die "Could not monitor $file. $!\n";
159 # Switch watcher into non-blocking mode.
160 $watcher->blocking(0);
164 # Check for any events and perform them, if there
166 if ($watcher->read) {
169 # Obtain fileposition from hash.
170 my $fileposition = $monitored_files{$file};
173 open (FILE
, $file) or die "Could not open $file. $!\n";
175 # Seek to the last known position.
176 seek (FILE
, $fileposition, 0);
178 # Get the log message.
179 while (my $line = <FILE
>) {
180 # Remove any newlines.
183 # Add all lines to the message array.
184 push (@message, $line);
189 lock(%monitored_files);
191 # Update fileposition.
192 $monitored_files{$file} = tell(FILE
);
198 # Send filename and message to the parser,
199 # which will return if an action has to be performed.
200 my @action = &Guardian
::Parser
::Parser
("$file", @message);
202 # Send the action to the main process and put it into
208 # Put the required action into the queue.
209 $queue->enqueue(@action);
212 # Sleep for 10ms until the next round of the loop will start.
221 ## This function uses the Socket module to create and listen to an UNIX socket.
222 ## It automatically accepts all incomming connections and pass the recieved
223 ## data messages to the the Message_Parser function which is also part of the
226 ## If a valid command has been sent through the socket, the corresponding event
227 ## will be enqueued into the shared event queue.
230 # Create the Server socket by calling the responsible function.
231 my $server = &Guardian
::Socket
::Server
();
233 # Accept incomming connections from the socket.
234 while (my $connection = $server->accept()) {
235 # Autoflush the socket after the data
237 $connection->autoflush(1);
239 # Gather all data from the connection.
240 while (my $message = <$connection>) {
241 # Remove any newlines.
244 # Send the recieved data message to the
246 my $action = &Guardian
::Socket
::Message_Parser
($message);
248 # If the parser returns to perform an action,
249 # add it to the main event queue.
254 # Enqueue the returned action.
255 $queue->enqueue($action);
262 ## Function for capturing process signals.
264 ## This function captures any sent process signals and will call various
265 ## actions, basend on the captured signal.
268 $SIG{INT
} = \
&Shutdown
;
269 $SIG{TERM
} = \
&Shutdown
;
270 $SIG{QUIT
} = \
&Shutdown
;
271 $SIG{HUP
} = \
&Reload
;
275 ## Function to start the workers (threads) for all monitored files.
277 ## This function will loop through the hash of monitored files and will
278 ## spawn an own thread based worker for each file. Every created worker will
279 ## be added to the array of running workers.
281 sub StartWorkers
() {
282 # Loop through the hash which contains the monitored files and start
283 # a worker thread for each single one.
284 foreach my $file (keys %monitored_files) {
285 # Create worker thread for the file.
286 push @running_workers, threads
->create(\
&Worker
,$file);
291 ## Function to stop all running workers.
293 ## This function is used to stop all currently running workers and will be
294 ## called when reloading or shutting down guardian.
297 # Loop through all running workers.
298 foreach my $worker (@running_workers) {
299 # Send the worker the "KILL" signal and detach the
300 # thread so perl can do an automatically clean-up.
301 $worker->kill('KILL');
308 ## This function will get called if the signal handler recieves a "SIGHUP" signal,
309 ## or the reload command will be sent via socket connection. It is responsible for
310 ## reloading all configure options and stopping/starting the worker threads.
313 # Stop all running workers.
316 # Re-read configuration file.
317 %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
319 # Re-generate hash of monitored files.
320 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
322 # Restart the worker threads.
327 ## Shutdown function.
329 ## This function is used to do a clean shutdown of guardian. It will be called
330 ## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
336 # Remove socket file on exit.
337 &Guardian
::Socket
::RemoveSocketFile
();
339 # Sleep for one second to give perl some
340 # time to proper clean up everything before