]>
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
::Daemon
;
33 require Guardian
::Logger
;
34 require Guardian
::Parser
;
35 require Guardian
::Socket
;
39 # Disable warnings of unjoinded threads when stopping guardian.
40 no warnings
'threads';
45 # Get and store the given command line arguments in a hash.
48 &GetOptions
(\
%cmdargs,
55 # Show help / version information.
56 if (defined($cmdargs{"help"})) {
57 print "Guardian $version \n";
58 print "Usage: guardian <optional arguments>\n";
59 print " -c, --config\t\tspecifiy a configuration file other than the default (/etc/guardian/guardian.conf)\n";
60 print " -f, --foreground\trun in the foreground (doesn't fork, any output goes to STDOUT)\n";
61 print " -h, --help\t\tshows this help\n";
62 print " -v, --version\t\tdisplay programm version and exit.\n";
64 } elsif (defined($cmdargs{"version"})) {
65 print "Guardian $version \n";
69 # Check if another instance of guardian is allready running.
70 if (&Guardian
::Daemon
::IsRunning
()) {
71 die "Another instance of Guardian is allready running...\n";
74 # Read-in the configuration file and store the settings.
75 # Push the may be given config file argument.
76 my %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
79 my $logger = Guardian
::Logger
->Init(%mainsettings);
80 $logger->Log("debug", "Logger successfully initialized...");
82 # Add the logger object to the mainsettings for passing
84 $mainsettings{Logger
} = $logger;
86 # Redirect perls "die" messages to the logger before exiting.
87 $SIG{__DIE__
} = sub { $logger->Log("err", "@_"); };
89 # Shared hash between the main process and all threads. It will store all
90 # monitored files and their current file position.
91 my %monitored_files :shared
= ();
93 # Create the main queue. It is used to store and process all events which are
94 # reported and enqueued by the worker threads.
95 my $queue :shared
= new Thread
::Queue
or die "Could not create new, empty queue. $!";;
97 # Array to store all currently running worker objects.
98 # (Does not include the socket thread)
101 # Check if guardian should be daemonized or keep in the foreground.
102 unless (defined($cmdargs{"foreground"})) {
103 # Fork into background.
104 &Guardian
::Daemon
::Daemonize
();
106 # Write PID (process-id).
107 &Guardian
::Daemon
::WritePID
();
110 # Call Init function to initzialize guardian.
113 # Infinite main loop, which processes all queued events.
115 # Get the amount of elements in our queue.
116 # "undef" will be returned if it is empty.
117 my $current_events = $queue->pending();
119 # If there is at least one element enqued
120 if($current_events > 0) {
121 # Grab the data of the top enqueued event.
122 my $event = $queue->peek();
124 # Log processed event.
125 $logger->Log("debug", "QUEUE - Processed event: $event");
127 # Drop processed event from queue.
131 # Sleep 10ms to reduce the load of the main process.
138 ## This function contains code which has to be executed while guardian
142 # Setup signal handler.
145 # Setup IPC mechanism via Socket in an own thread.
146 threads
->create(\
&Socket
);
148 # Generate hash of monitored files.
149 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
151 # Start worker threads.
158 ## This function is responsible for monitoring modifications of the given logfile,
159 ## read them and pass them to the message parser.
161 ## To get file modifications the inotify subsystem of the linux kernel is used.
163 ## In order to prevent from permanently read and keep files opened, or dealing
164 ## with huge logfiles, at initialization time of the worker process, the file will
165 ## be opened once and the cursor position of the end of file (EOF) get stored. When
166 ## reading any newly added lines from the file, we directly can jump to the last
167 ## known position and get these lines. Afterwards, we store the current curser position
168 ## again, so we can do it in this way over and over again.
170 ## All read lines get stored in an array, which will be passed to the Parser.
172 ## If any response (action) from the parser get recieved, it will be put into the
173 ## shared event queue.
178 # Signal handler to kill worker.
179 $SIG{'KILL'} = sub { threads
->exit(); };
181 # Create inotify watcher.
182 my $watcher = new Linux
::Inotify2
or die "Could not use inotify. $!";
184 # Monitor the specified file.
185 $watcher->watch("$file", IN_MODIFY
) or die "Could not monitor $file. $!";
187 # Switch watcher into non-blocking mode.
188 $watcher->blocking(0);
190 # Log successfully spawned worker.
191 $logger->Log("debug", "Spawned worker thread for: $file");
195 # Check for any events and perform them, if there
197 if ($watcher->read) {
200 # Obtain fileposition from hash.
201 my $fileposition = $monitored_files{$file};
204 open (FILE
, $file) or die "Could not open $file. $!";
206 # Seek to the last known position.
207 seek (FILE
, $fileposition, 0);
209 # Get the log message.
210 while (my $line = <FILE
>) {
211 # Remove any newlines.
214 # Add all lines to the message array.
215 push (@message, $line);
220 lock(%monitored_files);
222 # Update fileposition.
223 $monitored_files{$file} = tell(FILE
);
229 # Send filename and message to the parser,
230 # which will return if an action has to be performed.
231 my @action = &Guardian
::Parser
::Parser
("$file", @message);
233 # Send the action to the main process and put it into
239 # Put the required action into the queue.
240 $queue->enqueue(@action);
243 # Sleep for 10ms until the next round of the loop will start.
252 ## This function uses the Socket module to create and listen to an UNIX socket.
253 ## It automatically accepts all incomming connections and pass the recieved
254 ## data messages to the the Message_Parser function which is also part of the
257 ## If a valid command has been sent through the socket, the corresponding event
258 ## will be enqueued into the shared event queue.
261 # Create the Server socket by calling the responsible function.
262 my $server = &Guardian
::Socket
::Server
();
264 # Log successfull creation of socket.
265 $logger->Log("debug", "Listening to Socket...");
267 # Accept incomming connections from the socket.
268 while (my $connection = $server->accept()) {
269 # Autoflush the socket after the data
271 $connection->autoflush(1);
273 # Gather all data from the connection.
274 while (my $message = <$connection>) {
275 # Remove any newlines.
278 # Log recieved socket command.
279 $logger->Log("debug", "Socket - Recieved message: $message");
281 # Send the recieved data message to the
283 my $action = &Guardian
::Socket
::Message_Parser
($message);
285 # If the parser returns to perform an action,
286 # add it to the main event queue.
291 # Enqueue the returned action.
292 $queue->enqueue($action);
299 ## Function for capturing process signals.
301 ## This function captures any sent process signals and will call various
302 ## actions, basend on the captured signal.
305 $SIG{INT
} = \
&Shutdown
;
306 $SIG{TERM
} = \
&Shutdown
;
307 $SIG{QUIT
} = \
&Shutdown
;
308 $SIG{HUP
} = \
&Reload
;
312 ## Function to start the workers (threads) for all monitored files.
314 ## This function will loop through the hash of monitored files and will
315 ## spawn an own thread based worker for each file. Every created worker will
316 ## be added to the array of running workers.
318 sub StartWorkers
() {
319 # Loop through the hash which contains the monitored files and start
320 # a worker thread for each single one.
321 foreach my $file (keys %monitored_files) {
322 $logger->Log("debug", "Starting worker thread for $file");
323 # Create worker thread for the file.
324 push @running_workers, threads
->create(\
&Worker
,$file);
329 ## Function to stop all running workers.
331 ## This function is used to stop all currently running workers and will be
332 ## called when reloading or shutting down guardian.
335 # Loop through all running workers.
336 foreach my $worker (@running_workers) {
337 # Send the worker the "KILL" signal and detach the
338 # thread so perl can do an automatically clean-up.
339 $worker->kill('KILL');
341 $logger->Log("debug", "All workers are stopped now...");
347 ## This function will get called if the signal handler recieves a "SIGHUP" signal,
348 ## or the reload command will be sent via socket connection. It is responsible for
349 ## reloading all configure options and stopping/starting the worker threads.
353 $logger->Log("info", "Reload configuration...");
355 # Stop all running workers.
358 # Re-read configuration file.
359 %mainsettings = &Guardian
::Config
::UseConfig
($cmdargs{"config"});
361 # Update Logger settings.
362 $logger = Guardian
::Logger
->Init(%mainsettings);
364 # Update logger object in mainsettings hash.
365 $mainsettings{Logger
} = $logger;
367 # Re-generate hash of monitored files.
368 %monitored_files = &Guardian
::Base
::GenerateMonitoredFiles
(\
%mainsettings, \
%monitored_files);
370 # Restart the worker threads.
375 ## Shutdown function.
377 ## This function is used to do a clean shutdown of guardian. It will be called
378 ## by the signal handler when recieving INT (2), QUIT (3) and TERM (15) signals.
382 $logger->Log("info", "Shutting down...");
387 # Remove socket file on exit.
388 &Guardian
::Socket
::RemoveSocketFile
();
390 # Remove pid file on exit.
391 &Guardian
::Daemon
::RemovePIDFile
();
393 # Sleep for one second to give perl some
394 # time to proper clean up everything before
398 # Log good bye message.
399 $logger->Log("debug", "Good Bye!");