#!/usr/bin/perl -w

use strict;

# Make sure the output is valid 
print  "Content-type: text/html\n\n";
print "<html><body>\n";

my $ip = $ENV{'REMOTE_ADDR'};
my $mac = "";

# Test to make sure the client is on the known wireless net.
if ( (! defined($ENV{'REMOTE_ADDR'}) ) || ( $ENV{'REMOTE_ADDR'} !~ /10.0.1./ ) ) {
  print "Sorry.. this page is only for people on my wireless net<br>\n";
} else {
  #print "Your IP: $ENV{'REMOTE_ADDR'}<br>\n";
  $mac = get_mac($ENV{'REMOTE_ADDR'});
  #print "Your MAC: $mac<br>\n"
  print_auth_form();
}
print "</body></html>\n";


# Small subroutine that takes the ip of a host, and uses arp
#  to get the host's Mac addr.
sub get_mac {
  my $ip = shift;
  my $mac = "";

  open(ARP," /sbin/arp $ip|") || die "Can't run arp";
  while (<ARP>) {
    if ( /$ip\s+ether\s+(.*)\s+C\s+eth2/ ) {
      $mac = $1;
    }
  }
  close(ARP);
  return $mac;
}

# Print out the basic auth form and submit button.  
#  Nothing fancy here, no colors, styles, etc.
sub print_auth_form {
  print "
  <form method=post action=https://10.0.1.1/wireless_auth/auth.cgi>
  <table>
    <tr>
      <td>
        Username:
      </td>
      <td>
        <input type=text name=user_name>
      </td>
    </tr>
    <tr>
      <td>
        Password:
      </td>
      <td>
        <input type=password name=user_pass>
      </td>
    </tr>
    <tr colspan=2>
      <td>
         <input type=submit value=Go onclick=mungeChars(this.form)>
      </td>
    </tr>
    <input type=hidden name=rem_ip value=\"$ip\">
    <input type=hidden name=rem_mac value=\"$mac\">
  </table>
  </form>
  ";
}