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