#!/usr/bin/perl

#########################################################################################
#											#
#	Test implementation of Smash protocol in perl for CGI use.			#
#	Based on a textbook TCP/IP client example. (Yess! Cut'nPaste really works!)	#
#	This comes without any warranties. Use at own risk.				#
#	There is no real number validator in here. 					#
#	JavaScript is just doing concatenation & length check..				#
#											#
#	You can envoke the script with query line parameters "number=46701234567"	#
#	and "message=Testing%20writing%20to%20the%20form" which is useful in links.	#
#	These override any defaults in config section...				#
#											#
#	<a href="/cgi-bin/smash?number=46701234567&message=Test">SMS</a>		#
#											#
#	Göran Ekeberg <goran@ekeberg.virtualave.net> 2001-09-04				#
#											#
#########################################################################################

#Small script config part...
 $port = 7077;					#Server port
 $them = '10.42.17.2';				#Server IP adress or name
 $scriptURL = "/cgi-bin/sms"; 			#Where am I?
 @operators = ("comviq",
 "telia",					#Operators hash.
 "europolitan");				#See server config for the ones 2 chose.
 #"other");					#The first one is default...
 $number = "4670";				#Consider NOT setting this value...
 $defaultmessage = "";				#Hmmm...
 
######################################################################################
 
#Config page appearence
 $pageheader = "
	<html>
	<head>
	<title>Smash CGI Client</title>
	<style type=\"text/css\">
,TD,TH,P,H4,LI,DD,OL,UL,DIV {font-family: Helvetica,sans-serif;
                                 font-size: 12pt;    
                                }
H1 	{font-family: Helvetica,sans-serif;
	font-size: 18pt;
	}
H2 	{font-family: Helvetica,sans-serif;
	font-size: 16pt;
	}
H3 	{font-family: Helvetica,sans-serif;
	font-size: 12pt;
	}
A  	{text-decoration: none;
	color: #000099;
	}
,FORM,INPUT,TEXTAREA,SELECT {font-family: Helvetica,sans-serif;
              font-size: 10pt;
	      }
	</style>


	</head>
	<body 
	bgcolor=FFFFFF
	alink = 000000
	link = 0000FF
	vlink = 0000FF>";
#End of page header stuff.
###########################################################################################

#End of config! Wear gloves below this line!


#Variables
$htmlheader = "content-type: text/html\n\n";

###########################################################################################

#Decode form data
  $i=0;
  if ($ENV{'QUERY_STRING'}) {
  $temp = $ENV{'QUERY_STRING'};
  } else {
  read(STDIN,$temp,$ENV{'CONTENT_LENGTH'});
  }
  @pairs=split(/&/,$temp);
  foreach $item(@pairs)
   {
    ($key,$content)=split(/=/,$item);           #   (/=/,$item,2);
    $content=~tr/+/ /;
    $content=~s/%(..)/pack("c",hex($1))/ge;
    $content =~ s/<!--(.|\n)*-->//g;
    $fields{$key}=$content;
    $i++;
   }
#End decode

###########################################################################################

#Control script action

if ($fields{sendit}) {
&resultpage($fields{number},$fields{message},$fields{operator});
} else {
&formpage($fields{number},$fields{message});
}
#End control

######################################################################################

# Make some form html from operators hash
sub makeselect {
my $select = "";
$select = "<OPTION VALUE=\'$operators[0]\'>Default\n";
shift @operators;
foreach $op (@operators) {

  $select .= "<OPTION VALUE=\'$op\'>" . ucfirst ($op) . "\n";
  }
  return $select;
}

###########################################################################################

#Print web form
sub formpage {
my ($num, $mess) = @_;
$number = $num if ($num);
$defaultmessage = $mess if ($mess);
$operator_select = &makeselect();
print $htmlheader;
print <<EOM;
$pageheader
	<script language=JavaScript>
	<!-- Hide for old browsers	
      function updatecount() {
        if (document.sendform.message.value != null) {
        var textlength = document.sendform.message.value.length;
        var amount = 160 - textlength;
        document.sendform.count.value = amount;
        }
      }

      function validate(input) {
      regexp = \/\[^\\d\]\/g;
      punumber = input.replace(regexp, \"\");
      document.sendform.number.value = punumber;
	numlength = document.sendform.number.value.length;
          if (numlength < 11 || numlength > 11) {
              alert ((\"Is this really international formatted?\\n \") + punumber);
              return 0;
              }
          return 1;
      }

      function test(phonenumber) {
      slush = validate(phonenumber);
      if (slush == 0){
      return 0;
      }
      updatecount();
      amount = document.sendform.count.value;

          if (amount >= 0) {
              document.sendform.submit();
              } else {
              alert((\"Hmmm... \\nMessage too long. \\nRemove \") + Math.abs(amount) + (\" characters\"));
              }
      }
      --> //Back again!
      </script>

<h3><img src=http://$them/bilder/phnse2.gif> SEND SMS</h3><p>
        <form name='sendform' method='POST' action=\'$scriptURL\'>
        GSM-nr: (Int'l formatted "46701234567")<br>
        <input name=number size=18 value='$number'><br>
        Message < 160 tecken:<br>
        <textarea name=message 
        cols=18 rows=8 wrap=no 
        language='JavaScript' onKeyUp='updatecount()'; onKeyDown='updatecount()'; onKeyPress='updatecount()'; onRowsDelete='updatecount()';>$defaultmessage</TEXTAREA><br>
        <!-- <input type='hidden' name='operator' value='$operators[0]'> -->
        Operator: <select name='operator'>
        $operator_select
        </select><br>
        <input type='hidden' name='sendit' value=1>
        Char's left: <input name='count' value='160' ReadOnly size=3>
        <input type=button name='send' value='Queue It!' Language='JavaScript' onClick='test(sendform.number.value)'>
        </form></p> </body>
</html>
EOM
}
#End formpage

###########################################################################################

#Send and print result page
sub resultpage {
my ($num, $mess, $op) = @_;
$response = &sendIt($num, $mess, $op);
$mess =~ s/\n/<br>/g;
print $htmlheader;
print <<EOM;
$pageheader
<h3>Have queued:<br>
\"$mess\"</h3>
<h3>To:<br>
$num via $op</h3>
<p>
<b>The server response was:</b><br>
$response
</p>
<p>
<b>=> <a href="$ENV{'SCRIPT_NAME'}">Return to form!</a></b><br>
<b>=> <a href=JavaScript:window.close()>Close window</a></b>
</p>
</html>
EOM
}
#End of send & results

###########################################################################################

#Client TCP/IP, protocol and send stuff.

sub sendIt {
my ($number, $mess, $operator) = @_;
use Socket;

chop($hostname = `hostname`);

($name, $aliases, $proto) = getprotobyname('tcp');

($name, $aliases, $port) = getservbyname($port,'tcp')
    unless $port =~ /^\d+$/;

#print "Using port $port to connect to SMaSh server on host $them...\n";

($name,$aliases,$type,$len,$thisaddr) = gethostbyname($hostname);

($name, $aliases,$type,$len,$thataddr) = gethostbyname($them);

if (socket(S,AF_INET, SOCK_STREAM, $proto)) {
#  print "Socket creation succeeded.\n";
   } else {
   die $!;
   }

$sockaddr = 'S n a4 x8';
$this = pack($sockaddr, AF_INET, 0, $thisaddr);
$that = pack($sockaddr, AF_INET, $port, $thataddr);

if (bind(S, $this)) {
#  print "Bind succeeded.\n";
   } else  {
   die $!;
   }
if (connect(S, $that)) {
#   print "Connected... ";
   } else {
   die $!;
   }

# Force our socket to flush output immediately after a print

select(S);
$| = 1;

# Make standard output the default again

select(STDOUT);

#Smash protocol formatting and population...

$linend = "\r\n";
$mess = $defaultmessage unless $mess;
$number = $defaultnumber unless $number;
#die $! unless $number;
$operator = $operators[0] unless $operator;


$header = "SENDMSG * SMASHP/1.0" .  $linend;
$header .= "Phone: $number" . $linend;
$header .= "Operator: $operator" . $linend;
$header .= "Content-Length: " . length($mess) . $linend;
$header .= "User-Agent: PerlSmash/0.1.0" . $linend . $linend;

$string = $header . "$mess";

#print "Sending:\n$string\n";
print S $string;

#Get reponse
    
    while (<S>) {
	#print "Server: $_";
	push (@servermessage, $_);
    }
    
$return = join("<br>", @servermessage);
return $return;

} 
# End of sub sendIt

######################################################################################

That's all, Folks
