The snippet is from importMsnm.class.php,$data = $this->_get(); returns false on the 2nd time of loop, it worked before :
VER 1 MSNP9 CVR0
VER 1 CVR0
CVR 1 0x0409 win 4.10 i386 MSNMSGR 7.0.0816 MSMSGS username#hotmail.com
connection is lost
function connect($passport, $password)
{
$this->trID = 1;
if (!$this->fp = #fsockopen($this->server, $this->port, $errno, $errstr, 2)) {
//die("Could not connect to messenger service");
return array();
} else {
stream_set_timeout($this->fp, 2);
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
while (! feof($this->fp))
{
$data = $this->_get();
switch ($code = substr($data, 0, 3))
{
default:
//echo $this->_get_error($code);
return false;
break;
case 'VER':
$this->_put("CVR $this->trID 0x0409 win 4.10 i386 MSNMSGR 7.0.0816 MSMSGS $passport\r\n");
break;
case 'CVR':
$this->_put("USR $this->trID TWN I $passport\r\n");
break;
case 'XFR':
list(, , , $ip) = explode (' ', $data);
list($ip, $port) = explode (':', $ip);
if ($this->fp = #fsockopen($ip, $port, $errno, $errstr, 2))
{
$this->trID = 1;
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
}
else
{
if (! empty($this->debug)) echo 'Unable to connect to msn server (transfer)';
return false;
}
break;
case 'USR':
if (isset($this->authed))
{
return true;
}
else
{
$this->passport = $passport;
$this->password = urlencode($password);
list(,,,, $code) = explode(' ', trim($data));
if ($auth = $this->_ssl_auth($code))
{
$this->_put("USR $this->trID TWN S $auth\r\n");
$this->authed = 1;
}
else
{
if (! empty($this->debug)) echo 'auth failed';
return false;
}
}
break;
}
}
}
}
It seems like they've once again locked out old clients. Microsoft do this once in a while to make third party clients unusable. Their standard way of handling protocol exceptions is to immediately tearing down the connection.
Related
I figured I'd test the new PHP 7.2 release to see how many problems it creates on my site (I've been using 7.1 before this without trouble) and I noted that it appeared to disrupt the MySQL database connection in the Dp.php file for one of my scripts with the following error:
An exception occurred: count(): Parameter must be an array or an object that implements Countable in /../Db.php on line 57
The code it references is this bit:
if (!count($dsn)) {
return $parsed;
}
I believe this is related to the 'counting non-countable types' change in 7.2 (http://php.net/manual/en/migration72.incompatible.php) and thing its probably due to a "null" value but I'm no expert in PHP and am not sure how to fix it. Just for context, here's the full code block that relates to $dsn in the Dp.php file:
class Censura_Db
{
protected $connected_server_info; //cache for server information
public static function factory($dsn, $options = false)
{
$class = new self($dsn, $options);
return $class;
}
public static function parseDSN($dsn)
{
$parsed = array();
if (is_array($dsn)) {
$dsn = array_merge($parsed, $dsn);
if (!$dsn['dbsyntax']) {
$dsn['dbsyntax'] = $dsn['phptype'];
}
return $dsn;
}
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 3);
} else {
$str = $dsn;
$dsn = null;
}
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1];
$parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
} else {
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
}
if (!count($dsn)) {
return $parsed;
}
// Get (if found): username and password
// $dsn => username:password#protocol+hostspec/database
if (($at = strrpos($dsn, '#')) !== false) {
$str = substr($dsn, 0, $at);
$dsn = substr($dsn, $at + 1);
if (($pos = strpos($str, ':')) !== false) {
$parsed['username'] = rawurldecode(substr($str, 0, $pos));
$parsed['password'] = rawurldecode(substr($str, $pos + 1));
} else {
$parsed['username'] = rawurldecode($str);
}
}
// Find protocol and hostspec
// $dsn => proto(proto_opts)/database
if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
$proto = $match[1];
$proto_opts = $match[2] ? $match[2] : false;
$dsn = $match[3];
// $dsn => protocol+hostspec/database (old format)
} else {
if (strpos($dsn, '+') !== false) {
list($proto, $dsn) = explode('+', $dsn, 2);
}
if (strpos($dsn, '//') === 0
&& strpos($dsn, '/', 2) !== false
&& $parsed['phptype'] == 'oci8'
) {
//oracle's "Easy Connect" syntax:
//"username/password#[//]host[:port][/service_name]"
//e.g. "scott/tiger#//mymachine:1521/oracle"
$proto_opts = $dsn;
$dsn = null;
} elseif (strpos($dsn, '/') !== false) {
list($proto_opts, $dsn) = explode('/', $dsn, 2);
} else {
$proto_opts = $dsn;
$dsn = null;
}
}
// process the different protocol options
$parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
$proto_opts = rawurldecode($proto_opts);
if (strpos($proto_opts, ':') !== false) {
list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
}
if ($parsed['protocol'] == 'tcp') {
$parsed['hostspec'] = $proto_opts;
} elseif ($parsed['protocol'] == 'unix') {
$parsed['socket'] = $proto_opts;
}
// Get dabase if any
// $dsn => database
if ($dsn) {
// /database
if (($pos = strpos($dsn, '?')) === false) {
$parsed['database'] = $dsn;
// /database?param1=value1¶m2=value2
} else {
$parsed['database'] = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 1);
if (strpos($dsn, '&') !== false) {
$opts = explode('&', $dsn);
} else { // database?param1=value1
$opts = array($dsn);
}
foreach ($opts as $opt) {
list($key, $value) = explode('=', $opt);
if (!isset($parsed[$key])) {
// don't allow params overwrite
$parsed[$key] = rawurldecode($value);
}
}
}
}
return $parsed;
}
You're using count() on values that aren't arrays, apparently to check if they are null.
Use !== null or isset() instead.
When i run my code and type in (hello) or (hi) the Client is disconnected and i get this error from the server:
��r�W� not understood
This is my Server's code:
#!/php -q
<?php /* >php -q server.php */
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
$master = WebSocket("localhost",12345);
$sockets = array($master);
$users = array();
$debug = false;
while(true){
$changed = $sockets;
$write = NULL;
$except = NULL;
socket_select($changed, $write, $except, NULL);
foreach($changed as $socket){
if($socket==$master){
$client=socket_accept($master);
if($client<0){ console("socket_accept() failed"); continue; }
else{ connect($client); }
}
else{
$bytes = #socket_recv($socket,$buffer,2048,0);
if($bytes==0){ disconnect($socket); }
else{
$user = getuserbysocket($socket);
if(!$user->handshake){ dohandshake($user,$buffer); }
else{ process($user,$buffer); }
}
}
}
}
//---------------------------------------------------------------
function process($user,$msg){
$action = unwrap($msg);
say("< ".$action);
switch($action){
case "hello" : send($user->socket,"hello human"); break;
case "hi" : send($user->socket,"zup human"); break;
case "name" : send($user->socket,"my name is Multivac, silly I know"); break;
case "age" : send($user->socket,"I am older than time itself"); break;
case "date" : send($user->socket,"today is ".date("Y.m.d")); break;
case "time" : send($user->socket,"server time is ".date("H:i:s")); break;
case "thanks": send($user->socket,"you're welcome"); break;
case "bye" : send($user->socket,"bye"); break;
default : send($user->socket,$action." not understood"); break;
}
}
function send($client,$msg){
say("> ".$msg);
$msg = wrap($msg);
socket_write($client,$msg,strlen($msg));
}
function WebSocket($address,$port){
$master=socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("socket_create() failed");
socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1) or die("socket_option() failed");
socket_bind($master, $address, $port) or die("socket_bind() failed");
socket_listen($master,20) or die("socket_listen() failed");
echo "Server Started : ".date('Y-m-d H:i:s')."\n";
echo "Master socket : ".$master."\n";
echo "Listening on : ".$address." port ".$port."\n\n";
return $master;
}
function connect($socket){
global $sockets,$users;
$user = new User();
$user->id = uniqid();
$user->socket = $socket;
array_push($users,$user);
array_push($sockets,$socket);
console($socket." CONNECTED!");
}
function disconnect($socket){
global $sockets,$users;
$found=null;
$n=count($users);
for($i=0;$i<$n;$i++){
if($users[$i]->socket==$socket){ $found=$i; break; }
}
if(!is_null($found)){ array_splice($users,$found,1); }
$index = array_search($socket,$sockets);
socket_close($socket);
console($socket." DISCONNECTED!");
if($index>=0){ array_splice($sockets,$index,1); }
}
function dohandshake($user, $buffer) {
$key = null;
console("\nRequesting handshake...");
console($buffer);
console("Handshaking...");
preg_match("#Sec-WebSocket-Key: (.*?)\r\n#", $buffer, $match) && $key = $match[1];
$key .= "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
$key = sha1($key);
$key = pack('H*', $key);
$key = base64_encode($key);
$upgrade =
"HTTP/1.1 101 Switching Protocols\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"Sec-WebSocket-Accept: {$key}\r\n\r\n";
socket_write($user->socket, $upgrade . chr(0), strlen($upgrade . chr(0)));
$user->handshake = true;
console($upgrade);
console("Done handshaking...");
return true;
}
function getheaders($header) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach ($fields as $field) {
if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if (isset($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
if (preg_match("/GET (.*) HTTP/", $header, $match)) {
$retVal['GET'] = $match[1];
}
return $retVal;
}
function getuserbysocket($socket){
global $users;
$found=null;
foreach($users as $user){
if($user->socket==$socket){ $found=$user; break; }
}
return $found;
}
function say($msg=""){ echo $msg."\n"; }
function wrap($msg=""){ return chr(0).$msg.chr(255); }
function unwrap($msg=""){ return substr($msg,1,strlen($msg)-2); }
function console($msg=""){ global $debug; if($debug){ echo $msg."\n"; } }
class User{
var $id;
var $socket;
var $handshake;
}
?>
This is how it looks on the Client's side:
WebSocket - status 0
Welcome - status 1
Sent: hi
Disconnected - status 3
Can anyone here help ?
Is there any way (other than checking for ping responses) to detect when a client stream (I don't know if a stream would be any different from sockets) becomes unavailable (ie there is no longer any connection but no clean disconnection was made)?
Using this code:
#!/usr/bin/env php
<?php
$socket = stream_socket_server(
'tcp://192.168.1.1:47700',
$errno,
$errstr,
STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
stream_context_create(
array(),
array()
)
);
if (!$socket) {
echo 'Could not listen on socket'."\n";
}
else {
$clients = array((int)$socket => $socket);
$last = time();
while(true) {
$read = $clients;
$write = null;
$ex = null;
stream_select(
$read,
$write,
$ex,
5
);
foreach ($read as $sock) {
if ($sock === $socket) {
echo 'Incoming on master...'."\n";
$client = stream_socket_accept(
$socket,
5
);
if ($client) {
stream_set_timeout($client, 1);
$clients[(int)$client] = $client;
}
}
else {
echo 'Incoming on client '.((int)$sock)."...\n";
$length = 1400;
$remaining = $length;
$buffer = '';
$metadata['unread_bytes'] = 0;
do {
if (feof($sock)) {
break;
}
$result = fread($sock, $length);
if ($result === false) {
break;
}
$buffer .= $result;
if (feof($sock)) {
break;
}
$continue = false;
if (strlen($result) == $length) {
$continue = true;
}
$metadata = stream_get_meta_data($sock);
if ($metadata && isset($metadata['unread_bytes']) && $metadata['unread_bytes']) {
$continue = true;
$length = $metadata['unread_bytes'];
}
} while ($continue);
if (strlen($buffer) === 0 || $buffer === false) {
echo 'Client disconnected...'."\n";
stream_socket_shutdown($sock, STREAM_SHUT_RDWR);
unset($clients[(int)$sock]);
}
else {
echo 'Received: '.$buffer."\n";
}
echo 'There are '.(count($clients) - 1).' clients'."\n";
}
}
if ($last < (time() - 5)) {
foreach ($clients as $id => $client) {
if ($client !== $socket) {
$text = 'Yippee!';
$ret = fwrite($client, $text);
if ($ret !== strlen($text)) {
echo 'There seemed to be an error sending to the client'."\n";
}
}
}
}
}
}
if ($socket) {
stream_socket_shutdown($socket, STREAM_SHUT_RDWR);
}
and a sockets client on a different computer, I can connect to the server, send and receive data, and disconnect cleanly and everything functions as expected. If, however, I pull the network connection on the client computer, nothing is detected on the server side - the server keeps on listening to the client socket, and also writes to it without any error manifesting itself.
As I understand it, calling feof($stream) will tell you if the remote socket disconnected, but I'm not absolutely certain about that. I'm using ping/pong myself while continuing to research a solution.
You need to set a socket timeout, in which case you get an error if a client does not respond in a timely fashion.
Check PHP's stream_set_timeout function:
http://www.php.net/manual/en/function.stream-set-timeout.php
Also check socket_set_option:
http://php.net/manual/en/function.socket-set-option.php
and finally, check out this great article on how to use sockets in PHP effectively:
"PHP Socket Programming, done the Right Way™"
http://christophh.net/2012/07/24/php-socket-programming/
I am writing a WebSocket server. While handshaking is successful and server can send encoded data using RFC standard, socket_select() can only detect changes when a new client is connected, not when the client send data to the server. What is happening?
class Server{
private $address;
private $port;
private $master;
private $sockets;
private $stream_sockets;
private $clients;
private $verbose_mode;
function __construct($address = '127.0.0.1', $port = 5001, $verbose_mode = true){
$this->address = $address;
$this->port = $port;
$this->verbose_mode = $verbose_mode;
$this->console("Socket server is starting...");
//socket creation
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1))
{
$this->console("Failed to set socket option: ".socket_strerror(socket_last_error()));
}
if(!socket_set_nonblock($socket))
{
$this->console("Failed to set socket nonblock: ".socket_strerror(socket_last_error()));
}
if(!is_resource($socket))
{
$this->console("Failed to create socket: ".socket_strerror(socket_last_error()));
}
if(!socket_bind($socket, $this->address, $this->port))
{
$this->console("Failed to bind socket: ".socket_strerror(socket_last_error()));
}
if(!socket_listen($socket, 20))
{
$this->console("Failed to listen: ".socket_strerror(socket_last_error()));
}
$this->master = $socket; //add current socket resource as master socket
$this->sockets = array($socket);//add current resource to all sockets
$this->console("Socket server started on {$this->address}:{$this->port}");
}
public function run(){
$this->console("Start running...");
$write = array();
$except = array();
while(isset($this->sockets[0])){
$changed_sockets = $this->sockets;
$result = socket_select($changed_sockets, $write, $except, 1 ,0);
//#stream_select($changed_sockets, $write = null, $except = null, 0, 5000);
if($result > 0)
{
$this->console("number of sockets: ".count($this->sockets));
$this->console("number of changed sockets: ".$result);
foreach($changed_sockets as $socket)
{
if($socket == $this->master)//self changed
{
if(($accepted_socket = socket_accept($this->master))!== false)//incoming connection
{
$this->connect($accepted_socket);//add as a client to the pool with info to be tracked without handshaking at first
}
else
{
$this->console("Socket error: ".socket_strerror(socket_last_error()));
}
}
else //must be others in sockets pool
{
$this->console("Finding socket associated with the client...");
$client = $this->get_client_by_socket($socket); //get client object to track them using socket that they are associated with
if($client){
$this->console("receiving data from the client.");
$bytes = #socket_recv($socket, $data, 2048, MSG_DONTWAIT);
$this->console("byte size received: $bytes");
if(!$client->get_handshake())//check if handshaking has done
{
$this->console("handshaking...");
$this->handshake($client, $data);//handshaking if it is not done previously
}
else if($bytes === 0)
{
$this->disconnect($client);
}
else
{
$this->console("incoming data from client {client->get_id()}");
$this->read($client, $data);//read from client if there are changes in sockets
}
}
}
}
}
}
}
private function slingshot($client, $read){
$send="00:00:00:00".",DM,SAY,0,".$read;
fwrite($client->get_stream_socket(), $send);//output to apollo
//workaround for apollo
if($client->get_initial())
{
$initial = 7;
$continue = 0;
}
else
{
$initial = 8;
$continue = 1;
}
while(TRUE)
{
//input from iris
$num = fgets($client->get_stream_socket(), $initial);//$number of words
if(ltrim($num) > 0)
{
$res = fgets($client->get_stream_socket(), ltrim($num)+1);
if($res!="")
{
fgets($fp,1);
$client->set_initial(false);
$res = $num.$res;
$res = substr($res,6+$continue);
//output to client
$message = rtrim($res);
send($client, $message);
break;
}
}
}
}
private function read($client, $received){
$read = $this->unmask($received);
$this->console("received from client: ".$read);
if($read == "##client exit##") {
$this->console("Killing a child process");
posix_kill($client->get_pid(), SIGTERM);
$this->console("Process {$client->get_pid()} is terminated.");
}
else
{
$this->console("start a child process");
$pid = pcntl_fork();
if($pid == -1)
{
die('could not fork.');
}
else if($pid)
{
$client->set_pid($pid);
}
else
{
//we are the child
$this->slingshot($client, $read);
}
}
}
private function disconnect($client){
$this->console("Disconnecting client #{$client->get_id()}");
$i = array_search($client, $this->clients);//search client in clients pool
$j = array_search($client->get_socket(), $this->sockets);//search client's socket in socket pool
if($j >= 0)
{
array_splice($this->sockets, $j, 1);
socket_close($client->get_socket());
$this->console("Socket closed.");
}
if($i >= 0)
{
array_splice($this->clients, $i, 1);
}
$this->console("Client #{$client->get_id()} disconnected.");
}
private function unmask($payload) {
$length = ord($payload[1]) & 127;
if($length == 126)
{
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
}
elseif($length == 127)
{
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
}
else
{
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
}
$text = '';
for ($i = 0; $i < strlen($data); ++$i){
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
private function encode($text){
// 0x1 text frame (FIN + opcode)
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
{
$header = pack('CC', $b1, $length);
}
elseif($length > 125 && $length < 65536)
{
$header = pack('CCS', $b1, 126, $length);
}
elseif($length >= 65536)
{
$header = pack('CCN', $b1, 127, $length);
}
return $header.$text;
}
private function send($client, $text){
$this->console("Client {$client->get_id()}<<".$text);
$text = $this->encode($text);
if(socket_write($client->get_socket(), $text, strlen($text)) === false) {
$this->console("Unable to write to client #{$client->get_id()}'s socket");
$this->disconnect($client);
}
}
private function start_process(){
$this->console("start a child process");
$pid = pcntl_fork();
if($pid == -1)
{
die('could not fork.');
}
else if($pid)
{
$client->set_pid($pid);
}
else
{
//we are the child
$this->send($client, "something to be sent.");
}
}
private function handshake($client, $headers){//data as headers
$this->console("Getting client WebSocket version...");
if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
{
$version = $match[1];
}
else
{
$this->console("The client doesn't support WebSocket.");
}
$this->console("Client WebSocket version is {$version}, (required: 13)");
if($version == 13)
{
$this->console("Getting headers...");
if(preg_match("/GET (.*) HTTP/", $headers, $match))
{
$root = $match[1];
}
if(preg_match("/Host: (.*)\r\n/", $headers, $match))
{
$host = $match[1];
}
if(preg_match("/Origin: (.*)\r\n/", $headers, $match))
{
$origin = $match[1];
}
if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
{
$key = $match[1];
}
$this->console("client Headers are:");
$this->console("\t- Root: ".$root);
$this->console("\t- Host: ".$host);
$this->console("\t- Origin: ".$origin);
$this->console("\t- Sec-WebSocket-Key: ".$key);
$this->console("Generating Sec-WebSocket-Accept key...");
$acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Sec-WebSocket-Accept: $acceptKey".
"\r\n\r\n";
$this->console("sending this response to the client #{$client->get_id()}:\r\n".$upgrade);
socket_write($client->get_socket(), $upgrade);
$client->set_handshake(true);
$this->console("Handshake is successfully done!");
return true;
}
else
{
$this->console("WebSocket version 13 is required (the client supports version {$version})");
return false;
}
}
private function get_client_by_socket($socket){
foreach($this->clients as $client)//get all client objects from the pool and check one by one
{
if($client->get_socket() == $socket)//if socket returned from the client matches with parameter
{
$this->console("client found");
return $client;
}
}
return false;//no such client
}
private function connect($socket){
$this->console("creating client...");
$client_id = uniqid();
while(true){
$stream_socket = #stream_socket_client("tcp://127.0.0.1:10000", $errno, $errstr);
if($stream_socket)
{
$this->console("Apollo client created for client #$client_id.");
break;
}
else
{
$this->console("creation failed. Attempting to recreate Apollo client.");
}
}
$client = new Client($client_id, $socket, $stream_socket);
$this->clients[] = $client; //add the socket as client to be tracked
$this->sockets[] = $socket;//add socket as resource to sockets pool
$this->stream_sockets[] = $stream_socket;//add socket as resource to stream sockets pool
$this->console("Client #{$client->get_id()} is successfully created!");
}
private function console($text, $continue = true){
if(!$continue)
{
die($text);
}
if($this->verbose_mode)
{
echo date('[Y-m-d H:i:s] ').$text."\r\n";
}
}
}
That's because you have to accept the new incoming connection using socket_accept(), passing in the socket you've used for socket_listen().
The resulting socket can be used to check for incoming data as expected.
Edit
It seems that you forgot to add $write = $this->sockets; before your call to socket_select().
I figured out that to enable the socket select to detect data from the client, socket server has to send a dummy message to the client first immediately after handshake.
Im having problem in importing hotmail contacts from hotmail in php it simple give the erorr message : Error code not found
Please tell me what im doing wrong. I want this to be working.
Im using thew msn_contact_grab.class.php
and iam calling as :
<?php
include('msn_contact_grab.class.php');
$msn2 = new msn;
$returned_emails = $msn2->qGrab("just_4_love01#hotmail.com", "xxxxxxx");
?>
msn_contact_grab.class.php is as follows:
<?php
class msn
{
var $server = 'messenger.hotmail.com';
var $port = 1863;
var $nexus = 'https://nexus.passport.com/rdr/pprdr.asp';
var $ssh_login = 'login.live.com/login2.srf';
var $debug = 0;
var $curl_bin = 0;
var $curl = 'c:/wamp/www/hotmail/curl/curl'; // linux
//var $curl = 'c:\curl.exe'; // windows
//Used to prevent the script from hanging
var $count = 0;
//Used to store the email addresses until all have been collected
var $email_input = array();
var $email_processing = array();
var $email_output = array();
/**
*
* desc : Connect to MSN Messenger Network
*
* in : $passport = passport i.e: user#hotmail.com
* $password = password for passport
*
* out : true on success else return false
*
*/
function connect($passport, $password)
{
$this->trID = 1;
if (!$this->fp = #fsockopen($this->server, $this->port, $errno, $errstr, 2)) {
die("Could not connect to messenger service");
} else {
stream_set_timeout($this->fp, 2);
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
while (! feof($this->fp))
{
$data = $this->_get();
switch ($code = substr($data, 0, 3))
{
default:
echo $this->_get_error($code);
return false;
break;
case 'VER':
$this->_put("CVR $this->trID 0x0409 win 4.10 i386 MSNMSGR 7.0.0816 MSMSGS $passport\r\n");
break;
case 'CVR':
$this->_put("USR $this->trID TWN I $passport\r\n");
break;
case 'XFR':
list(, , , $ip) = explode (' ', $data);
list($ip, $port) = explode (':', $ip);
if ($this->fp = #fsockopen($ip, $port, $errno, $errstr, 2))
{
$this->trID = 1;
$this->_put("VER $this->trID MSNP9 CVR0\r\n");
}
else
{
if (! empty($this->debug)) echo 'Unable to connect to msn server (transfer)';
return false;
}
break;
case 'USR':
if (isset($this->authed))
{
return true;
}
else
{
$this->passport = $passport;
$this->password = urlencode($password);
list(,,,, $code) = explode(' ', trim($data));
if ($auth = $this->_ssl_auth($code))
{
$this->_put("USR $this->trID TWN S $auth\r\n");
$this->authed = 1;
}
else
{
if (! empty($this->debug)) echo 'auth failed';
return false;
}
}
break;
}
}
}
}
//Collects the raw data containing the email addresses
function rx_data()
{
$this->_put("SYN $this->trID 0\r\n");
//Supplies the second MSG code which stops
//the script from hanging as it waits for
//more content
$this->_put("CHG $this->trID NLN\r\n");
$stream_info = stream_get_meta_data($this->fp);
$email_total = 100;
//the count check prevents the script hanging as it waits for more content
while ((! feof($this->fp)) && (! $stream_info['timed_out']) && ($this->count <= 1) && (count($this->email_input) < $email_total))
{
$data = $this->_get();
$stream_info = stream_get_meta_data($this->fp);
if ($data)
{
switch($code = substr($data, 0, 3))
{
default:
// uncommenting this line here would probably give a load of "error code not found" messages.
//echo $this->_get_error($code);
break;
case 'MSG':
//This prevents the script hanging as it waits for more content
$this->count++;
break;
case 'LST':
//These are the email addresses
//They need to be collected in email_input
$this->email_input[] = $data;
if ($this->debug) print("<span class='b'>" . count($this->email_input) . "</span>");
break;
case 'SYN':
$syn_explode = explode(" ", $data);
$email_total = $syn_explode[3];
break;
case 'CHL':
$bits = explode (' ', trim($data));
$return = md5($bits[2].'Q1P7W2E4J9R8U3S5');
$this->_put("QRY $this->trID msmsgs#msnmsgr.com 32\r\n$return");
break;
}
}
}
}
//This function extracts the emails and screen names from the raw data
//collected by rx_data
function process_emails () {
//Neaten up the emails
//$regex = "|^LST\s(\S+?)\s(\S+?)\s\d+?\s\d+?$|";
foreach($this->email_input as $email_entry) {
//Seperate out the email from the name and other data
$this->email_processing[] = explode(" ", $email_entry);
}
//Get rid of the unnecessary data and clean up the name
foreach($this->email_processing as $email_entry){
$this->email_output[] = array(0 => $email_entry['1'],
1 => urldecode($email_entry[2]));
}
//var_dump($this->email_processing);
//var_dump($this->email_output);
}
//This is a quick way of calling all the seperate functions
//needed to grab the contact list
function qGrab ($username, $password) {
//Connect to the MSNM service
$this->connect($username, $password);
//Get data
$this->rx_data();
//Process emails
$this->process_emails();
//send the email array
return $this->email_output;
}
/*====================================*\
Various private functions
\*====================================*/
function _ssl_auth($auth_string)
{
if (empty($this->ssh_login))
{
if ($this->curl_bin)
{
exec("$this->curl -m 60 -LkI $this->nexus", $header);
$header = implode($header, null);
}
else
{
$ch = curl_init($this->nexus);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$header = curl_exec($ch);
curl_close($ch);
}
preg_match ('/DALogin=(.*?),/', $header, $out);
if (isset($out[1]))
{
$slogin = $out[1];
}
else
{
return false;
}
}
else
{
$slogin = $this->ssh_login;
}
if ($this->curl_bin)
{
$header1 = '"Authorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in='.$this->passport.',pwd='.$this->password.','.$auth_string.'"';
exec("$this->curl -m 60 -LkI -H $header1 https://$slogin", $auth_string);
$header = null;
foreach ($auth_string as $key => $value)
{
if (strstr($value, 'Unauthorized'))
{
echo 'Unauthorised';
return false;
}
elseif (strstr($value, 'Authentication-Info'))
{
$header = $value;
}
}
}
else
{
$ch = curl_init('https://'.$slogin);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in='.$this->passport.',pwd='.$this->password.','.$auth_string,
'Host: login.passport.com'
));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$header = curl_exec($ch);
curl_close($ch);
}
preg_match ("/from-PP='(.*?)'/", $header, $out);
return (isset($out[1])) ? $out[1] : false;
}
function _get()
{
if ($data = #fgets($this->fp, 4096))
{
if ($this->debug) echo "<div class=\"r\"><<< $data</div>\n";
return $data;
}
else
{
return false;
}
}
function _put($data)
{
fwrite($this->fp, $data);
$this->trID++;
if ($this->debug) echo "<div class=\"g\">>>> $data</div>";
}
function _get_error($code)
{
switch ($code)
{
case 201:
return 'Error: 201 Invalid parameter';
break;
case 217:
return 'Error: 217 Principal not on-line';
break;
case 500:
return 'Error: 500 Internal server error';
break;
case 540:
return 'Error: 540 Challenge response failed';
break;
case 601:
return 'Error: 601 Server is unavailable';
break;
case 710:
return 'Error: 710 Bad CVR parameters sent';
break;
case 713:
return 'Error: 713 Calling too rapidly';
break;
case 731:
return 'Error: 731 Not expected';
break;
case 800:
return 'Error: 800 Changing too rapidly';
break;
case 910:
case 921:
return 'Error: 910/921 Server too busy';
break;
case 911:
return 'Error: 911 Authentication failed';
break;
case 923:
return 'Error: 923 Kids Passport without parental consent';
break;
case 928:
return 'Error: 928 Bad ticket';
break;
default:
return 'Error code '.$code.' not found';
break;
}
}
}
?>
(moving this from a comment to an answer)
It's probably not that you are doing anything wrong, it's probably just that this class is fishy. The $curl = 'c:/...'; // linux line doesn't instill a lot of confidence. This also seems to be reverse-engineering the messenger protocol, which is a very fragile thing to do.
There seems to be an official API, which you should be using instead: http://dev.live.com/contacts/