659d41a687e2111b6c56a5dd7b8f229a0e42b666
[ipfire-2.x.git] / config / cfgroot / header.pl
1 # SmoothWall CGIs
2 #
3 # This code is distributed under the terms of the GPL
4 #
5 # (c) The SmoothWall Team
6 # Copyright (C) 2002 Alex Hudson - getcgihash() rewrite
7 # Copyright (C) 2002 Bob Grant <bob@cache.ucr.edu> - validmac()
8 # Copyright (c) 2002/04/13 Steve Bootes - add alias section, helper functions
9 # Copyright (c) 2002/08/23 Mark Wormgoor <mark@wormgoor.com> validfqdn()
10 # Copyright (c) 2003/09/11 Darren Critchley <darrenc@telus.net> srtarray()
11 #
12 package Header;
13
14 use CGI();
15 use Socket;
16 use Time::Local;
17
18 $|=1; # line buffering
19
20 $Header::revision = 'final';
21 $Header::swroot = '/var/ipfire';
22 $Header::pagecolour = '#ffffff';
23 #$Header::tablecolour = '#a0a0a0';
24 $Header::tablecolour = '#FFFFFF';
25 $Header::bigboxcolour = '#F6F4F4';
26 $Header::boxcolour = '#EAE9EE';
27 $Header::bordercolour = '#000000';
28 $Header::table1colour = '#E0E0E0';
29 $Header::table2colour = '#F0F0F0';
30 $Header::colourred = '#993333';
31 $Header::colourorange = '#FF9933';
32 $Header::colouryellow = '#FFFF00';
33 $Header::colourgreen = '#339933';
34 $Header::colourblue = '#333399';
35 $Header::colourovpn = '#339999';
36 $Header::colourfw = '#000000';
37 $Header::colourvpn = '#990099';
38 $Header::colourerr = '#FF0000';
39 $Header::viewsize = 150;
40 $Header::errormessage = '';
41 my %menuhash = ();
42 my $menu = \%menuhash;
43 %settings = ();
44 %ethsettings = ();
45 @URI = ();
46 $Header::supported=0;
47
48 ### Make sure this is an SSL request
49 if ($ENV{'SERVER_ADDR'} && $ENV{'HTTPS'} ne 'on') {
50     print "Status: 302 Moved\r\n";
51     print "Location: https://$ENV{'SERVER_ADDR'}:10443/$ENV{'PATH_INFO'}\r\n\r\n";
52     exit 0;
53 }
54
55 ### Initialize environment
56 &readhash("${swroot}/main/settings", \%settings);
57 &readhash("${swroot}/ethernet/settings", \%ethsettings);
58 $language = $settings{'LANGUAGE'};
59 $hostname = $settings{'HOSTNAME'};
60 $hostnameintitle = 0;
61
62 ### Initialize language
63 if ($language =~ /^(\w+)$/) {$language = $1;}
64
65 ### Read English Files
66 if ( -d "/var/ipfire/langs/en/" ) {
67     opendir(DIR, "/var/ipfire/langs/en/");
68     @names = readdir(DIR) or die "Cannot Read Directory: $!\n";
69     foreach $name(@names) {
70         next if ($name eq ".");
71         next if ($name eq "..");
72         next if (!($name =~ /\.pl$/));
73         require "${swroot}/langs/en/${name}";
74     };
75 };
76
77
78 ### Enable Language Files
79 if ( -d "/var/ipfire/langs/${language}/" ) {
80     opendir(DIR, "/var/ipfire/langs/${language}/");
81     @names = readdir(DIR) or die "Cannot Read Directory: $!\n";
82     foreach $name(@names) {
83         next if ($name eq ".");
84         next if ($name eq "..");
85         next if (!($name =~ /\.pl$/));
86         require "${swroot}/langs/${language}/${name}";
87     };
88 };
89
90
91 require "${swroot}/langs/en.pl";
92 require "${swroot}/langs/${language}.pl";
93
94 sub orange_used () {
95     if ($ethsettings{'CONFIG_TYPE'} =~ /^[1357]$/) {
96         return 1;
97     }
98     return 0;
99 }
100
101 sub blue_used () {
102     if ($ethsettings{'CONFIG_TYPE'} =~ /^[4567]$/) {
103         return 1;
104     }
105     return 0;
106 }
107
108 sub is_modem {
109     if ($ethsettings{'CONFIG_TYPE'} =~ /^[0145]$/) {
110         return 1;
111     }
112     return 0;
113 }
114
115 ### Initialize menu
116 sub genmenu {
117     my %subsystemhash = ();
118     my $subsystem = \%subsystemhash;
119
120     $subsystem->{'10.home'} = {
121                                 'caption' => $tr{'alt home'},
122                                 'uri' => '/cgi-bin/index.cgi',
123                                 'title' => "$tr{'alt home'}",
124                                 'enabled' => 1,
125                                 };
126     $subsystem->{'20.passwords'} = {
127                                 'caption' => $tr{'sspasswords'},
128                                 'uri' => '/cgi-bin/changepw.cgi',
129                                 'title' => "$tr{'sspasswords'}",
130                                 'enabled' => 1,
131                                 };
132     $subsystem->{'30.ssh'} = {
133                                 'caption' => $tr{'ssh access'},
134                                 'uri' => '/cgi-bin/remote.cgi',
135                                 'title' => "$tr{'ssh access'}",
136                                 'enabled' => 1,
137                                 };
138     $subsystem->{'40.gui'} = {
139                                 'caption' => $tr{'gui settings'},
140                                 'uri' => '/cgi-bin/gui.cgi',
141                                 'title' => "$tr{'gui settings'}",
142                                 'enabled' => 1,
143                                 };
144     $subsystem->{'50.shutdown'} = {
145                                 'caption' => $tr{'shutdown'},
146                                 'uri' => '/cgi-bin/shutdown.cgi',
147                                 'title' => "$tr{'shutdown'} / $tr{'reboot'}",
148                                 'enabled' => 1,
149                                 };
150     $subsystem->{'99.credits'} = {
151                                 'caption' => $tr{'credits'},
152                                 'uri' => '/cgi-bin/credits.cgi',
153                                 'title' => "$tr{'credits'}",
154                                 'enabled' => 1,
155                                 };
156
157     my %substatushash = ();
158     my $substatus = \%substatushash;
159     $substatus->{'10.systemstatus'} = {
160                                  'caption' => $tr{'sssystem status'},
161                                  'uri' => '/cgi-bin/status.cgi',
162                                  'title' => "$tr{'sssystem status'}",
163                                  'enabled' => 1,
164                                  };
165     $substatus->{'20.networkstatus'} = {
166                                 'caption' => $tr{'ssnetwork status'},
167                                 'uri' => '/cgi-bin/netstatus.cgi',
168                                 'title' => "$tr{'ssnetwork status'}",
169                                 'enabled' => 1,
170                                 };
171     $substatus->{'30.systemgraphs'} = {
172                                 'caption' => $tr{'system graphs'},
173                                 'uri' => '/cgi-bin/graphs.cgi',
174                                 'novars' => 1,
175                                 'title' => "$tr{'system graphs'}",
176                                 'enabled' => 1,
177                                 };
178     $substatus->{'40.trafficgraphs'} = {
179                                 'caption' => $tr{'sstraffic graphs'},
180                                 'uri' => '/cgi-bin/graphs.cgi',
181                                 'vars' => 'graph=network',
182                                 'title' => "$tr{'sstraffic graphs'}",
183                                 'enabled' => 1,
184                                 };
185     $substatus->{'50.proxygraphs'} = {
186                                 'caption' => $tr{'ssproxy graphs'},
187                                 'uri' => '/cgi-bin/proxygraphs.cgi',
188                                 'title' => "$tr{'ssproxy graphs'}",
189                                 'enabled' => 1,
190                                 };
191     $substatus->{'60.fwhits'} = {
192                                   'caption' => 'Firewall-Diagramme',
193                                   'uri' => '/cgi-bin/fwhits.cgi',
194                                   'title' => "Firewall-Diagramme",
195                                  'enabled' => 1,
196                                   };
197     $substatus->{'70.hddtemp'} = {
198                                   'caption' => "$tr{'harddisk temperature graphs'}",
199                                   'uri' => '/cgi-bin/hddgraph.cgi',
200                                   'title' => "$tr{'harddisk temperature graphs'}",
201                                  'enabled' => 1,
202                                   };
203     $substatus->{'80.connections'} = {
204                                 'caption' => $tr{'connections'},
205                                 'uri' => '/cgi-bin/connections.cgi',
206                                 'title' => "$tr{'connections'}",
207                                 'enabled' => 1,
208                                 };
209     $substatus->{'90.nettraf'} = {
210                                   'caption' => $tr{'sstraffic'},
211                                   'uri' => '/cgi-bin/traffic.cgi',
212                                   'title' => "$tr{'sstraffic'}",
213                                  'enabled' => 1,
214                                   };
215     $substatus->{'99.iptable'} = {
216                                 'caption' => $tr{'iptable rules'},
217                                 'uri' => '/cgi-bin/iptables.cgi',
218                                 'title' => "$tr{'iptable rules'}",
219                                 'enabled' => 1,
220                                 };
221
222     my %subnetworkhash = ();
223     my $subnetwork = \%subnetworkhash;
224
225     $subnetwork->{'10.proxy'} = {'caption' => 'Webproxy',
226                                 'uri' => '/cgi-bin/proxy.cgi',
227                                 'title' => "Webproxy",
228                                 'enabled' => 1,
229                                 };
230     $subnetwork->{'20.urlfilter'} = {'caption' => 'URL-Filter',
231                                 'uri' => '/cgi-bin/urlfilter.cgi',
232                                 'title' => "URL-Filter",
233                                 'enabled' => 1,
234                                 };
235     $subnetwork->{'30.dhcp'} = {'caption' => $tr{'dhcp server'},
236                                  'uri' => '/cgi-bin/dhcp.cgi',
237                                  'title' => "$tr{'dhcp server'}",
238                                  'enabled' => 1,
239                                  };
240     $subnetwork->{'40.dialup'} = {
241                                   'caption' => $tr{'alt dialup'},
242                                   'uri' => '/cgi-bin/pppsetup.cgi',
243                                   'title' => "$tr{'alt dialup'}",
244                                   'enabled' => 1,
245                                   };
246     $subnetwork->{'50.hosts'} = {
247                                  'caption' => $tr{'edit hosts'},
248                                  'uri' => '/cgi-bin/hosts.cgi',
249                                  'title' => "$tr{'edit hosts'}",
250                                  'enabled' => 1,
251                                  };
252     $subnetwork->{'60.upload'} = {
253                                   'caption' => $tr{'upload'},
254                                   'uri' => '/cgi-bin/upload.cgi',
255                                   'title' => "$tr{'upload'}",
256                                   'enabled' => 0,
257                                   };
258     $subnetwork->{'70.aliases'} = {
259                                   'caption' => $tr{'aliases'},
260                                   'uri' => '/cgi-bin/aliases.cgi',
261                                   'title' => "$tr{'aliases'}",
262                                   'enabled' => 0,
263                                   };
264
265     my %subserviceshash = ();
266     my $subservices = \%subserviceshash;
267
268
269     $subservices->{'10.openvpn'} = {
270                                 'caption' => 'OpenVPN',
271                                 'uri' => '/cgi-bin/ovpnmain.cgi',
272                                 'title' => "$tr{'virtual private networking'}",
273                                'enabled' => 1,
274                                 };
275     $subservices->{'20.ipsec'} = {
276                                 'caption' => 'IPSec',
277                                 'uri' => '/cgi-bin/vpnmain.cgi',
278                                 'title' => "$tr{'virtual private networking'}",
279                                 'enabled' => 1,
280                                 };
281     $subservices->{'30.dyndns'} = {'caption' => $tr{'dynamic dns'},
282                                 'uri' => '/cgi-bin/ddns.cgi',
283                                 'title' => "$tr{'dynamic dns'}",
284                                 'enabled' => 1,
285                                 };
286     $subservices->{'40.time'} = {'caption' => $tr{'time server'},
287                                 'uri' => '/cgi-bin/time.cgi',
288                                 'title' => "$tr{'time server'}",
289                                 'enabled' => 1,
290                                 };
291     $subservices->{'50.qos'} = {'caption' => 'Quality of Service',
292                                 'uri' => '/cgi-bin/qos.cgi',
293                                 'title' => "Quality of Service",
294                                 'enabled' => 1,
295                                 };
296     $subservices->{'60.ids'} = {'caption' => $tr{'intrusion detection'},
297                                 'enabled' => 1,
298                                 'uri' => '/cgi-bin/ids.cgi',
299                                 'title' => "$tr{'intrusion detection system'}",
300                                 };
301
302
303
304     my %subfirewallhash = ();
305     my $subfirewall = \%subfirewallhash;
306
307     
308     $subfirewall->{'10.dnat'} = {
309                                  'caption' => $tr{'ssport forwarding'},
310                                  'uri' => '/cgi-bin/portfw.cgi',
311                                  'title' => "$tr{'ssport forwarding'}",
312                                  'enabled' => 1,
313                                  };
314     $subfirewall->{'20.xtaccess'} = {
315                                  'caption' => $tr{'external access'},
316                                  'uri' => '/cgi-bin/xtaccess.cgi',
317                                  'title' => "$tr{'external access'}",
318                                  'enabled' => 1,
319                                  };
320     $subfirewall->{'30.wireless'} = {
321                                 'caption' => $tr{'blue access'},
322                                 'uri' => '/cgi-bin/wireless.cgi',
323                                 'title' => "$tr{'blue access'}",
324                                 'enabled' => 1,
325                                  };
326     $subfirewall->{'40.dmz'} = {
327                                 'caption' => $tr{'ssdmz pinholes'},
328                                 'uri' => '/cgi-bin/dmzholes.cgi',
329                                 'title' => "$tr{'dmz pinhole configuration'}",
330                                 'enabled' => 1,
331                                  };
332     $subfirewall->{'50.outgoing'} = {
333                                 'caption' => $tr{'outgoing firewall'},
334                                 'uri' => '/cgi-bin/outgoingfw.cgi',
335                                 'title' => "$tr{'outgoing firewall'}",
336                                 'enabled' => 1,
337                                 };
338     $subfirewall->{'60.fwopts'} = {
339                                 'caption' => $tr{'options fw'},
340                                 'uri' => '/cgi-bin/optionsfw.cgi',
341                                 'title' => "$tr{'options fw'}",
342                                 'enabled' => 1,
343                                  };
344     
345     my %sublogshash = ();
346     my $sublogs = \%sublogshash;
347
348     $sublogs->{'10.summary'} = {'caption' => $tr{'log summary'},
349                                  'uri' => '/cgi-bin/logs.cgi/summary.dat',
350                                  'title' => "$tr{'log summary'}",
351                                  'enabled' => 1
352                                  };
353     $sublogs->{'20.settings'} = {'caption' => $tr{'log settings'},
354                                  'uri' => '/cgi-bin/logs.cgi/config.dat',
355                                  'title' => "$tr{'log settings'}",
356                                  'enabled' => 1
357                                  };
358     $sublogs->{'30.proxy'} = {'caption' => $tr{'proxy logs'},
359                                  'uri' => '/cgi-bin/logs.cgi/proxylog.dat',
360                                  'title' => "$tr{'proxy logs'}",
361                                  'enabled' => 1
362                                  };
363     $sublogs->{'40.firewall'} = {'caption' => $tr{'firewall logs'},
364                                  'uri' => '/cgi-bin/logs.cgi/firewalllog.dat',
365                                  'title' => "$tr{'firewall logs'}",
366                                  'enabled' => 1
367                                  };
368     $sublogs->{'50.ids'} = {'caption' => $tr{'ids logs'},
369                                 'uri' => '/cgi-bin/logs.cgi/ids.dat',
370                                 'title' => "$tr{'ids logs'}",
371                                 'enabled' => 1
372                                 };
373     $sublogs->{'60.urlfilter'} = {
374                                 'caption' => $tr{'urlfilter log'},
375                                 'uri' => '/cgi-bin/logs.cgi/urlfilter.dat',
376                                 'title' => "$tr{'urlfilter log'}",
377                                 'enabled' => 1,
378                                 };
379     $sublogs->{'70.openvpn'} = {'caption' => $tr{'openvpn log'},
380                                 'uri' => '/cgi-bin/logs.cgi/openvpn.dat',
381                                 'title' => "$tr{'openvpn log'}",
382                                 'enabled' => 1
383                                 };
384     $sublogs->{'80.system'} = {'caption' => $tr{'system logs'},
385                                 'uri' => '/cgi-bin/logs.cgi/log.dat',
386                                 'title' => "$tr{'system logs'}",
387                                 'enabled' => 1
388                                 };
389     $sublogs->{'90.userlog'} = {'caption' => $tr{'user proxy logs'},
390                                 'uri' => '/cgi-bin/logs.cgi/userlog.dat',
391                                 'title' => "$tr{'user log'}",
392                                 'enabled' => 1
393                                 };
394
395     my %subipfirehash = ();
396     my $subipfire = \%subipfirehash;
397     $subipfire->{'10.pakfire'} = {'caption' => 'Pakfire',
398                                   'uri' => '/cgi-bin/pakfire.cgi',
399                                   'title' => "Pakfire",
400                                   'enabled' => 1,
401                                   };
402     $subipfire->{'20.asterisk'} = {'caption' => 'Asterisk',
403                                   'uri' => '/cgi-bin/asterisk.cgi',
404                                   'title' => "Asterisk",
405                                   'enabled' => 1,
406                                   };
407     $subipfire->{'30.samba'} = {'caption' => 'Samba',
408                                   'uri' => '/cgi-bin/samba.cgi',
409                                   'title' => "Samba",
410                                   'enabled' => 1,
411                                   };
412     $subipfire->{'99.help'} = {'caption' => $tr{'help'},
413                                   'uri' => '/cgi-bin/help.cgi',
414                                   'title' => "$tr{'help'}",
415                                   'enabled' => 1,
416                                   };
417
418
419
420     $menu->{'01.system'} = {'caption' => $tr{'alt system'},
421                                 'enabled' => 1,
422                                 'subMenu' => $subsystem
423                                 };
424     $menu->{'02.status'} = {'caption' => $tr{'status'},
425                                 'enabled' => 1,
426                                 'subMenu' => $substatus
427                                 };
428     $menu->{'03.network'} = {'caption' => $tr{'network'},
429                                 'enabled' => 1,
430                                 'subMenu' => $subnetwork
431                                 };
432     $menu->{'04.services'} = {'caption' => $tr{'alt services'},
433                                 'enabled' => 1,
434                                 'subMenu' => $subservices
435                                 };
436     $menu->{'05.firewall'} = {'caption' => $tr{'firewall'},
437                                 'enabled' => 1,
438                                 'subMenu' => $subfirewall
439                                 };
440     $menu->{'06.proxy'} = {'caption' => $tr{'alt proxy'},
441                                 'enabled' => 1,
442                                 'subMenu' => $subproxy
443                                 };
444     $menu->{'07.ipfire'} = {'caption' => 'IPFire',
445                                 'enabled' => 1,
446                                 'subMenu' => $subipfire
447                                 };
448     $menu->{'08.logs'} = {'caption' => $tr{'alt logs'},
449                                 'enabled' => 1,
450                                 'subMenu' => $sublogs
451                                 };
452
453     if (! blue_used() && ! orange_used()) {
454         $menu->{'05.firewall'}{'subMenu'}->{'40.dmz'}{'enabled'} = 0;
455     }
456     if (! blue_used()) {
457         $menu->{'05.firewall'}{'subMenu'}->{'30.wireless'}{'enabled'} = 0;
458     }
459     if (! $ethsettings{'CONFIG_TYPE'} =~ /^(2|3|6|7)$/ && $ethsettings{'RED_TYPE'} eq 'STATIC' ) {
460         $menu->{'03.network'}{'subMenu'}->{'70.aliases'}{'enabled'} = 1;
461     }
462 }
463
464 sub showhttpheaders
465 {
466         print "Pragma: no-cache\n";
467         print "Cache-control: no-cache\n";
468         print "Connection: close\n";
469         print "Content-type: text/html\n\n";
470 }
471
472 sub is_menu_visible($) {
473     my $link = shift;
474     $link =~ s#\?.*$##;
475     return (-e $ENV{'DOCUMENT_ROOT'}."/../$link");
476 }
477
478
479 sub getlink($) {
480     my $root = shift;
481     if (! $root->{'enabled'}) {
482         return '';
483     }
484     if ($root->{'uri'} !~ /^$/) {
485         my $vars = '';
486         if ($root->{'vars'} !~ /^$/) {
487             $vars = '?'. $root->{'vars'};
488         }
489         if (! is_menu_visible($root->{'uri'})) {
490             return '';
491         }
492         return $root->{'uri'}.$vars;
493     }
494     my $submenus = $root->{'subMenu'};
495     if (! $submenus) {
496         return '';
497     }
498     foreach my $item (sort keys %$submenus) {
499         my $link = getlink($submenus->{$item});
500         if ($link ne '') {
501             return $link;
502         }
503     }
504     return '';
505 }
506
507
508 sub compare_url($) {
509     my $conf = shift;
510
511     my $uri = $conf->{'uri'};
512     my $vars = $conf->{'vars'};
513     my $novars = $conf->{'novars'};
514
515     if ($uri eq '') {
516         return 0;
517     }
518     if ($uri ne $URI[0]) {
519         return 0;
520     }
521     if ($novars) {
522         if ($URI[1] !~ /^$/) {
523             return 0;
524         }
525     }
526     if (! $vars) {
527         return 1;
528     }
529     return ($URI[1] eq $vars);
530 }
531
532
533 sub gettitle($) {
534     my $root = shift;
535
536     if (! $root) {
537         return '';
538     }
539     foreach my $item (sort keys %$root) {
540         my $val = $root->{$item};
541         if (compare_url($val)) {
542             $val->{'selected'} = 1;
543             if ($val->{'title'} !~ /^$/) {
544                 return $val->{'title'};
545             }
546             return 'EMPTY TITLE';
547         }
548
549         my $title = gettitle($val->{'subMenu'});
550         if ($title ne '') {
551             $val->{'selected'} = 1;
552             return $title;
553         }
554     }
555     return '';
556 }
557
558
559 sub showmenu() {
560     print <<EOF
561   <div id="menu-top">
562     <ul>
563 EOF
564 ;
565     foreach my $k1 ( sort keys %$menu ) {
566         if (! $menu->{$k1}{'enabled'}) {
567             next;
568         }
569
570         my $link = getlink($menu->{$k1});
571         if ($link eq '') {
572             next;
573         }
574         if (! is_menu_visible($link)) {
575             next;
576         }
577         if ($menu->{$k1}->{'selected'}) {
578             print '<li class="selected">';
579         } else {
580             print '<li>';
581         }
582
583         print <<EOF
584     <div class="rcorner">
585       <a href="$link">$menu->{$k1}{'caption'}</a>
586     </div>
587   </li>
588 EOF
589 ;
590     }
591
592     print <<EOF
593     </ul>
594   </div>
595 EOF
596 ;    
597 }
598
599 sub getselected($) {
600     my $root = shift;
601     if (!$root) {
602         return 0;
603     }
604
605     foreach my $item (%$root) {
606         if ($root->{$item}{'selected'}) {
607             return $root->{$item};
608         }
609     }
610 }
611
612 sub showsubsection($$) {
613     my $root = shift;
614     my $id = shift;
615     if ($id eq '') {
616         $id = 'menu-left';
617     }
618
619     if (! $root) {
620         return;
621     }
622     my $selected = getselected($root);
623     if (! $selected) {
624         return;
625     }
626     my $submenus = $selected->{'subMenu'};
627     if (! $submenus) {
628         return;
629     }
630
631     print <<EOF
632   <div id="$id">
633     <ul>
634 EOF
635 ;
636     foreach my $item (sort keys %$submenus) {
637         my $hash = $submenus->{$item};
638         if (! $hash->{'enabled'}) {
639             next;
640         }
641
642         my $link = getlink($hash);
643         if ($link eq '') {
644             next;
645         }
646         if (! is_menu_visible($link)) {
647             next;
648         }
649         if ($hash->{'selected'}) {
650             print '<li class="selected">';
651         } else {
652             print '<li>';
653         }
654
655         print <<EOF
656       <a href="$link">$hash->{'caption'}</a>
657   </li>
658 EOF
659 ;
660     }
661
662     print <<EOF
663     </ul>
664   </div>
665 EOF
666 ;    
667
668 }
669
670
671 sub showsubsubsection($) {
672     my $root = shift;
673     if (!$root) {
674         return;
675     }
676     my $selected = getselected($root);
677     if (! $selected) {
678         return
679     }
680     if (! $selected->{'subMenu'}) {
681         return
682     }
683
684     showsubsection($selected->{'subMenu'}, 'menu-subtop');
685 }
686
687
688 sub get_helpuri() {
689     my $helpfile = '';
690     if ($URI[0] =~ /.*\/([^\/]+)\.cgi/) {
691         $helpfile = $1;
692     } else {
693         return '';
694     }
695     $helpfile .= '.help.html';
696
697     my $helpuri = '/doc/'.$language.'/'.$helpfile;
698     if (! -e $ENV{'DOCUMENT_ROOT'}.$helpuri) {
699         return '';
700     }
701     return $helpuri;
702 }
703
704
705 sub openpage {
706     my $title = shift;
707     my $boh = shift;
708     my $extrahead = shift;
709
710     @URI=split ('\?',  $ENV{'REQUEST_URI'} );
711     &readhash("${swroot}/main/settings", \%settings);
712     &genmenu();
713
714     my $h2 = gettitle($menu);
715     my $helpuri = get_helpuri();
716
717     $title = "IPFire - $title";
718     if ($settings{'WINDOWWITHHOSTNAME'} eq 'on') {
719         $title =  "$settings{'HOSTNAME'}.$settings{'DOMAINNAME'} - $title"; 
720     }
721
722     print <<END
723 <!DOCTYPE html 
724      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
725      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
726
727 <html>
728   <head>
729   <title>$title</title>
730
731     $extrahead
732     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
733     <meta http-equiv="Page-Enter" content="blendTrans(Duration=0.5,Transition=12)">
734     <meta http-equiv="Page-Exit" content="blendTrans(Duration=0.5,Transition=12)">
735     <link rel="shortcut icon" href="/favicon.ico" />
736     <style type="text/css">\@import url(/include/style.css);</style>
737     <style type="text/css">\@import url(/include/menu.css);</style>
738     <style type="text/css">\@import url(/include/content.css);</style>
739     <script language="javascript" type="text/javascript">
740       
741         function swapVisibility(id) {
742             el = document.getElementById(id);
743             if(el.style.display != 'block') {
744                 el.style.display = 'block'
745             }
746             else {
747                 el.style.display = 'none'
748             }
749         }
750     </script>
751
752   </head>
753   <body>
754 <!-- IPFIRE HEADER -->
755
756 <div id="main">
757
758 <div id="header">
759         <img id="logo-product" src="/images/logo_ipfire.gif">
760    <div id="header-icons">
761             <a href="http://users.ipfire.eu/" target="_blank"><img border="0" src="/images/help.gif"></a>
762    </div>
763 </div>
764
765 END
766 ;
767
768     &showmenu();
769
770 print <<END
771 <div id="content">
772   <table width="90%">
773     <tr>
774       <td valign="top">
775 END
776 ;
777         
778     &showsubsection($menu);
779
780     print <<END
781       <p><center><img src="/images/iptux.png" width='160px' height='160px'></center></p>
782       </td>
783         <td width="100%" valign="top">
784         <div id="page-content">
785             <h2>$h2</h2>
786 END
787     ;
788     
789     &showsubsubsection($menu);
790
791     eval {
792         require 'ipfire-network.pl';
793         $supported = check_support();
794         warn_unsupported($supported);
795     };
796 }
797
798 sub closepage () {
799     my $status = &connectionstatus();
800     $uptime = `/usr/bin/uptime`;
801         
802     print <<END
803           <div align="center">
804             <p>
805               <div style="font-size: 9px"><b>Status:</b> $status <b>Uptime:</b>$uptime</div>
806             </p>
807           </div>
808         </body>
809 </html>
810 END
811 ;
812 }
813
814 sub openbigbox
815 {
816     my $width = $_[0];
817     my $align = $_[1];
818     my $sideimg = $_[2];
819
820     if ($errormessage) {
821         $bgcolor = "style='background-color: $colourerr;'";
822     } else {
823         $bgcolor = '';
824     }
825 }
826
827 sub closebigbox
828 {
829 #       print "</td></tr></table></td></tr></table>\n" 
830 }
831
832 sub openbox
833 {
834         $width = $_[0];
835         $align = $_[1];
836         $caption = $_[2];
837
838         if ($caption) { print "<h3>$caption</h3>\n"; } else { print "&nbsp;"; }
839         
840         print "<table class=\"list\"><tr><td align=\"$align\">\n";
841 }
842
843 sub closebox
844 {
845         print "</td></tr></table><br><br>";
846 }
847
848 sub writehash
849 {
850         my $filename = $_[0];
851         my $hash = $_[1];
852         
853         # write cgi vars to the file.
854         open(FILE, ">${filename}") or die "Unable to write file $filename";
855         flock FILE, 2;
856         foreach $var (keys %$hash) 
857         {
858                 $val = $hash->{$var};
859                 # Darren Critchley Jan 17, 2003 added the following because when submitting with a graphic, the x and y
860                 # location of the mouse are submitted as well, this was being written to the settings file causing
861                 # some serious grief! This skips the variable.x and variable.y
862                 if (!($var =~ /(.x|.y)$/)) {
863                         if ($val =~ / /) {
864                                 $val = "\'$val\'"; }
865                         if (!($var =~ /^ACTION/)) {
866                                 print FILE "${var}=${val}\n"; }
867                 }
868         }
869         close FILE;
870 }
871
872 sub readhash
873 {
874         my $filename = $_[0];
875         my $hash = $_[1];
876         my ($var, $val);
877
878         open(FILE, $filename) or die "Unable to read file $filename";
879         
880         while (<FILE>)
881         {
882                 chop;
883                 ($var, $val) = split /=/, $_, 2;
884                 if ($var)
885                 {
886                         $val =~ s/^\'//g;
887                         $val =~ s/\'$//g;
888
889                         # Untaint variables read from hash
890                         $var =~ /([A-Za-z0-9_-]*)/;        $var = $1;
891                         $val =~ /([\w\W]*)/; $val = $1;
892                         $hash->{$var} = $val;
893                 }
894         }
895         close FILE;
896 }
897
898 sub getcgihash {
899         my ($hash, $params) = @_;
900         my $cgi = CGI->new ();
901         $hash->{'__CGI__'} = $cgi;
902         return if ($ENV{'REQUEST_METHOD'} ne 'POST');
903         if (!$params->{'wantfile'}) {
904                 $CGI::DISABLE_UPLOADS = 1;
905                 $CGI::POST_MAX        = 512 * 1024;
906         } else {
907                 $CGI::POST_MAX = 10 * 1024 * 1024;
908         }
909
910         $cgi->referer() =~ m/^https?\:\/\/([^\/]+)/;
911         my $referer = $1;
912         $cgi->url() =~ m/^https?\:\/\/([^\/]+)/;
913         my $servername = $1;
914         return if ($referer ne $servername);
915
916         ### Modified for getting multi-vars, split by |
917         %temp = $cgi->Vars();
918         foreach my $key (keys %temp) {
919                 $hash->{$key} = $temp{$key};
920                 $hash->{$key} =~ s/\0/|/g;
921                 $hash->{$key} =~ s/^\s*(.*?)\s*$/$1/;
922         }
923
924         if (($params->{'wantfile'})&&($params->{'filevar'})) {
925                 $hash->{$params->{'filevar'}} = $cgi->upload
926                                                 ($params->{'filevar'});
927         }
928         return;
929 }
930
931 sub log
932 {
933         my $logmessage = $_[0];
934         $logmessage =~ /([\w\W]*)/;
935         $logmessage = $1;
936         system('/usr/bin/logger', '-t', 'ipfire', $logmessage);
937 }
938
939 sub age
940 {
941         my ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
942                 $atime, $mtime, $ctime, $blksize, $blocks) = stat $_[0];
943         my $now = time;
944
945         my $totalsecs = $now - $mtime;
946         my $days = int($totalsecs / 86400);
947         my $totalhours = int($totalsecs / 3600);
948         my $hours = $totalhours % 24;
949         my $totalmins = int($totalsecs / 60);
950         my $mins = $totalmins % 60;
951         my $secs = $totalsecs % 60;
952
953         return "${days}d ${hours}h ${mins}m ${secs}s";
954 }
955
956 sub validip
957 {
958         my $ip = $_[0];
959
960         if (!($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/)) {
961                 return 0; }
962         else 
963         {
964                 @octets = ($1, $2, $3, $4);
965                 foreach $_ (@octets)
966                 {
967                         if (/^0./) {
968                                 return 0; }
969                         if ($_ < 0 || $_ > 255) {
970                                 return 0; }
971                 }
972                 return 1;
973         }
974 }
975
976 sub validmask
977 {
978         my $mask = $_[0];
979
980         # secord part an ip?
981         if (&validip($mask)) {
982                 return 1; }
983         # second part a number?
984         if (/^0/) {
985                 return 0; }
986         if (!($mask =~ /^\d+$/)) {
987                 return 0; }
988         if ($mask >= 0 && $mask <= 32) {
989                 return 1; }
990         return 0;
991 }
992
993 sub validipormask
994 {
995         my $ipormask = $_[0];
996
997         # see if it is a IP only.
998         if (&validip($ipormask)) {
999                 return 1; }
1000         # split it into number and mask.
1001         if (!($ipormask =~ /^(.*?)\/(.*?)$/)) {
1002                 return 0; }
1003         $ip = $1;
1004         $mask = $2;
1005         # first part not a ip?
1006         if (!(&validip($ip))) {
1007                 return 0; }
1008         return &validmask($mask);
1009 }
1010
1011 sub validipandmask
1012 {
1013         my $ipandmask = $_[0];
1014
1015         # split it into number and mask.
1016         if (!($ipandmask =~ /^(.*?)\/(.*?)$/)) {
1017                 return 0; }
1018         $ip = $1;
1019         $mask = $2;
1020         # first part not a ip?
1021         if (!(&validip($ip))) {
1022                 return 0; }
1023         return &validmask($mask);
1024 }
1025
1026 sub validport
1027 {
1028         $_ = $_[0];
1029
1030         if (!/^\d+$/) {
1031                 return 0; }
1032         if (/^0./) {
1033                 return 0; }
1034         if ($_ >= 1 && $_ <= 65535) {
1035                 return 1; }
1036         return 0;
1037 }
1038
1039 sub validmac
1040 {
1041         my $checkmac = $_[0];
1042         my $ot = '[0-9a-f]{2}'; # 2 Hex digits (one octet)
1043         if ($checkmac !~ /^$ot:$ot:$ot:$ot:$ot:$ot$/i)
1044         {
1045                 return 0;
1046         }
1047         return 1;
1048 }
1049
1050 sub validhostname
1051 {
1052         # Checks a hostname against RFC1035
1053         my $hostname = $_[0];
1054
1055         # Each part should be at least two characters in length
1056         # but no more than 63 characters
1057         if (length ($hostname) < 2 || length ($hostname) > 63) {
1058                 return 0;}
1059         # Only valid characters are a-z, A-Z, 0-9 and -
1060         if ($hostname !~ /^[a-zA-Z0-9-]*$/) {
1061                 return 0;}
1062         # First character can only be a letter or a digit
1063         if (substr ($hostname, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
1064                 return 0;}
1065         # Last character can only be a letter or a digit
1066         if (substr ($hostname, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
1067                 return 0;}
1068         return 1;
1069 }
1070
1071 sub validdomainname
1072 {
1073         # Checks a domain name against RFC1035
1074         my $domainname = $_[0];
1075         my @parts = split (/\./, $domainname);  # Split hostname at the '.'
1076
1077         foreach $part (@parts) {
1078                 # Each part should be at least two characters in length
1079                 # but no more than 63 characters
1080                 if (length ($part) < 2 || length ($part) > 63) {
1081                         return 0;}
1082                 # Only valid characters are a-z, A-Z, 0-9 and -
1083                 if ($part !~ /^[a-zA-Z0-9-]*$/) {
1084                         return 0;}
1085                 # First character can only be a letter or a digit
1086                 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
1087                         return 0;}
1088                 # Last character can only be a letter or a digit
1089                 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
1090                         return 0;}
1091         }
1092         return 1;
1093 }
1094
1095 sub validfqdn
1096 {
1097         # Checks a fully qualified domain name against RFC1035
1098         my $fqdn = $_[0];
1099         my @parts = split (/\./, $fqdn);        # Split hostname at the '.'
1100         if (scalar(@parts) < 2) {               # At least two parts should
1101                 return 0;}                      # exist in a FQDN
1102                                                 # (i.e. hostname.domain)
1103         foreach $part (@parts) {
1104                 # Each part should be at least two characters in length
1105                 # but no more than 63 characters
1106                 if (length ($part) < 2 || length ($part) > 63) {
1107                         return 0;}
1108                 # Only valid characters are a-z, A-Z, 0-9 and -
1109                 if ($part !~ /^[a-zA-Z0-9-]*$/) {
1110                         return 0;}
1111                 # First character can only be a letter or a digit
1112                 if (substr ($part, 0, 1) !~ /^[a-zA-Z0-9]*$/) {
1113                         return 0;}
1114                 # Last character can only be a letter or a digit
1115                 if (substr ($part, -1, 1) !~ /^[a-zA-Z0-9]*$/) {
1116                         return 0;}
1117         }
1118         return 1;
1119 }
1120
1121 sub validportrange # used to check a port range 
1122 {
1123         my $port = $_[0]; # port values
1124         $port =~ tr/-/:/; # replace all - with colons just in case someone used -
1125         my $srcdst = $_[1]; # is it a source or destination port
1126
1127         if (!($port =~ /^(\d+)\:(\d+)$/)) {
1128         
1129                 if (!(&validport($port))) {      
1130                         if ($srcdst eq 'src'){
1131                                 return $tr{'source port numbers'};
1132                         } else  {
1133                                 return $tr{'destination port numbers'};
1134                         } 
1135                 }
1136         }
1137         else 
1138         {
1139                 @ports = ($1, $2);
1140                 if ($1 >= $2){
1141                         if ($srcdst eq 'src'){
1142                                 return $tr{'bad source range'};
1143                         } else  {
1144                                 return $tr{'bad destination range'};
1145                         } 
1146                 }
1147                 foreach $_ (@ports)
1148                 {
1149                         if (!(&validport($_))) {
1150                                 if ($srcdst eq 'src'){
1151                                         return $tr{'source port numbers'}; 
1152                                 } else  {
1153                                         return $tr{'destination port numbers'};
1154                                 } 
1155                         }
1156                 }
1157                 return;
1158         }
1159 }
1160
1161 # Test if IP is within a subnet
1162 # Call: IpInSubnet (Addr, Subnet, Subnet Mask)
1163 #       Subnet can be an IP of the subnet: 10.0.0.0 or 10.0.0.1
1164 #       Everything in dottted notation
1165 # Return: TRUE/FALSE
1166 sub IpInSubnet
1167 {
1168     $ip = unpack('N', inet_aton(shift));
1169     $start = unpack('N', inet_aton(shift));
1170     $mask  = unpack('N', inet_aton(shift));
1171     $start &= $mask;  # base of subnet...
1172     $end   = $start + ~$mask;
1173     return (($ip >= $start) && ($ip <= $end));
1174 }
1175
1176 sub validemail {
1177     my $mail = shift;
1178     return 0 if ( $mail !~ /^[0-9a-zA-Z\.\-\_]+\@[0-9a-zA-Z\.\-]+$/ );
1179     return 0 if ( $mail =~ /^[^0-9a-zA-Z]|[^0-9a-zA-Z]$/);
1180     return 0 if ( $mail !~ /([0-9a-zA-Z]{1})\@./ );
1181     return 0 if ( $mail !~ /.\@([0-9a-zA-Z]{1})/ );
1182     return 0 if ( $mail =~ /.\.\-.|.\-\..|.\.\..|.\-\-./g );
1183     return 0 if ( $mail =~ /.\.\_.|.\-\_.|.\_\..|.\_\-.|.\_\_./g );
1184     return 0 if ( $mail !~ /\.([a-zA-Z]{2,3})$/ );
1185     return 1;
1186 }
1187
1188 sub readhasharray {
1189     my ($filename, $hash) = @_;
1190
1191     open(FILE, $filename) or die "Unable to read file $filename";
1192
1193     while (<FILE>) {
1194         my ($key, $rest, @temp);
1195         chomp;
1196         ($key, $rest) = split (/,/, $_, 2);
1197         if ($key =~ /^[0-9]+$/ && $rest) {
1198             @temp = split (/,/, $rest);
1199             $hash->{$key} = \@temp;
1200         }
1201     }
1202     close FILE;
1203     return;
1204 }
1205
1206 sub writehasharray {
1207     my ($filename, $hash) = @_;
1208     my ($key, @temp);
1209
1210     open(FILE, ">$filename") or die "Unable to write to file $filename";
1211
1212     foreach $key (keys %$hash) {
1213         if ( $hash->{$key} ) {
1214             print FILE "$key";
1215             foreach $i (0 .. $#{$hash->{$key}}) {
1216                 print FILE ",$hash->{$key}[$i]";
1217             }
1218         }
1219         print FILE "\n";
1220     }
1221     close FILE;
1222     return;
1223 }
1224
1225 sub findhasharraykey {
1226     foreach my $i (1 .. 1000000) {
1227         if ( ! exists $_[0]{$i}) {
1228              return $i;
1229         }
1230     }
1231 }
1232
1233 sub cleanhtml
1234 {
1235         my $outstring =$_[0];
1236         $outstring =~ tr/,/ / if not defined $_[1] or $_[1] ne 'y';
1237         $outstring =~ s/&/&amp;/g;
1238         $outstring =~ s/\'/&#039;/g;
1239         $outstring =~ s/\"/&quot;/g;
1240         $outstring =~ s/</&lt;/g;
1241         $outstring =~ s/>/&gt;/g;
1242         return $outstring;
1243 }
1244
1245 sub connectionstatus
1246 {
1247     my %pppsettings = ();
1248     my %netsettings = ();
1249     my $iface='';
1250
1251     $pppsettings{'PROFILENAME'} = 'None';
1252     &General::readhash("${General::swroot}/ppp/settings", \%pppsettings);
1253     &General::readhash("${General::swroot}/ethernet/settings", \%netsettings);
1254
1255     my $profileused='';
1256     if ( ! ( $netsettings{'CONFIG_TYPE'} =~ /^(2|3|6|7)$/ && $netsettings{'RED_TYPE'} =~ /^(DHCP|STATIC)$/ ) ) {
1257         $profileused="- $pppsettings{'PROFILENAME'}";
1258     }
1259
1260     if ( ( $pppsettings{'METHOD'} eq 'DHCP' && $netsettings{'RED_TYPE'} ne 'PPTP') 
1261                                                 || $netsettings{'RED_TYPE'} eq 'DHCP' ) {
1262                 if (open(IFACE, "${General::swroot}/red/iface")) {
1263                         $iface = <IFACE>;
1264                         close IFACE;
1265                         chomp ($iface);
1266                         $iface =~ /([a-zA-Z0-9]*)/; $iface = $1;
1267                 }
1268     }
1269
1270     my ($timestr, $connstate);
1271     if ($netsettings{'CONFIG_TYPE'} =~ /^(0|1|4|5)$/ &&  $pppsettings{'TYPE'} =~ /^isdn/) {
1272         # Count ISDN channels
1273         my ($idmap, $chmap, $drmap, $usage, $flags, $phone);
1274         my @phonenumbers;
1275         my $count=0;
1276
1277         open (FILE, "/dev/isdninfo");
1278
1279         $idmap = <FILE>; chop $idmap;
1280         $chmap = <FILE>; chop $chmap;
1281         $drmap = <FILE>; chop $drmap;
1282         $usage = <FILE>; chop $usage;
1283         $flags = <FILE>; chop $flags;
1284         $phone = <FILE>; chop $phone;
1285
1286         $phone =~ s/^phone(\s*):(\s*)//;
1287
1288         @phonenumbers = split / /, $phone;
1289
1290         foreach (@phonenumbers) {
1291                 if ($_ ne '???') {
1292                         $count++;
1293                 }
1294         }
1295         close (FILE);
1296
1297         ## Connection status
1298         my $number;
1299         if ($count == 0) {
1300                 $number = 'none!';
1301         } elsif ($count == 1) {
1302                 $number = 'single';
1303         } else {
1304                 $number = 'dual';
1305         }
1306
1307         if (-e "${General::swroot}/red/active") {
1308                 $timestr = &General::age("${General::swroot}/red/active");
1309                 $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connected'} - $number channel (<span class='ipcop_StatusBigRed'>$timestr</span>) $profileused</span>";
1310         } else {
1311                 if ($count == 0) {
1312                         if (-e "${General::swroot}/red/dial-on-demand") {
1313                                 $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'dod waiting'} $profileused</span>";
1314                         } else {
1315                                 $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'idle'} $profileused</span>";
1316                         }
1317                 } else {
1318                         $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connecting'} $profileused</span>";
1319                 }
1320         }
1321     } elsif ($netsettings{'RED_TYPE'} eq "STATIC" || $pppsettings {'METHOD'} eq 'STATIC') {
1322         if (-e "${General::swroot}/red/active") {
1323                 $timestr = &General::age("${General::swroot}/red/active");
1324                 $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connected'} (<span class='ipcop_StatusBigRed'>$timestr</span>) $profileused</span>";
1325         } else {
1326                 $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'idle'} $profileused</span>";
1327         }
1328     } elsif ( ( (-e "${General::swroot}/dhcpc/dhcpcd-$iface.pid") && $netsettings{'RED_TYPE'} ne 'PPTP' ) || 
1329         !system("/bin/ps -ef | /bin/grep -q '[p]ppd'") || !system("/bin/ps -ef | /bin/grep -q '[c]onnectioncheck'")) {
1330         if (-e "${General::swroot}/red/active") {
1331                 $timestr = &General::age("${General::swroot}/red/active");
1332                 if ($pppsettings{'TYPE'} =~ /^(modem|bewanadsl|conexantpciadsl|eagleusbadsl)$/) {
1333                         my $speed;
1334                         if ($pppsettings{'TYPE'} eq 'modem') {
1335                                 open(CONNECTLOG, "/var/log/connect.log");
1336                                 while (<CONNECTLOG>) {
1337                                         if (/CONNECT/) {
1338                                                 $speed = (split / /)[6];
1339                                         }
1340                                 }
1341                                 close (CONNECTLOG);
1342                         } elsif ($pppsettings{'TYPE'} eq 'bewanadsl') {
1343                                 $speed = `/usr/bin/unicorn_status | /bin/grep Rate | /usr/bin/cut -f2 -d ':'`;
1344                         } elsif ($pppsettings{'TYPE'} eq 'conexantpciadsl') {
1345                                 $speed = `/bin/cat /proc/net/atm/CnxAdsl:* | /bin/grep 'Line Rates' | /bin/sed -e 's+Line Rates:   Receive+Rx+' -e 's+Transmit+Tx+'`;
1346                         } elsif ($pppsettings{'TYPE'} eq 'eagleusbadsl') {
1347                                 $speed = `/usr/sbin/eaglestat | /bin/grep Rate`;
1348                         }
1349                         $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connected'} (<span class='ipcop_StatusBigRed'>$timestr</span>) $profileused (\@$speed)</span>";
1350                 } else {
1351                         $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connected'} (<span class='ipcop_StatusBigRed'>$timestr</span>) $profileused</span>";
1352                 }
1353         } else {
1354                 if (-e "${General::swroot}/red/dial-on-demand") {
1355                     $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'dod waiting'} $profileused</span>";
1356                 } else {
1357                     $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'connecting'} $profileused</span>";
1358                 }
1359         }
1360     } else {
1361         $connstate = "<span class='ipcop_StatusBig'>$Lang::tr{'idle'} $profileused</span>";
1362     }
1363     return $connstate;
1364 }
1365
1366 sub srtarray 
1367 # Darren Critchley - darrenc@telus.net - (c) 2003
1368 # &srtarray(SortOrder, AlphaNumeric, SortDirection, ArrayToBeSorted)
1369 # This subroutine will take the following parameters:
1370 #   ColumnNumber = the column which you want to sort on, starts at 1
1371 #   AlphaNumberic = a or n (lowercase) defines whether the sort should be alpha or numberic
1372 #   SortDirection = asc or dsc (lowercase) Ascending or Descending sort
1373 #   ArrayToBeSorted = the array that wants sorting
1374 #
1375 #   Returns an array that is sorted to your specs
1376 #
1377 #   If SortOrder is greater than the elements in array, then it defaults to the first element
1378
1379 {
1380         my ($colno, $alpnum, $srtdir, @tobesorted) = @_;
1381         my @tmparray;
1382         my @srtedarray;
1383         my $line;
1384         my $newline;
1385         my $ttlitems = scalar @tobesorted; # want to know the number of rows in the passed array
1386         if ($ttlitems < 1){ # if no items, don't waste our time lets leave
1387                 return (@tobesorted);
1388         }
1389         my @tmp = split(/\,/,$tobesorted[0]);
1390         $ttlitems = scalar @tmp; # this should be the number of elements in each row of the passed in array
1391
1392         # Darren Critchley - validate parameters
1393         if ($colno > $ttlitems){$colno = '1';}
1394         $colno--; # remove one from colno to deal with arrays starting at 0
1395         if($colno < 0){$colno = '0';}
1396         if ($alpnum ne '') { $alpnum = lc($alpnum); } else { $alpnum = 'a'; }
1397         if ($srtdir ne '') { $srtdir = lc($srtdir); } else { $srtdir = 'src'; }
1398
1399         foreach $line (@tobesorted)
1400         {
1401                 chomp($line);
1402                 if ($line ne '') {
1403                         my @temp = split(/\,/,$line);
1404                         # Darren Critchley - juggle the fields so that the one we want to sort on is first
1405                         my $tmpholder = $temp[0];
1406                         $temp[0] = $temp[$colno];
1407                         $temp[$colno] = $tmpholder;
1408                         $newline = "";
1409                         for ($ctr=0; $ctr < $ttlitems ; $ctr++) {
1410                                 $newline=$newline . $temp[$ctr] . ",";
1411                         }
1412                         chop($newline);
1413                         push(@tmparray,$newline);
1414                 }
1415         }
1416         if ($alpnum eq 'n') {
1417                 @tmparray = sort {$a <=> $b} @tmparray;
1418         } else {
1419                 @tmparray = (sort @tmparray);
1420         }
1421         foreach $line (@tmparray)
1422         {
1423                 chomp($line);
1424                 if ($line ne '') {
1425                         my @temp = split(/\,/,$line);
1426                         my $tmpholder = $temp[0];
1427                         $temp[0] = $temp[$colno];
1428                         $temp[$colno] = $tmpholder;
1429                         $newline = "";
1430                         for ($ctr=0; $ctr < $ttlitems ; $ctr++){
1431                                 $newline=$newline . $temp[$ctr] . ",";
1432                         }
1433                         chop($newline);
1434                         push(@srtedarray,$newline);
1435                 }
1436         }
1437
1438         if ($srtdir eq 'dsc') {
1439                 @tmparray = reverse(@srtedarray);
1440                 return (@tmparray);
1441         } else {
1442                 return (@srtedarray);
1443         }
1444 }
1445
1446 sub speedtouchversion
1447 {
1448         if (-f "/proc/bus/usb/devices")
1449         {
1450                 $speedtouch=`/bin/cat /proc/bus/usb/devices | /bin/grep 'Vendor=06b9 ProdID=4061' | /usr/bin/cut -d ' ' -f6`;
1451                 if ($speedtouch eq '') {
1452                         $speedtouch= $tr{'connect the modem'};
1453                 }
1454         } else {
1455                 $speedtouch='USB '.$tr{'not running'};
1456         }
1457         return $speedtouch
1458 }
1459
1460 sub CheckSortOrder {
1461 #Sorting of allocated leases
1462     if ($ENV{'QUERY_STRING'} =~ /^IPADDR|^ETHER|^HOSTNAME|^ENDTIME/ ) {
1463         my $newsort=$ENV{'QUERY_STRING'};
1464         &readhash("${swroot}/dhcp/settings", \%dhcpsettings);
1465         $act=$dhcpsettings{'SORT_LEASELIST'};
1466         #Reverse actual ?
1467         if ($act =~ $newsort) {
1468             if ($act !~ 'Rev') {$Rev='Rev'};
1469             $newsort.=$Rev
1470         };
1471
1472         $dhcpsettings{'SORT_LEASELIST'}=$newsort;
1473         &writehash("${swroot}/dhcp/settings", \%dhcpsettings);
1474         $dhcpsettings{'ACTION'} = 'SORT';  # avoid the next test "First lauch"
1475     }
1476
1477 }
1478
1479 sub PrintActualLeases
1480 {
1481     &openbox('100%', 'left', $tr{'current dynamic leases'});
1482     print <<END
1483 <table width='100%'>
1484 <tr>
1485 <td width='25%' align='center'><a href='$ENV{'SCRIPT_NAME'}?IPADDR'><b>$tr{'ip address'}</b></a></td>
1486 <td width='25%' align='center'><a href='$ENV{'SCRIPT_NAME'}?ETHER'><b>$tr{'mac address'}</b></a></td>
1487 <td width='20%' align='center'><a href='$ENV{'SCRIPT_NAME'}?HOSTNAME'><b>$tr{'hostname'}</b></a></td>
1488 <td width='30%' align='center'><a href='$ENV{'SCRIPT_NAME'}?ENDTIME'><b>$tr{'lease expires'} (local time d/m/y)</b></a></td>
1489 </tr>
1490 END
1491     ;
1492
1493     open(LEASES,"/var/state/dhcp/dhcpd.leases") or die "Can't open dhcpd.leases";
1494     while ($line = <LEASES>) {
1495         next if( $line =~ /^\s*#/ );
1496         chomp($line);
1497         @temp = split (' ', $line);
1498
1499         if ($line =~ /^\s*lease/) {
1500             $ip = $temp[1];
1501             #All field are not necessarily read. Clear everything
1502             $endtime = 0;
1503             $ether = "";
1504             $hostname = "";
1505         }
1506
1507         if ($line =~ /^\s*ends/) {
1508             $line =~ /(\d+)\/(\d+)\/(\d+) (\d+):(\d+):(\d+)/;
1509             $endtime = timegm($6, $5, $4, $3, $2 - 1, $1 - 1900);
1510         }
1511
1512         if ($line =~ /^\s*hardware ethernet/) {
1513             $ether = $temp[2];
1514             $ether =~ s/;//g;
1515         }
1516
1517         if ($line =~ /^\s*client-hostname/) {
1518             $hostname = "$temp[1] $temp[2] $temp[3]";
1519             $hostname =~ s/;//g;
1520             $hostname =~ s/\"//g;
1521         }
1522
1523         if ($line eq "}") {
1524             @record = ('IPADDR',$ip,'ENDTIME',$endtime,'ETHER',$ether,'HOSTNAME',$hostname);
1525             $record = {};                                       # create a reference to empty hash
1526             %{$record} = @record;                               # populate that hash with @record
1527             $entries{$record->{'IPADDR'}} = $record;    # add this to a hash of hashes
1528         }
1529     }
1530     close(LEASES);
1531
1532     my $id = 0;
1533     foreach my $key (sort leasesort keys %entries) {
1534
1535         my $hostname = &cleanhtml($entries{$key}->{HOSTNAME},"y");
1536
1537         if ($id % 2) {
1538             print "<tr bgcolor='$table1colour'>"; 
1539         }
1540         else {
1541             print "<tr bgcolor='$table2colour'>"; 
1542         }
1543
1544         print <<END
1545 <td align='center'>$entries{$key}->{IPADDR}</td>
1546 <td align='center'>$entries{$key}->{ETHER}</td>
1547 <td align='center'>&nbsp;$hostname </td>
1548 <td align='center'>
1549 END
1550         ;
1551
1552         ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $dst) = localtime ($entries{$key}->{ENDTIME});
1553         $enddate = sprintf ("%02d/%02d/%d %02d:%02d:%02d",$mday,$mon+1,$year+1900,$hour,$min,$sec);
1554
1555         if ($entries{$key}->{ENDTIME} < time() ){
1556             print "<strike>$enddate</strike>";
1557         } else {
1558             print "$enddate";
1559         }
1560         print "</td></tr>";
1561         $id++;
1562     }
1563
1564     print "</table>";
1565     &closebox();
1566 }
1567
1568
1569 # This sub is used during display of actives leases
1570 sub leasesort {
1571     if (rindex ($dhcpsettings{'SORT_LEASELIST'},'Rev') != -1)
1572     {
1573         $qs=substr ($dhcpsettings{'SORT_LEASELIST'},0,length($dhcpsettings{'SORT_LEASELIST'})-3);
1574         if ($qs eq 'IPADDR') {
1575             @a = split(/\./,$entries{$a}->{$qs});
1576             @b = split(/\./,$entries{$b}->{$qs});
1577             ($b[0]<=>$a[0]) ||
1578             ($b[1]<=>$a[1]) ||
1579             ($b[2]<=>$a[2]) ||
1580             ($b[3]<=>$a[3]);
1581         }else {
1582             $entries{$b}->{$qs} cmp $entries{$a}->{$qs};
1583         }
1584     }
1585     else #not reverse
1586     {
1587         $qs=$dhcpsettings{'SORT_LEASELIST'};
1588         if ($qs eq 'IPADDR') {
1589             @a = split(/\./,$entries{$a}->{$qs});
1590             @b = split(/\./,$entries{$b}->{$qs});
1591             ($a[0]<=>$b[0]) ||
1592             ($a[1]<=>$b[1]) ||
1593             ($a[2]<=>$b[2]) ||
1594             ($a[3]<=>$b[3]);
1595         }else {
1596             $entries{$a}->{$qs} cmp $entries{$b}->{$qs};
1597         }
1598     }
1599 }
1600
1601 sub get_uplinks() {
1602     my @uplinks = ();
1603     opendir(DIR, "${swroot}/uplinks/") || return \@uplinks;
1604     foreach my $dir (readdir(DIR)) {
1605         next if ($dir =~ /^\./);
1606         next if (-f "${swroot}/uplinks/$dir");
1607         push(@uplinks, $dir);
1608     }
1609     closedir(DIR);
1610     return \@uplinks;
1611 }
1612
1613 sub get_iface($) {
1614     my $filename = shift;
1615     chomp($filename);
1616     open (F, $filename) || return "";
1617     my $iface = <F>;
1618     close(F);
1619     chomp($iface);
1620     return $iface;
1621 }
1622
1623 sub get_red_ifaces_by_type($) {
1624     my $type=shift;
1625     my @gottypeiface = ();
1626     my @gottypeuplink = ();
1627     my @gottype = ();
1628
1629     my $ref=get_uplinks();
1630     my @uplinks=@$ref;
1631     my %set = ();
1632     foreach my $link (@uplinks) {
1633         eval {
1634             &readhash("${swroot}/uplinks/$link/settings", \%set);
1635         };
1636         push(@gottype, $link);
1637
1638         my $iface = $set{'RED_DEV'};
1639         if (!$iface) {
1640             $iface = get_iface("${swroot}/uplinks/$link/interface");
1641         }
1642         next if (!$iface);
1643
1644         if ($set{'RED_TYPE'} eq $type) {
1645             push(@gottypeiface, $iface);
1646             push(@gottypeuplink, $link);
1647         }
1648     }
1649     return (\@gottypeiface, \@gottypeuplink, \@gottype);
1650 }
1651
1652 sub get_red_ifaces() {
1653     return `cat ${swroot}/uplinks/*/interface 2>/dev/null`;
1654 }
1655
1656 sub get_zone_devices($) {
1657     my $bridge = shift;
1658     my @ifaces = ();
1659     open (FILE, "${swroot}/ethernet/$bridge") || return "";
1660     foreach my $line (<FILE>) {
1661         chomp($line);
1662         next if (!$line);
1663         push(@ifaces, $line);
1664     }
1665     close(FILE);
1666     return \@ifaces;
1667 }