#!/usr/bin/perl
# loadfw - Connect to SonicWALL and load current or uploaded firmware with default settings. Boot button does not work on Internet Explorer 8 and Firefox.
# Junya Keller / 20110305
# open_TCP: http://oreilly.com/openbook/webclient/ch04.html

############
# open_TCP #
############
#
# Given ($file_handle, $dest, $port) return 1 if successful, undef when
# unsuccessful.
#
# Input: $fileHandle is the name of the filehandle to use
#        $dest is the name of the destination computer,
#              either IP address or hostname
#        $port is the port number
#
# Output: successful network connection in file handle
#
 
use Socket;

sub open_TCP
{
  # get parameters
  my ($FS, $dest, $port) = @_;
 
  my $proto = getprotobyname('tcp');
  socket($FS, PF_INET, SOCK_STREAM, $proto);
  my $sin = sockaddr_in($port,inet_aton($dest));
  connect($FS,$sin) || return undef;
  
  my $old_fh = select($FS); 
  $| = 1; 		        # don't buffer output
  select($old_fh);
  1;
}
1;

# If no parameters were given, print out help text
if ($#ARGV) {
  print "Usage: $0 <cur|up>\n";
  print "\nConnect to SonicWALL and load current or uploaded firmware with default settings.\n";
  exit(-1);
} else {
 
# contact the server
  if (open_TCP(F, "192.168.168.168", 80) == undef) {
    print "Error: Connecting to http://192.168.168.168 failed. Check cabling and network settings.\n";
    exit(-1);
  }
 
# send request with "\r\n" after POST Data
  if ($ARGV[0] eq "cur") {
    print F "POST /boot.cgi HTTP/1.0\r\nHost: 192.168.168.168\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 11\r\n\r\nfile=curDef\r\n";
  } elsif ($ARGV[0] eq "up") {
    print F "POST /boot.cgi HTTP/1.0\r\nHost: 192.168.168.168\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 10\r\n\r\nfile=upDef\r\n";
  } else {
    print "Error: Unknown option.\n";
    close(F);
    exit(-1);
  }

# print out the response
  while ($_=<F>) {
    $lastline=$_;
  }
  if ($lastline eq '') {
    print "Error: Put SonicWALL into setup mode: Press and hold reset button until setup LED lights on.\n"
  } else {
    $lastline =~ s/.*Status: ([^<]*)<.*$/Error: $1/;
    $lastline =~ s/.*(The SonicWALL[^<]*)<.*$/Success: $1/;
    print "$lastline\n";
  }
  close(F);
}

