Hi everyone, I've been 'commissioned' to write an application for primary schools that filters bad language from inbound email. I figured I'd write a PHP script that acts as fake POP server and sits between the client and the real POP server, filtering emails on the way through.
I've managed to get the script up and running but I'm concerned about its robustness and whether it can handle multiple connections at the same time. Is this even possible with PHP or am I barking up the wrong tree here?
Here it is so far:
<?
// run with "php -q this.php"
// don't timeout
set_time_limit (0);
// this is the 'fake' POP server
$host = "127.0.0.1";
$port = 110;
// this is the 'real' pop server
$destHost="mail.sample.com";
$destPort = 110;
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "Waiting for connections...\n";
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Received connection request\n";
// open a client connection
$destFp = fsockopen ($destHost, $destPort, $destErrno, $destErrstr);
// send first reply to client
$welcome = fgets ($destFp, 150);
socket_write($spawn, $welcome, strlen($welcome)) or die("Could not write client output\n");
echo "Send to client: ". $welcome;
// keep looping and looking for client input
do
{
$tmpData = "";
while(($buf = socket_read($spawn, 512)) !== false) {
$tmpData .= $buf;
if(strpos($tmpData,"\r\n")) break;
}
$input = $tmpData;
echo "Recv from client: ". $input;
// send client command to dest
echo "Send to dest: ". $input;
fputs ($destFp, $input);
// read response from dest
$destRecv = "";
$terminator = "\r\n";
while(strpos($destRecv,$terminator)===false) {
$destRecv .= fgets ($destFp, 50);
if (strpos($destRecv, " follow.") > 0) $terminator = "\r\n.\r\n";
}
echo "Recv from dest: ". $destRecv;
// FILTER LANGUAGE HERE
// send to client
socket_write($spawn, $destRecv, strlen($destRecv)) or die("Could not write client output\n");
echo "Send to client: ". $destRecv;
} while (true);
// close primary socket
socket_close($socket);
echo "Socket terminated\n";
?>