]> git.ipfire.org Git - people/pmueller/ipfire-2.x.git/blame - html/cgi-bin/logs.cgi/ovpnclients.dat
ovpnclients.dat: Do not perform DB actions if there is an error message.
[people/pmueller/ipfire-2.x.git] / html / cgi-bin / logs.cgi / ovpnclients.dat
CommitLineData
3e10b3de
SS
1#!/usr/bin/perl
2###############################################################################
3# #
4# IPFire.org - A linux based firewall #
5# Copyright (C) 2020 IPFire Team <info@ipfire.org> #
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 POSIX();
24use DBI;
25
26# enable only the following on debugging purpose
27#use warnings;
28#use CGI::Carp 'fatalsToBrowser';
29
30require '/var/ipfire/general-functions.pl';
31require "${General::swroot}/lang.pl";
32require "${General::swroot}/header.pl";
33
34my %color = ();
35my %mainsettings = ();
36&General::readhash("${General::swroot}/main/settings", \%mainsettings);
37&General::readhash("/srv/web/ipfire/html/themes/".$mainsettings{'THEME'}."/include/colors.txt", \%color);
38
39# Path and file of the OVPN connections database.
40my $database = "/var/ipfire/ovpn/clients.db";
41
42my %cgiparams=();
43my %logsettings=();
44my %ovpnsettings=();
45
46my $errormessage='';
47
48# Hash wich contains the month numbers and the translated names for easy access.
49my %monthhash = (
50 "1" => "$Lang::tr{'january'}",
51 "2" => "$Lang::tr{'february'}",
52 "3" => "$Lang::tr{'march'}",
53 "4" => "$Lang::tr{'april'}",
54 "5" => "$Lang::tr{'may'}",
55 "6" => "$Lang::tr{'june'}",
56 "7" => "$Lang::tr{'july'}",
57 "8" => "$Lang::tr{'august'}",
58 "9" => "$Lang::tr{'september'}",
59 "10" => "$Lang::tr{'october'}",
60 "11" => "$Lang::tr{'november'}",
61 "12" => "$Lang::tr{'december'}"
62);
63
64# Get current time.
65my ($sec,$min,$hour,$mday,$month,$year,$wday,$yday,$isdst) = localtime(time);
66
67# Adjust month, because Jan starts as month "0".
68$month = $month+1;
69
70# Adjust year number.
71$year = $year+1900;
72
73# Assign default vaules.
74$cgiparams{'FROM_DAY'} = $mday;
75$cgiparams{'FROM_MONTH'} = $month;
76$cgiparams{'FROM_YEAR'} = $year;
77$cgiparams{'TO_DAY'} = $mday;
78$cgiparams{'TO_MONTH'} = $month;
79$cgiparams{'TO_YEAR'} = $year;
80
81&Header::getcgihash(\%cgiparams);
82
83# Read-in OpenVPN settings and connections.
84&General::readhasharray("${General::swroot}/ovpn/ovpnconfig", \%ovpnsettings);
85
86# Init DB Module and connect to the database.
87my $database_handle = DBI->connect("DBI:SQLite:dbname=$database", "", "", { RaiseError => 1 });
88
89# Generate datestrings for SQL queries.
90my $from_datestring = sprintf '%04d-%02d-%02d', ($cgiparams{"FROM_YEAR"}, $cgiparams{"FROM_MONTH"}, $cgiparams{"FROM_DAY"});
91my $to_datestring = sprintf '%04d-%02d-%02d', ($cgiparams{"TO_YEAR"}, $cgiparams{"TO_MONTH"}, $cgiparams{"TO_DAY"});
92
0f195a53
SS
93# Check if the to datestring is later than the from datestring.
94unless ($to_datestring ge $from_datestring) {
95 $errormessage = "$Lang::tr{'error the to date has to be later than the from date'}";
96}
97
3e10b3de
SS
98my $database_query = qq(
99 SELECT
100 common_name, SUM(
101 STRFTIME('%s', (
102 CASE
103 WHEN DATETIME(COALESCE(disconnected_at, CURRENT_TIMESTAMP), 'localtime') < DATETIME('$to_datestring', 'localtime', 'start of day', '+86399 seconds')
104 THEN DATETIME(COALESCE(disconnected_at, CURRENT_TIMESTAMP), 'localtime')
105 ELSE DATETIME('$to_datestring', 'localtime', 'start of day', '+86399 seconds')
106 END
107 ), 'utc') -
108 STRFTIME('%s', (
109 CASE
110 WHEN DATETIME(connected_at, 'localtime') > DATETIME('$from_datestring', 'localtime', 'start of day')
111 THEN DATETIME(connected_at, 'localtime')
112 ELSE DATETIME('$from_datestring', 'localtime', 'start of day')
113 END
114 ), 'utc')
70e1d587 115 ) AS duration
3e10b3de
SS
116 FROM sessions
117 WHERE
70e1d587
MT
118 (
119 disconnected_at IS NULL
120 OR
121 DATETIME(disconnected_at, 'localtime') > DATETIME('$from_datestring', 'localtime', 'start of day')
122 )
123 AND
3e10b3de
SS
124 DATETIME(connected_at, 'localtime') < DATETIME('$to_datestring', 'localtime', 'start of day', '+86399 seconds')
125 GROUP BY common_name
70e1d587 126 ORDER BY common_name, duration DESC;
3e10b3de
SS
127);
128
129if ($cgiparams{'CONNECTION_NAME'}) {
130 $database_query = qq(
1242cb01 131 SELECT common_name, DATETIME(connected_at, 'localtime'), DATETIME(disconnected_at, 'localtime'), bytes_received, bytes_sent FROM sessions
3e10b3de 132 WHERE
70e1d587
MT
133 common_name = '$cgiparams{"CONNECTION_NAME"}'
134 AND (
135 DATETIME(disconnected_at, 'localtime') > DATETIME('$from_datestring', 'localtime', 'start of day')
136 AND
137 DATETIME(connected_at, 'localtime') < DATETIME('$to_datestring', 'localtime', 'start of day', '+86399 seconds')
138 )
139 ORDER BY connected_at;
3e10b3de
SS
140 );
141}
142
e1cc1e6c
SS
143my $statement_handle;
144my $database_return_value;
3e10b3de 145
e1cc1e6c
SS
146# Only process SQL actions if there is no error message.
147unless ($errormessage) {
148 # Prepare SQL statement.
149 $statement_handle = $database_handle->prepare($database_query);
150
151 # Execute SQL statement and get retun value if any error happened.
152 $database_return_value = $statement_handle->execute();
153}
3e10b3de
SS
154
155# If an error has been returned, assign it to the errorstring value for displaying.
156if($database_return_value < 0) {
157 $errormessage = "$DBI::errstr";
158}
159
160&Header::showhttpheaders();
161
162&Header::openpage($Lang::tr{'ovpn rw connection log'}, 1, '');
163
164&Header::openbigbox('100%', 'left', '', $errormessage);
165
166if ($errormessage) {
167 &Header::openbox('100%', 'left', $Lang::tr{'error messages'});
168 print "<font class='base'>$errormessage&nbsp;</font>\n";
169 &Header::closebox();
170}
171
172&Header::openbox('100%', 'left', "$Lang::tr{'settings'}:");
173
174print "<form method='post' action=\"$ENV{'SCRIPT_NAME'}\">\n";
175print "<table width='100%'>\n";
176 print "<tr>\n";
177 print "<td class='base' colspan='2'><b>$Lang::tr{'from'}:</b></td>\n";
178 print "</tr>\n";
179
180 print "<tr>\n";
181 print "<td class='base'>$Lang::tr{'day'}:&nbsp\;\n";
182 &generate_select("FROM_DAY", "days");
183 print "</td>\n";
184
185 print "<td class='base'>$Lang::tr{'month'}:&nbsp\;\n";
186 &generate_select("FROM_MONTH", "months");
187 print "</td>\n";
188
189 print "<td class='base'>$Lang::tr{'year'}:&nbsp\;\n";
190 &generate_select("FROM_YEAR", "years");
191 print "</td>\n";
192 print "</tr>\n";
193
194 print "<tr><td><br></td></tr>\n";
195
196 print "<tr>\n";
197 print "<td class='base' colspan='2'><b>$Lang::tr{'to'}:</b></td>\n";
198 print "</tr>\n";
199
200 print "<tr>\n";
201 print "<td class='base'>$Lang::tr{'day'}:&nbsp\;\n";
202 &generate_select("TO_DAY", "days");
203 print "</td>\n";
204
205 print "<td class='base'>$Lang::tr{'month'}:&nbsp\;\n";
206 &generate_select("TO_MONTH", "months");
207 print "</td>\n";
208
209 print "<td class='base'>$Lang::tr{'year'}:&nbsp\;\n";
210 &generate_select("TO_YEAR", "years");
211 print "</td>\n";
212 print "</tr>\n";
213
214 print "<tr><td><br></td></tr>\n";
215
216 print "<tr>\n";
217 print "<td class='base'>$Lang::tr{'ovpn connection name'}:</td>\n";
218 print "<td class='base' colspan='2'>\n";
219
220 print "<select name='CONNECTION_NAME' size='1'>\n";
6317d55c 221 print "<option value=''>$Lang::tr{'all'}</option>\n";
3e10b3de
SS
222
223 # Loop through all configured OpenVPN connections and sort them by name.
224 foreach my $key (sort { $ovpnsettings{$a}[2] cmp $ovpnsettings{$b}[2] } keys %ovpnsettings) {
225 my $connection_name = $ovpnsettings{$key}[2];
226 my $selected;
227
228 # Skip all non roadwarrior connections.
229 next unless ($ovpnsettings{"$key"}[3] eq "host");
230
231 # Check and mark the selected one.
232 if ($connection_name eq "$cgiparams{'CONNECTION_NAME'}") {
233 $selected = "selected";
234 }
235
236 print "<option value='$connection_name' $selected>$connection_name</option>\n";
237 }
238
239 print "</select>\n";
240 print "</td>\n";
241 print "</tr>\n";
242
243 print "<tr>\n";
244 print "<td width='100%' align='right' colspan='3'><input type='submit' name='ACTION' value='$Lang::tr{'update'}'></td>\n";
245 print "</tr>\n";
246print "</table>\n";
247print "</form>\n";
248
249&Header::closebox();
250
251&Header::openbox('100%', 'left', $Lang::tr{'log'});
252
253my $lines = 0;
254
255print "<table width='100%' class='tbl'>";
256
d5b6023c
SS
257my $col = "bgcolor='$color{'color20'}'";
258
259 print "<tr>\n";
260 print "<td width='40%' $col><b>$Lang::tr{'ovpn connection name'}</b></td>\n";
261
262 if ($cgiparams{'CONNECTION_NAME'}) {
263 print "<td width='20%' $col><b>$Lang::tr{'connected'}</b></td>\n";
264 print "<td width='20%' $col><b>$Lang::tr{'disconnected'}</b></td>\n";
265 print "<td width='10%' $col><b>$Lang::tr{'recieved'}</b></td>\n";
266 print "<td width='10%' $col><b>$Lang::tr{'sent'}</b></td>\n";
267 } else {
268 print "<td $col><b>$Lang::tr{'total connection time'}</b>\n";
269 }
270
271 print "</tr>\n";
3e10b3de 272
e1cc1e6c
SS
273# Only try to fetch the DB items if there is no error message.
274unless ($errormessage) {
275 while(my @row = $statement_handle->fetchrow_array()) {
276 # Assign some nice to read variable names for the DB fields.
277 my $connection_name = $row[0];
278 my $connection_open_time = $row[1];
279 my $connection_close_time = $row[2];
280 my $connection_bytes_recieved = &General::formatBytes($row[3]);
281 my $connection_bytes_sent = &General::formatBytes($row[4]);
282
283 # Colorize columns.
284 if ($lines % 2) {
285 $col="bgcolor='$color{'color20'}'";
286 } else {
287 $col="bgcolor='$color{'color22'}'";
288 }
289
290 print "<tr>\n";
291 print "<td width='40%' $col>$connection_name</td>\n";
292
293 if ($cgiparams{'CONNECTION_NAME'}) {
294 print "<td width='20%' $col>$connection_open_time</td>\n";
295 print "<td width='20%' $col>$connection_close_time</td>\n";
296 print "<td width='10%' $col>$connection_bytes_recieved</td>\n";
297 print "<td width='10%' $col>$connection_bytes_sent</td>\n";
298 } else {
299 # Convert total connection time into human-readable format.
300 my $total_time = &General::format_time($row[1]);
301
302 print "<td $col>$total_time</td>\n";
303 }
304
305 print "</tr>\n";
306
307 # Increase lines count.
308 $lines++;
d5b6023c 309 }
c7d55d7f 310}
3e10b3de 311
c7d55d7f 312# If nothing has been fetched, the amount of lines is still zero.
e1cc1e6c 313# In this case display a hint about no data.
c7d55d7f
SS
314unless ($lines) {
315 print "<tr><td bgcolor='$color{'color22'}' colspan='5' align='center'>$Lang::tr{'no entries'}</td></tr>\n";
316}
3e10b3de
SS
317
318print "</table><br>\n";
319
320&Header::closebox();
321
322# Close database connection.
323$database_handle->disconnect();
324
325&Header::closebigbox();
326
327&Header::closepage();
328
329#
330## Function for easy select generation.
331#
332sub generate_select($$) {
333 my ($name, $type) = @_;
334
335 my $start = 1;
336 my $stop;
337
338 # Adjust start and stop by the given type.
339 if ($type eq "days") {
340 $stop = 31;
341 } elsif ($type eq "months") {
342 $stop = 12;
343 } elsif ($type = "years") {
344 $stop = $year;
345 $start = $stop - 10;
346 }
347
348 # Print select HTML tag.
349 print "<select name='$name' size='1'>\n";
350
351 # Loop through the range.
352 for ( my $i = $start; $i <= $stop; $i++) {
353 print "\t<option ";
354
355 # Check and select the current processed item.
356 if ($i == $cgiparams{$name}) {
357 print 'selected="selected" ';
358 }
359
360 # Check if months are processed and display the corresponding names.
361 if ($type eq "months") {
362 print "value='$i'>$monthhash{$i}</option>\n";
363 } else {
364 print "value='$i'>$i</option>\n";
365 }
366 }
367
368 # Close select HTML tag.
369 print "</select>\n\n";
370}