]> git.ipfire.org Git - people/stevee/guardian.git/blob - guardian
Introduce "IPtables" module.
[people/stevee/guardian.git] / guardian
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
22 use strict;
23 use threads;
24 use threads::shared;
25 use Getopt::Long;
26 use Thread::Queue;
27 use Linux::Inotify2;
28 use Time::HiRes qw[ time sleep ];
29
30 require Guardian::Base;
31 require Guardian::Config;
32 require Guardian::Daemon;
33 require Guardian::Logger;
34 require Guardian::Parser;
35 require Guardian::Socket;
36
37 use warnings;
38
39 # Disable warnings of unjoinded threads when stopping guardian.
40 no warnings 'threads';
41
42 # Define version.
43 my $version ="2.0";
44
45 # Get and store the given command line arguments in a hash.
46 my %cmdargs = ();
47
48 &GetOptions (\%cmdargs,
49 'foreground|f',
50 'config|c=s',
51 'help|h',
52 'version|v',
53 );
54
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";
63 exit;
64 } elsif (defined($cmdargs{"version"})) {
65 print "Guardian $version \n";
66 exit;
67 }
68
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";
72 }
73
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"});
77
78 # Initialize Logger.
79 my $logger = Guardian::Logger->Init(%mainsettings);
80 $logger->Log("debug", "Logger successfully initialized...");
81
82 # Add the logger object to the mainsettings for passing
83 # it to the modules.
84 $mainsettings{Logger} = $logger;
85
86 # Redirect perls "die" messages to the logger before exiting.
87 $SIG{__DIE__} = sub { $logger->Log("err", "@_"); };
88
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 = ();
92
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. $!";;
96
97 # Array to store all currently running worker objects.
98 # (Does not include the socket thread)
99 my @running_workers;
100
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();
105 } else {
106 # Write PID (process-id).
107 &Guardian::Daemon::WritePID();
108 }
109
110 # Call Init function to initzialize guardian.
111 &Init();
112
113 # Infinite main loop, which processes all queued events.
114 while(1) {
115 # Get the amount of elements in our queue.
116 # "undef" will be returned if it is empty.
117 my $current_events = $queue->pending();
118
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();
123
124 # Log processed event.
125 $logger->Log("debug", "QUEUE - Processed event: $event");
126
127 # Drop processed event from queue.
128 $queue->dequeue();
129 }
130
131 # Sleep 10ms to reduce the load of the main process.
132 sleep(0.01);
133 }
134
135 #
136 ## Init function.
137 #
138 ## This function contains code which has to be executed while guardian
139 ## is starting.
140 #
141 sub Init () {
142 # Setup signal handler.
143 &SignalHandler();
144
145 # Setup IPC mechanism via Socket in an own thread.
146 threads->create(\&Socket);
147
148 # Generate hash of monitored files.
149 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
150
151 # Start worker threads.
152 &StartWorkers();
153 }
154
155 #
156 ## Worker function.
157 #
158 ## This function is responsible for monitoring modifications of the given logfile,
159 ## read them and pass them to the message parser.
160 #
161 ## To get file modifications the inotify subsystem of the linux kernel is used.
162 #
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.
169 #
170 ## All read lines get stored in an array, which will be passed to the Parser.
171 #
172 ## If any response (action) from the parser get recieved, it will be put into the
173 ## shared event queue.
174 #
175 sub Worker ($) {
176 my $file = $_[0];
177
178 # Signal handler to kill worker.
179 $SIG{'KILL'} = sub { threads->exit(); };
180
181 # Create inotify watcher.
182 my $watcher = new Linux::Inotify2 or die "Could not use inotify. $!";
183
184 # Monitor the specified file.
185 $watcher->watch("$file", IN_MODIFY) or die "Could not monitor $file. $!";
186
187 # Switch watcher into non-blocking mode.
188 $watcher->blocking(0);
189
190 # Log successfully spawned worker.
191 $logger->Log("debug", "Spawned worker thread for: $file");
192
193 # Infinite loop.
194 while(1) {
195 # Check for any events and perform them, if there
196 # is a least one.
197 if ($watcher->read) {
198 my @message = ();
199
200 # Obtain fileposition from hash.
201 my $fileposition = $monitored_files{$file};
202
203 # Open the file.
204 open (FILE, $file) or die "Could not open $file. $!";
205
206 # Seek to the last known position.
207 seek (FILE, $fileposition, 0);
208
209 # Get the log message.
210 while (my $line = <FILE>) {
211 # Remove any newlines.
212 chomp $line;
213
214 # Add all lines to the message array.
215 push (@message, $line);
216 }
217
218 {
219 # Lock shared hash.
220 lock(%monitored_files);
221
222 # Update fileposition.
223 $monitored_files{$file} = tell(FILE);
224 }
225
226 # Close file.
227 close(FILE);
228
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);
232
233 # Send the action to the main process and put it into
234 # the queue.
235 if (@action) {
236 # Lock the queue.
237 lock($queue);
238
239 # Put the required action into the queue.
240 $queue->enqueue(@action);
241 }
242 } else {
243 # Sleep for 10ms until the next round of the loop will start.
244 sleep(0.01);
245 }
246 }
247 }
248
249 #
250 ## Socket function.
251 #
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
255 ## socket module.
256 #
257 ## If a valid command has been sent through the socket, the corresponding event
258 ## will be enqueued into the shared event queue.
259 #
260 sub Socket () {
261 # Create the Server socket by calling the responsible function.
262 my $server = &Guardian::Socket::Server();
263
264 # Log successfull creation of socket.
265 $logger->Log("debug", "Listening to Socket...");
266
267 # Accept incomming connections from the socket.
268 while (my $connection = $server->accept()) {
269 # Autoflush the socket after the data
270 # has been recieved.
271 $connection->autoflush(1);
272
273 # Gather all data from the connection.
274 while (my $message = <$connection>) {
275 # Remove any newlines.
276 chomp($message);
277
278 # Log recieved socket command.
279 $logger->Log("debug", "Socket - Recieved message: $message");
280
281 # Send the recieved data message to the
282 # socket parser.
283 my $action = &Guardian::Socket::Message_Parser($message);
284
285 # If the parser returns to perform an action,
286 # add it to the main event queue.
287 if ($action) {
288 # Lock the queue.
289 lock($queue);
290
291 # Enqueue the returned action.
292 $queue->enqueue($action);
293 }
294 }
295 }
296 }
297
298 #
299 ## Function for capturing process signals.
300 #
301 ## This function captures any sent process signals and will call various
302 ## actions, basend on the captured signal.
303 #
304 sub SignalHandler {
305 $SIG{INT} = \&Shutdown;
306 $SIG{TERM} = \&Shutdown;
307 $SIG{QUIT} = \&Shutdown;
308 $SIG{HUP} = \&Reload;
309 }
310
311 #
312 ## Function to start the workers (threads) for all monitored files.
313 #
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.
317 #
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);
325 }
326 }
327
328 #
329 ## Function to stop all running workers.
330 #
331 ## This function is used to stop all currently running workers and will be
332 ## called when reloading or shutting down guardian.
333 #
334 sub StopWorkers () {
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');
340 }
341 $logger->Log("debug", "All workers are stopped now...");
342 }
343
344 #
345 ## Reload function.
346 #
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.
350 #
351 sub Reload () {
352 # Log reload.
353 $logger->Log("info", "Reload configuration...");
354
355 # Stop all running workers.
356 &StopWorkers();
357
358 # Re-read configuration file.
359 %mainsettings = &Guardian::Config::UseConfig($cmdargs{"config"});
360
361 # Update Logger settings.
362 $logger = Guardian::Logger->Init(%mainsettings);
363
364 # Update logger object in mainsettings hash.
365 $mainsettings{Logger} = $logger;
366
367 # Re-generate hash of monitored files.
368 %monitored_files = &Guardian::Base::GenerateMonitoredFiles(\%mainsettings, \%monitored_files);
369
370 # Restart the worker threads.
371 &StartWorkers();
372 }
373
374 #
375 ## Shutdown function.
376 #
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.
379 #
380 sub Shutdown () {
381 # Log shutdown.
382 $logger->Log("info", "Shutting down...");
383
384 # Stop all workers.
385 &StopWorkers();
386
387 # Remove socket file on exit.
388 &Guardian::Socket::RemoveSocketFile();
389
390 # Remove pid file on exit.
391 &Guardian::Daemon::RemovePIDFile();
392
393 # Sleep for one second to give perl some
394 # time to proper clean up everything before
395 # exiting.
396 sleep(1);
397
398 # Log good bye message.
399 $logger->Log("debug", "Good Bye!");
400
401 # Exit guardian.
402 exit;
403 }