ping host and offer wake-on-lan if down
[pxelator] / lib / PXElator / httpd.pm
1 package httpd;
2
3 use warnings;
4 use strict;
5 use autodie;
6
7 =head1 httpd
8
9 Start with:
10
11   perl -Ilib/PXElator -Mhttpd -e httpd::start
12
13 =cut
14
15 use Data::Dump qw/dump/;
16 use Carp qw/confess/;
17 use File::Slurp;
18 #use JSON;
19 use IO::Socket::INET;
20 use Regexp::Common qw/net/;
21
22 sub menu {qq{
23
24 <div style="font-size: 80%; color: #888">
25 <a href=/>home</a>
26 <a href=/server>server</a>
27 <a href=/brctl>brctl</a>
28 <a href=/ip>ip</a>
29 <a href=/nmap>nmap</a>
30 <a href=/client>client</a>
31 </div>
32
33 }}
34
35 our $port = 7777;
36
37 use server;
38 our $debug = server::debug;
39 our $url = "http://$server::ip:$port";
40
41 use html;
42 our $static_pids;
43 use progress_bar;
44 use config;
45 use client;
46 use log;
47 use x11;
48 use amt;
49 use boolean;
50 use daemons;
51
52 use kvm;
53 use browser;
54 use network;
55 use ip;
56 use wireshark;
57 use syslogd;
58 use nmap;
59 use ping;
60 use wol;
61
62 use CouchDB;
63
64 sub static {
65         my ($client,$path) = @_;
66
67         my $full = "$server::base_dir/tftp/$path";
68
69         return if ! -f $full;
70
71         if ( my $pid = fork ) {
72                 # parent
73                 close($client);
74                 $static_pids->{$pid} = $path;
75                 return 1;
76         }
77
78         my $type = 'application/octet-stream';
79         $type = 'text/html' if $path =~ m{\.htm};
80         $type = 'application/javascript' if $path =~ m{\.js};
81         $type = 'text/plain' if $path =~ m{\.txt};
82
83         my $size = -s $full || return;
84
85         print $client "HTTP/1.0 200 OK\r\nContent-Type: $type\r\nContent-Length: $size\r\nConnection: close\r\n\r\n";
86
87         open(my $fh, $full);
88
89         my $block = 1400; # try not to fragment packages (pxelinux seems to have problems with it)
90         my $buff;
91         my $pos = 0;
92
93         CouchDB::audit( 'static', { pid => $$, path => $path, type => $type, size => $size, block => $block, peerhost => $client->peerhost });
94
95         progress_bar::start;
96
97         while( my $len = read $fh, $buff, $block ) {
98                 print $client $buff;
99                 $client->flush;
100                 $pos += $len;
101                 progress_bar::tick( $path, $pos, $size );
102         }
103         close($fh);
104         close($client);
105
106         print STDERR "\n";
107
108         exit(0);
109 }
110
111 sub ok {
112         qq|HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n| . menu()
113 }
114
115 sub redirect {
116         my $to = shift;
117         $to ||= $url;
118         qq|HTTP/1.1 302 Found\r\nContent-type: text/html\r\nLocation: $to\r\n\r\n|
119 }
120
121 sub get_request {
122         my ( $client, $path, $param ) = @_;
123
124         server->refresh;
125
126         CouchDB::audit( 'request', { path => $path, param => $param, peerhost => $client->peerhost } );
127
128         if ( my $found = static( $client,$path ) ) {
129                 warn "static $found" if $debug;
130         } elsif ( $path eq '/' ) {
131
132                 my @rows;
133
134                 my $debug_proc = '';
135
136 warn "XXX pids = ", dump( $daemons::pids );
137
138                 foreach my $name ( sort keys %$daemons::pids ) {
139                         my $pid = $daemons::pids->{$name}; # || next;
140
141                         my $html;
142
143                         my $proc = "/proc/$pid/status";
144
145                         if ( -e $proc ) {
146                                 $html .= qq|<a href=/start_stop/$name>$pid</a>|;
147                                 if ( $debug ) {
148                                         $html .= qq| <a name=$pid href=#proc-$pid>?</a>| if $name->can('start');
149
150                                         $debug_proc
151                                                 .= qq|<a name=proc-$pid href=#$pid>$proc</a><pre style="font-size: 10%">|
152                                                 .  read_file($proc)
153                                                 .  qq|</pre>|
154                                                 ;
155                                 }
156
157                                 if ( $name->can('fork_if_active') ) {
158                                         $html .= qq| <a href=/start_stop/$name/$_>$_</a>| foreach $name->fork_if_active;
159                                 }
160
161                                 if ( $name->can('actions') ) {
162                                         $html .= qq| <a href=/action/$name/$_>$_</a>| foreach $name->actions;
163                                 }
164                         } else {
165                                 if ( $pid =~ m{^\d+$} ) {
166                                         $html .= qq|$pid exited |
167                                 } else {
168                                         $html .= qq|$pid |;
169                                 }
170                                 $html .= qq|<a href=/start_stop/$name>restart</a>| if $pid || $name->can('start');
171                                 if ( $name->can('fork_actions') ) {
172                                         $html .= qq| <a href=/start_stop/$name/$_>$_</a>| foreach $name->fork_actions;
173                                 }
174                         }
175
176                         die "no html generated" unless $html;
177
178                         push @rows, ( $name => $html );
179                 }
180
181                 my $below_table = '';
182
183                 warn 'static_pids: ', dump( $static_pids ) if $debug;
184                 foreach my $pid ( keys %$static_pids ) {
185                         my $path = $static_pids->{$pid};
186                         if ( -d "/proc/$pid" ) {
187                                 push @rows, ( $path => qq|<a href=/kill/static/$pid>$pid</a>| );
188                         } elsif ( $param->{clean_completed_downloads} ) {
189                                 delete $static_pids->{$pid}
190                         } else {
191                                 push @rows, ( $path => "$pid competed" );
192                                 $below_table = qq|<a href="/?clean_completed_downloads=1">clean completed downloads</a>|;
193                         }
194                 }
195
196                 print $client ok
197                         , html::table( 2, @rows )
198                         , $below_table
199                         , html::tabs( log::mac_changes )
200                         , $debug_proc
201                         ;
202
203         } elsif ( $path =~ m{^/server} ) {
204                 print $client ok
205                         , html::table( 2,
206                                 'debug' => qq|<a href=/our/debug/| . boolean::toggle($debug) . qq|>$debug</a>|,
207                                  map {
208                                         ( $_, html::tt eval '$server::'.$_ )
209                                  } ( 'ip', 'netmask', 'ip_from', 'ip_to', 'domain_name', 'base_dir', 'conf' )
210                         )
211                         ;
212         } elsif ( $path =~ m!^/client(?:/$RE{net}{IPv4}{-keep})?! ) {
213                 my $ip = $1;
214
215                 if ( $param->{action} eq 'remove' ) {
216                         client::remove( $param->{change_ip} );
217                         print $client redirect("$url/client");
218                         return;
219                 } elsif ( $param->{action} eq 'change' ) {
220                         if ( my $new_ip = client::change_ip( $ip, $param->{change_ip} ) ) {
221                                 print $client redirect("$url/client#$new_ip");
222                                 return;
223                         }
224                 }
225
226                 if ( ! $ip ) {
227                         my $peer_ip = $client->peerhost;
228
229                         my $netmask  = ip::to_int $server::netmask;
230                         my $network  = ip::to_int($server::ip) & $netmask;
231                         my $from_int = $network | $server::ip_from;
232                         my $to_int   = $network | $server::ip_to;
233                         my $ip_int   = ip::to_int $peer_ip;
234
235                         # show edit for clients in our dhcp range
236                         if ( $ip_int >= $from_int && $ip_int <= $to_int ) {
237                                 $ip = $peer_ip;
238                         }
239                 }
240
241                 if ( $ip && $ip ne $server::ip ) {
242                         my $hostname = client::conf( $ip, 'hostname' => $param->{hostname} );
243
244                         my @table = (
245                                 'ip' => qq|<input type=text name=change_ip value="$ip" onChange="document.getElementById('old_ip').style.display = '';"><span id=old_ip style="display: none; color: #888;">old: $ip<span>|,
246                                 'hostname' => qq|<input type=text name=hostname value="$hostname">|,
247                                 'ping' => ping::host($ip) ? qq|<span style="color:green">up</span>| : qq|<a href=/wol/$ip title=wol>down</a>|,
248                         );
249
250                         my $config;
251
252                         if ( my $mac = client::mac_from_ip( $ip ) ) {
253                                 my $deploy = client::conf( $ip, 'deploy' => $param->{deploy} );
254                                 push @table, (
255                                         'mac' => format::mac( $mac => 'html' ),
256                                         'deploy' => html::select( 'deploy', $deploy, config::available )
257                                 );
258                                 if ( $config = config::for_ip( $ip ) ) {
259                                         $config = qq|<h2>config</h2>| . html::pre( $config );
260                                 }
261                         }
262
263                         print $client ok
264                                 , qq|<form method=get>|
265                                 , html::table( 2, @table ),
266                                 , qq|
267                                         <input type=submit name=action value=change>
268                                         <input type=submit name=action value=remove style="color: red">
269                                         </form>|
270                                 , $config
271                                 ;
272
273                         if ( my $amt = client::conf( $ip, 'amt' ) ) {
274                                 print $client qq|<h2>AMT</h2>|, amt::info( $amt, $ip );
275                         }
276
277                 } else {
278
279                         my @ping;
280                         if ( my $host = $param->{ping_target} ) {
281                                 @ping = ( $host );
282                         } elsif ( $param->{ping} ) {
283                                 @ping = client::all_ips;
284                         }
285
286                         my $ping = ping::fping( @ping ) if @ping;
287                         my $arp = client::arp_mac_dev;
288
289                         print $client ok
290                                 , qq|<h2>Clients on $server::ip</h2>|
291                                 , html::table( -6,
292                                         'ip', 'mac', 'dev', 'hostname', 'deploy', 'conf',
293                                         map {
294                                                 my $ip = $_;
295                                                 my $conf = client::all_conf( $ip );
296                                                 my $mac = delete $conf->{mac} || '';
297                                                 my $style;
298                                                 $style
299                                                         = 'style="color:'
300                                                         . ( $ping->{$ip} ? 'green' : 'red' )
301                                                         . '"'
302                                                         if $ping;
303                                                 $style ||= '';
304                                                 (
305                                                         qq|<a $style name=$ip href=/client/$ip>$ip</a>|
306                                                         , format::mac( $mac => 'html' )
307                                                         , $arp->{$mac}
308                                                         , delete $conf->{hostname}
309                                                         , delete $conf->{deploy}
310                                                         , ( %$conf ? html::pre_dump( $conf ) : qq|<a href=/nmap?scan=$ip>nmap</a>| )
311                                                 );
312                                         } client::all_ips
313                                 )
314                                 ;
315                         print $client qq|
316                                 <form method=get>
317                                 <input type=text   name=ping_target   size=15>
318                                 <input type=submit name=ping value=ping>
319                                 </form>
320                         |;
321                 }
322         } elsif ( $path =~ m{^/brctl} ) {
323                 print $client ok, html::table( -4,
324                         map {
325                                 my @c = split(/\t+/,$_,4);
326                                 if ( $#c == 1 ) {
327                                         ( '', '', '', $c[1] )
328                                 } else {
329                                         @c
330                                 }
331                         } split(/\n/, `brctl show`)
332                 );
333         } elsif ( $path =~ m{^/ip/?(\w+)?} ) {
334                 print $client ok
335                         , join("\n", map { qq|<a href=/ip/$_>$_</a>| } ( qw/link addr route neigh ntable tunnel maddr mroute xfrm/ ))
336                         , ip::html( $1 )
337                         ;
338         } elsif ( $path =~ m{^/nmap} ) {
339                 if ( my $scan = $param->{scan} ) {
340                         nmap::scan( $scan );
341                         print $client redirect("$url/client#$scan");
342                 } else {
343                         print $client ok, qq|
344                                 <form method=get>
345                                 <input type=text name=scan>
346                                 <input type=submit value=scan>
347                                 </form>
348                         |;
349                 }
350         } elsif ( $path =~ m{^/wol/(\S+)} ) {
351                 print $client redirect( "$url/client/$1" ), wol::power_on($1);
352         } elsif ( $path =~ m{^/our/(\w+)/(\S+)} ) {
353                 eval 'our $' . $1 . ' = ' . $2;
354                 warn $@ if $@;
355                 print $client redirect($url), qq|<big>$1 = $2</big><br>Location: <a href="$url">$url</a>|;
356                 server::debug( $debug ) if $1 eq 'debug';
357         } elsif ( $path =~ m{^/start_stop/(\S+)} ) {
358                 print $client redirect, daemons::start_stop($1);
359         } elsif ( $path =~ m{^/action/([^/]+)/(.+)} ) {
360                 $1->$2();
361                 print $client redirect;
362         } elsif ( $path =~ m{^/kill/static/(\d+)} ) {
363                 print $client redirect;
364                 kill 1, $1 || kill 9, $2 && warn "killed $1";
365         } else {
366                 print $client "HTTP/1.0 404 $path\r\nConnection: close\r\nContent-type: text/html\r\n\r\n<big>404 $path</big>";
367                 warn "404 $path";
368         }
369
370 }
371
372 sub start {
373
374         warn 'network ', network::setup();
375
376         daemons::start_stop 'browser', $url;
377         daemons::start_stop $_ foreach ( qw/dhcpd tftpd dnsd syslogd/ );
378         daemons::start_stop 'kvm' unless $ENV{DEV}; # skip kvm statup when running on real device
379
380         my $server = IO::Socket::INET->new(
381                         Proto     => 'tcp',
382                         LocalAddr => $server::ip,
383                         LocalPort => $httpd::port,
384                         Listen    => SOMAXCONN,
385                         Reuse     => 1
386         ) || die "can't start server on $url: $!";
387
388         print "url $url\n";
389
390         while (1) {
391                 my $client = $server->accept() || next; # ALARM trickle us
392                 my $request = <$client>;
393
394                 warn "request $request\n" if $debug;
395
396                 if ($request =~ m{^GET (/.*) HTTP/1.[01]}) {
397                         my $path = $1;
398                         $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
399                         my $param;
400                         if ( $path =~ s{\?(.+)}{} ) {
401                                 foreach my $p ( split(/[&;]/, $1) ) {
402                                         my ($n,$v) = split(/=/, $p, 2);
403                                         $param->{$n} = $v;
404                                 }
405                                 warn "param: ",dump( $param ) if $debug;
406                         }
407                         get_request $client, $path, $param;
408                 } else {
409                         print $client "HTTP/1.0 500 No method\r\nConnection: close\r\nContent-type: text/plain\r\n\r\n500 $request";
410                         warn "500 $request";
411                 }
412
413                 print $client menu() if $client->connected;
414
415         }
416
417         die "server died";
418 }
419
420 warn "loaded";
421
422 1;